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                // A footprint of zero, which asks the chunk gate for the full
331                // slack. The gate exists to price the re-reads extra chunks cost,
332                // and on a single column of panels there are none: each chunk
333                // covers a disjoint band of A, and the one B panel every chunk
334                // re-reads is a vector.
335                0,
336                0,
337                |ia_start, ia_end, _, _, _| {
338                    scratch.run_in_tls_scope(|scratch, tls| {
339                        for ia in ia_start..ia_end {
340                            scratch.run_one_tile(ker, non_linear, tls, ia, 0)?;
341                        }
342                        TractResult::Ok(())
343                    })
344                },
345            ),
346            #[cfg(feature = "multithread-mm")]
347            Executor::RayonGlobal => chunked_dispatch_rayon(
348                None,
349                m.divceil(ker.mr()),
350                1,
351                ker.mr(),
352                ker.nr(),
353                // A footprint of zero, which asks the chunk gate for the full
354                // slack. The gate exists to price the re-reads extra chunks cost,
355                // and on a single column of panels there are none: each chunk
356                // covers a disjoint band of A, and the one B panel every chunk
357                // re-reads is a vector.
358                0,
359                0,
360                |ia_start, ia_end, _, _, _| {
361                    scratch.run_in_tls_scope(|scratch, tls| {
362                        for ia in ia_start..ia_end {
363                            scratch.run_one_tile(ker, non_linear, tls, ia, 0)?;
364                        }
365                        TractResult::Ok(())
366                    })
367                },
368            ),
369        }
370    }
371}
372
373/// Upper bound on the inner (L2-resident) panel-block edge.
374const BLK_MAX: usize = 16;
375
376/// Upper bound on the outer (L3-resident) super-block edge. 4× the inner cap so
377/// an L3 several times larger than L2 can hold a meaningfully bigger super-block.
378const BLK_L3_MAX: usize = 64;
379
380/// Panel-block working-set budget (bytes) from a detected cache size: a fraction
381/// `num/den` of the cache (leaving room for the C accumulator tile + packing
382/// metadata), clamped to a sane range. `0` (cache unknown) ⇒ `fallback`, which
383/// is kept small so the block ≈ the naive loop and can never over-block a cache
384/// it can't see. Sizes come from the shared [`crate::cache`] probe.
385fn tier_budget_bytes(cache_bytes: usize, num: usize, den: usize, fallback: usize) -> usize {
386    if cache_bytes == 0 {
387        fallback
388    } else {
389        (cache_bytes * num / den).clamp(64 * 1024, 64 * 1024 * 1024)
390    }
391}
392
393/// Inner tier: ~a third of L2 (private per perf-core), 256 KiB fallback.
394fn l2_block_budget_bytes() -> usize {
395    tier_budget_bytes(crate::cache::cache_info().l2, 1, 3, 256 * 1024)
396}
397
398/// Outer tier: `(llc_bytes, budget_bytes)` — the raw last-level-cache size and the
399/// fraction of it the outer super-block may budget — but only when an L3/LLC larger
400/// than L2 is detected (otherwise an outer tier just duplicates the inner one).
401/// `None` ⇒ no outer tier; the walk stays single-level. The raw size is returned
402/// alongside the budget so the caller can check whether the working set even
403/// spills the cache before blocking. Both numbers are for the *whole* cache;
404/// concurrent walkers each get a share (see [`outer_block_edge`]).
405fn l3_block_budget_bytes() -> Option<(usize, usize)> {
406    use crate::cache::LlcKind;
407    let (bytes, kind) = crate::cache::last_level_cache()?;
408    // Dedicated cluster L3: ~half. A shared System-Level Cache is contended by the
409    // GPU/NPU/display, so we can't assume residency of lines they keep evicting —
410    // budget it to ~a quarter.
411    let (num, den) = match kind {
412        LlcKind::Dedicated => (1, 2),
413        LlcKind::SystemLevel => (1, 4),
414    };
415    Some((bytes, tier_budget_bytes(bytes, num, den, 0)))
416}
417
418/// Cache-adaptive panel-block edge for a given byte budget: large enough to
419/// amortise streaming, small enough that the block's A+B sub-panels
420/// (`~blk·(mr+nr)·k·elem_bytes`) stay cache-resident at the given `k`. Capped at
421/// `cap`; the floor of 1 degrades exactly to the naive loop, so an unknown/small
422/// cache can never over-block (regression-safe).
423#[inline]
424fn block_edge_for(
425    budget: usize,
426    mr: usize,
427    nr: usize,
428    k: usize,
429    elem_bytes: usize,
430    cap: usize,
431) -> usize {
432    if k == 0 {
433        return cap;
434    }
435    let per_blk = ((mr + nr) * k * elem_bytes.max(1)).max(1);
436    (budget / per_blk).clamp(1, cap)
437}
438
439/// Whether inner (L2) blocking captures reuse the naive stream cannot, given the
440/// operand the walk re-streams — A (the m side, `panels·r = m_panels·mr`) for a
441/// column-outer order, B (the n side) for a row-outer one. If that streamed
442/// operand already fits L2 it is re-read from cache, not DRAM, so reordering
443/// tiles buys no reuse and only disturbs the prefetchers; only when it spills L2
444/// does the block save re-fetches. Mirrors [`outer_tier_pays`] for the inner
445/// tier, keyed on the streamed operand rather than the whole working set.
446fn inner_tier_pays(panels: usize, r: usize, k: usize, elem_bytes: usize, l2_bytes: usize) -> bool {
447    let streamed = panels.saturating_mul(r).saturating_mul(k).saturating_mul(elem_bytes);
448    l2_bytes > 0 && streamed > l2_bytes
449}
450
451/// Inner (L2) panel-block edge, or `usize::MAX` (single block, i.e. the naive
452/// stream) when the streamed operand already fits L2 (see [`inner_tier_pays`]).
453/// The budget is **cache-size derived** (not a hard-coded constant), so it is
454/// correct across hardware.
455///
456/// `l2_share` is how many rectangles concurrently share this L2, so each walker
457/// may only assume its slice of it — like [`outer_block_edge`]'s `llc_share`, but
458/// bounded by the L2's physical sharing degree rather than the thread count. On a
459/// core-private L2 (`l2_share == 1`) this is the whole cache, unchanged; on a
460/// cluster-shared L2 (Cortex-A9/A53) it prevents sibling rectangles from evicting
461/// one another's blocks.
462#[inline]
463#[allow(clippy::too_many_arguments)]
464fn inner_block_edge(
465    mr: usize,
466    nr: usize,
467    k: usize,
468    elem_bytes: usize,
469    m_panels: usize,
470    n_panels: usize,
471    col_outer: bool,
472    l2_share: usize,
473) -> usize {
474    let (panels, r) = if col_outer { (m_panels, mr) } else { (n_panels, nr) };
475    let share = l2_share.max(1);
476    if !inner_tier_pays(panels, r, k, elem_bytes, crate::cache::cache_info().l2 / share) {
477        return usize::MAX;
478    }
479    block_edge_for(l2_block_budget_bytes() / share, mr, nr, k, elem_bytes, BLK_MAX)
480}
481
482/// Whether an L3 outer super-block can capture reuse the inner (L2) tier cannot.
483/// It only can when the packed working set (`A + B ≈ (m·mr + n·nr)·k·elem`)
484/// actually spills the last-level cache: if both operands already fit, they stay
485/// resident across the sweep regardless of traversal order, so the reorder buys
486/// no reuse and only disturbs the hardware prefetchers — a measured net loss on
487/// small models that never leave L3 (voicecom_float on jetson-orin-nx, +15.6%).
488/// This is exactly the precondition the outer tier was introduced for ("a grid
489/// that exceeds L2 still re-fetches A/B from DRAM"); without the check the tier
490/// also engages on grids that never leave the LLC.
491fn outer_tier_pays(
492    m_panels: usize,
493    n_panels: usize,
494    mr: usize,
495    nr: usize,
496    k: usize,
497    elem_bytes: usize,
498    llc_bytes: usize,
499) -> bool {
500    let working_set = m_panels
501        .saturating_mul(mr)
502        .saturating_add(n_panels.saturating_mul(nr))
503        .saturating_mul(k)
504        .saturating_mul(elem_bytes);
505    llc_bytes > 0 && working_set > llc_bytes
506}
507
508/// Outer (L3) super-block edge, or `usize::MAX` (one block over the whole
509/// rectangle, i.e. no outer tier) when no usable L3 is detected or the working set
510/// already fits it (see [`outer_tier_pays`]). Never smaller than the inner edge
511/// `inner`.
512///
513/// `llc_share` is how many rectangles are walked concurrently: the LLC is shared,
514/// so each walker may only assume its slice of it. Sizing every chunk of a
515/// multi-threaded dispatch against the whole LLC would have them evict each
516/// other's super-blocks.
517#[inline]
518#[allow(clippy::too_many_arguments)]
519fn outer_block_edge(
520    mr: usize,
521    nr: usize,
522    k: usize,
523    elem_bytes: usize,
524    inner: usize,
525    m_panels: usize,
526    n_panels: usize,
527    llc_share: usize,
528) -> usize {
529    let Some((llc, budget)) = l3_block_budget_bytes() else { return usize::MAX };
530    let share = llc_share.max(1);
531    if !outer_tier_pays(m_panels, n_panels, mr, nr, k, elem_bytes, llc / share) {
532        return usize::MAX;
533    }
534    block_edge_for(budget / share, mr, nr, k, elem_bytes, BLK_L3_MAX).max(inner)
535}
536
537/// Visit every `(ia, ib)` tile of the `m × n` panel rectangle exactly once,
538/// blocked two levels deep: an outer `blk_outer` super-block (L3-resident) holds
539/// inner `blk` blocks (L2-resident). `col_outer` selects the within-block inner
540/// order (B-reuse vs A-reuse). When `blk_outer` spans the whole rectangle the
541/// outer loop runs once and this is exactly the single-level inner walk. Pure
542/// tile reordering ⇒ no result changes; extracted so the nesting can be
543/// unit-tested independently of the kernel.
544#[inline]
545fn for_each_blocked_tile(
546    m: Range<usize>,
547    n: Range<usize>,
548    blk: usize,
549    blk_outer: usize,
550    col_outer: bool,
551    mut f: impl FnMut(usize, usize) -> TractResult<()>,
552) -> TractResult<()> {
553    let blk = blk.max(1);
554    let blk_outer = blk_outer.max(blk);
555    let mut jb3 = n.start;
556    while jb3 < n.end {
557        let jb3_end = jb3.saturating_add(blk_outer).min(n.end);
558        let mut ja3 = m.start;
559        while ja3 < m.end {
560            let ja3_end = ja3.saturating_add(blk_outer).min(m.end);
561            let mut jb = jb3;
562            while jb < jb3_end {
563                let jb_end = jb.saturating_add(blk).min(jb3_end);
564                let mut ja = ja3;
565                while ja < ja3_end {
566                    let ja_end = ja.saturating_add(blk).min(ja3_end);
567                    if col_outer {
568                        for ib in jb..jb_end {
569                            for ia in ja..ja_end {
570                                f(ia, ib)?;
571                            }
572                        }
573                    } else {
574                        for ia in ja..ja_end {
575                            for ib in jb..jb_end {
576                                f(ia, ib)?;
577                            }
578                        }
579                    }
580                    ja = ja_end;
581                }
582                jb = jb_end;
583            }
584            ja3 = ja3_end;
585        }
586        jb3 = jb3_end;
587    }
588    Ok(())
589}
590
591/// Tile walk over one panel rectangle — the whole grid on the single-thread
592/// path, one dispatch chunk on the rayon path — blocked into cache-sized panel
593/// blocks for locality (the naive nested loop re-streams the whole inner operand
594/// per outer panel at large k). Two tiers: an inner L2-resident block and, where
595/// an L3 is detected, an outer L3-resident super-block sized for one of
596/// `llc_share` concurrent walkers. Both tiers are gated on the rectangle's own
597/// extents, so a rectangle whose streamed operand already fits cache walks
598/// exactly the naive order. Reordering independent tiles changes no result —
599/// bit-exact with the naive loop at any chunking.
600#[inline]
601#[allow(clippy::too_many_arguments)]
602unsafe fn run_blocked<K: MatMatMulKer>(
603    ker: &K,
604    m: Range<usize>,
605    n: Range<usize>,
606    k: usize,
607    col_outer: bool,
608    llc_share: usize,
609    scratch: &ScratchSpaceImpl<K::Acc>,
610    non_linear: &[FusedSpec],
611) -> TractResult<()> {
612    unsafe {
613        let elem = K::Acc::datum_type().size_of();
614        let (mr, nr) = (ker.mr(), ker.nr());
615        let (m_panels, n_panels) = (m.len(), n.len());
616        let l2_share = llc_share.min(crate::cache::cache_info().l2_sharers_or_one());
617        let blk = inner_block_edge(mr, nr, k, elem, m_panels, n_panels, col_outer, l2_share);
618        let blk_outer = outer_block_edge(mr, nr, k, elem, blk, m_panels, n_panels, llc_share);
619        scratch.run_in_tls_scope(|scratch, tls| {
620            for_each_blocked_tile(m, n, blk, blk_outer, col_outer, |ia, ib| {
621                scratch.run_one_tile(ker, non_linear, tls, ia, ib)
622            })
623        })
624    }
625}
626
627/// Run the whole `m × n` output over the executor currently installed: as one
628/// rectangle when single-threaded, else split into the chunk grid
629/// [`chunk_grid`] picks. `col_outer` selects the tile order inside a rectangle
630/// (B-reuse vs A-reuse), from the fused ops' preference. `k` is used to size the
631/// cache blocking and the packed-operand footprint the chunk gate reads.
632unsafe fn run_with_scratch_space_2d<K: MatMatMulKer>(
633    ker: &K,
634    m: usize,
635    n: usize,
636    k: usize,
637    col_outer: bool,
638    scratch: &ScratchSpaceImpl<K::Acc>,
639    non_linear: &[FusedSpec],
640) -> TractResult<()> {
641    unsafe {
642        let (m_panels, n_panels) = (m.divceil(ker.mr()), n.divceil(ker.nr()));
643        #[cfg(feature = "multithread-mm")]
644        let chunk = |ia_start, ia_end, ib_start, ib_end, concurrency| {
645            run_blocked(
646                ker,
647                ia_start..ia_end,
648                ib_start..ib_end,
649                k,
650                col_outer,
651                concurrency,
652                scratch,
653                non_linear,
654            )
655        };
656        match crate::multithread::current_tract_executor() {
657            Executor::SingleThread => {
658                run_blocked(ker, 0..m_panels, 0..n_panels, k, col_outer, 1, scratch, non_linear)
659            }
660            #[cfg(feature = "multithread-mm")]
661            Executor::MultiThread(pool) => chunked_dispatch_rayon(
662                Some(&pool),
663                m_panels,
664                n_panels,
665                ker.mr(),
666                ker.nr(),
667                k,
668                K::Acc::datum_type().size_of(),
669                chunk,
670            ),
671            #[cfg(feature = "multithread-mm")]
672            Executor::RayonGlobal => chunked_dispatch_rayon(
673                None,
674                m_panels,
675                n_panels,
676                ker.mr(),
677                ker.nr(),
678                k,
679                K::Acc::datum_type().size_of(),
680                chunk,
681            ),
682        }
683    }
684}
685
686/// Chunks per thread the 2D dispatch aims for when the extra chunks are worth
687/// their re-reads (see [`chunks_per_thread`]). Above one, rayon can steal work
688/// when threads progress unevenly — a contended core, an E-core on a big.LITTLE
689/// part, a chunk carrying more border tiles — so a straggler costs at most its
690/// share rather than the whole grid's tail. Each extra chunk also re-reads a band
691/// of the packed operands, and that cost grows as `sqrt(chunks)` against a linear
692/// gain in slack, which is what keeps this small.
693#[cfg(feature = "multithread-mm")]
694const CHUNKS_PER_THREAD: usize = 4;
695
696/// Last-level cache above which the slack is always worth taking, whatever the
697/// problem: a part with this much LLC absorbs the re-reads of anything the
698/// dispatch is likely to see, so the gate below never fires and the chunk grid is
699/// bit-for-bit what it was before this gate existed.
700#[cfg(feature = "multithread-mm")]
701const CHUNK_SLACK_LLC_BYTES: usize = 2 * 1024 * 1024;
702
703/// Largest packed-operand footprint whose re-reads a small-cache part still
704/// absorbs. Below it the extra chunks re-read something the memory system is
705/// plausibly still holding and the slack is close to free; above it each extra
706/// chunk is a fresh DRAM stream.
707///
708/// A slider, not a separator. The two models that disagree about the slack do
709/// **not** occupy disjoint footprint ranges — over their threaded matmuls at
710/// 12x8/f32, InceptionV3 spans 0.16-23.8 MB (median 0.54) and MobileNet v2
711/// 0.20-6.95 MB (median 0.88) — so no boundary sorts one model from the other.
712/// What the boundary does is set the share of each model's FLOPs that keeps the
713/// slack, and the a53's InceptionV3 win and the a7/a9/beaglev MobileNet
714/// regression both scale with that share:
715///
716/// ```text
717///   boundary   incep FLOPs at cpt 1 -> a53      mobilenet at cpt 1 -> a7/a9/bv
718///     0.5 MB           88.5%          -7.3%          79.7%           +5.6%
719///     1.0 MB           85.9%          -7.0%          53.5%           +3.7%
720///     1.5 MB           76.9%          -6.3%          21.5%           +1.5%
721///     2.0 MB           62.0%          -5.1%          18.9%           +1.3%
722///     4.0 MB           41.5%          -3.4%           0.3%            0.0%
723/// ```
724///
725/// Predicted linearly from the two measured endpoints (all-cpt-1: a53 -8.2%,
726/// MobileNet +6.0..8.0%), which reproduce the measured 2 MB point to within half
727/// a point on both models. 1.5 MB is the knee: MobileNet's share falls off a
728/// cliff between 1.5 and 1.0 MB while InceptionV3's barely moves, so it buys most
729/// of the a53 win before the regression comes back.
730///
731/// `TRACT_MMM_CHUNK_SLACK_BYTES` moves it, which is how the table above would be
732/// measured rather than predicted.
733#[cfg(feature = "multithread-mm")]
734const CHUNK_SLACK_OPERAND_BYTES: usize = 3 * 512 * 1024;
735
736/// Machine facts the chunk gate reads, resolved once: `(llc_bytes, slack_bytes,
737/// override)`. Memoised like the cache probe underneath it — this sits on the
738/// per-matmul dispatch path, and neither the env vars nor the cache geometry
739/// change under a running process.
740#[cfg(feature = "multithread-mm")]
741fn chunk_gate_env() -> (usize, usize, Option<usize>) {
742    use std::sync::OnceLock;
743    static ENV: OnceLock<(usize, usize, Option<usize>)> = OnceLock::new();
744    *ENV.get_or_init(|| {
745        let usize_var =
746            |k: &str| std::env::var(k).ok().and_then(|v| v.trim().parse::<usize>().ok());
747        let llc = crate::cache::last_level_cache()
748            .map(|(bytes, _)| bytes)
749            .unwrap_or_else(|| crate::cache::cache_info().l2);
750        let slack = usize_var("TRACT_MMM_CHUNK_SLACK_BYTES").unwrap_or(CHUNK_SLACK_OPERAND_BYTES);
751        (llc, slack, usize_var("TRACT_MMM_CHUNKS_PER_THREAD"))
752    })
753}
754
755/// Chunks per thread [`chunk_grid`] aims for, for a dispatch whose packed
756/// operands occupy `packed_bytes`.
757///
758/// An extra chunk buys load-balance slack and costs one more pass over a packed
759/// operand. Whether that pass is worth taking is a property of the *problem* as
760/// much as of the machine: on a part with a large last-level cache every pass is
761/// a cache hit, so the slack is always taken; on a small-cache part it depends on
762/// whether the operands are small enough for the memory system to still be
763/// holding them. Gating on the machine alone takes the slack away from the small
764/// problems that were paying nothing for it.
765///
766/// `TRACT_MMM_CHUNKS_PER_THREAD` overrides the choice outright, and
767/// `TRACT_MMM_CHUNK_SLACK_BYTES` moves the footprint boundary. Both are resolved
768/// once, like the cache probe they sit next to.
769#[cfg(feature = "multithread-mm")]
770fn chunks_per_thread(packed_bytes: usize) -> usize {
771    let (llc, slack, over) = chunk_gate_env();
772    resolve_chunks_per_thread(over, llc, slack, packed_bytes)
773}
774
775/// Pure resolution of [`chunks_per_thread`] (factored out so the gate is testable
776/// without the host's cache geometry, which decides it otherwise).
777#[cfg(feature = "multithread-mm")]
778fn resolve_chunks_per_thread(
779    override_cpt: Option<usize>,
780    llc: usize,
781    slack_bytes: usize,
782    packed_bytes: usize,
783) -> usize {
784    if let Some(n) = override_cpt {
785        return n.max(1);
786    }
787    // A big enough LLC absorbs the re-reads whatever the problem: unchanged.
788    if llc >= CHUNK_SLACK_LLC_BYTES {
789        return CHUNKS_PER_THREAD;
790    }
791    if packed_bytes <= slack_bytes { CHUNKS_PER_THREAD } else { 1 }
792}
793
794/// Bytes the packed operands of a dispatch occupy: A is `n_panels_m·mr` rows and
795/// B `n_panels_n·nr` columns, both over `k`, both padded to whole panels — which
796/// is exactly what the packers wrote and the chunks re-read.
797#[cfg(feature = "multithread-mm")]
798fn packed_operand_bytes(
799    n_panels_m: usize,
800    n_panels_n: usize,
801    mr: usize,
802    nr: usize,
803    k: usize,
804    elem: usize,
805) -> usize {
806    (n_panels_m.saturating_mul(mr).saturating_add(n_panels_n.saturating_mul(nr)))
807        .saturating_mul(k)
808        .saturating_mul(elem)
809}
810
811/// Chunk grid for the 2D dispatch: `(nchunks_m, nchunks_n, dr_m, dr_n)`.
812///
813/// Aims for `cpt · nth` chunks — see [`chunks_per_thread`] for where `cpt` comes
814/// from — and shapes them to minimise how
815/// often the packed operands are re-read: a chunk covering `dr_m × dr_n` panels
816/// reads `dr_m·mr·k` of A and `dr_n·nr·k` of B, so over the whole grid A is read
817/// `nchunks_n` times and B `nchunks_m` times. Minimising
818/// `nchunks_n·m + nchunks_m·n` at a fixed chunk count puts
819/// `nchunks_m = sqrt(chunks · m / n)` — chunks as square as the operands'
820/// extents, rather than a band across one axis.
821///
822/// Cache locality *inside* a chunk is [`run_blocked`]'s job, not this function's;
823/// chunk *shape* therefore tracks the operands' extents and chunk *count* the
824/// thread count, with the cache entering only through `cpt`.
825///
826/// Both panel counts must be non-zero; the dispatcher returns early on an empty
827/// grid.
828#[cfg(feature = "multithread-mm")]
829fn chunk_grid(
830    n_panels_m: usize,
831    n_panels_n: usize,
832    mr: usize,
833    nr: usize,
834    nth: usize,
835    cpt: usize,
836) -> (usize, usize, usize, usize) {
837    let chunks = (cpt * nth).max(1);
838    let (m, n) = (n_panels_m * mr, (n_panels_n * nr).max(1));
839    let nchunks_m = (chunks.saturating_mul(m) / n).isqrt().clamp(1, n_panels_m);
840    let nchunks_n = (chunks / nchunks_m).clamp(1, n_panels_n);
841    let nchunks_m = (chunks / nchunks_n).clamp(1, n_panels_m);
842    let dr_m = n_panels_m.div_ceil(nchunks_m);
843    let dr_n = n_panels_n.div_ceil(nchunks_n);
844    // Recount from the edges: `div_ceil` can make the last chunk of an axis land
845    // entirely outside the grid, and an empty work item is a wasted dispatch.
846    (n_panels_m.div_ceil(dr_m), n_panels_n.div_ceil(dr_n), dr_m, dr_n)
847}
848
849/// Dispatch the `m_panels × n_panels` panel grid across the rayon path, split into
850/// the 2D chunk grid [`chunk_grid`] picks. Grids below
851/// [`crate::multithread::current_threading_panel_threshold`] run whole on the
852/// calling thread instead.
853///
854/// The closure receives **chunk bounds** (`ia_start, ia_end, ib_start, ib_end`)
855/// plus the number of chunks running concurrently, not per-tile indices. Chunk
856/// bounds let it amortise per-worker setup (e.g.
857/// `ScratchSpaceImpl::run_in_tls_scope`) over all the tiles in the chunk; the
858/// concurrency lets it size shared-cache blocking against the share it actually
859/// gets. The closure is invoked exactly once per rayon work item, and once in
860/// total with a concurrency of 1 on the below-threshold path.
861///
862/// `pool`:
863///   * `Some(p)` with `p.current_num_threads() > 1` → scoped via `p.install`
864///     (native, custom pool path).
865///   * `Some(p)` with single-thread pool, or `None` → dispatched via
866///     `into_par_iter` directly, which uses rayon's GLOBAL pool. This is
867///     the only working path on `wasm32-unknown-unknown` via
868///     `wasm_bindgen_rayon::init_thread_pool`.
869#[cfg(feature = "multithread-mm")]
870#[allow(clippy::too_many_arguments)]
871unsafe fn chunked_dispatch_rayon<F>(
872    pool: Option<&rayon::ThreadPool>,
873    n_panels_m: usize,
874    n_panels_n: usize,
875    mr: usize,
876    nr: usize,
877    k: usize,
878    elem: usize,
879    run_chunk: F,
880) -> TractResult<()>
881where
882    F: Fn(usize, usize, usize, usize, usize) -> TractResult<()> + Sync,
883{
884    use rayon::prelude::*;
885    if n_panels_m == 0 || n_panels_n == 0 {
886        return Ok(());
887    }
888    if n_panels_m * n_panels_n < crate::multithread::current_threading_panel_threshold() {
889        // Below the threading threshold: run the whole grid as a single chunk
890        // on the calling thread. Closure handles its own TLS scope.
891        return run_chunk(0, n_panels_m, 0, n_panels_n, 1);
892    }
893    let use_global = pool.is_none_or(|p| p.current_num_threads() <= 1);
894    let cpt = chunks_per_thread(packed_operand_bytes(n_panels_m, n_panels_n, mr, nr, k, elem));
895    let body = || {
896        let nth = rayon::current_num_threads();
897        let (nchunks_m, nchunks_n, dr_m, dr_n) =
898            chunk_grid(n_panels_m, n_panels_n, mr, nr, nth, cpt);
899        let total = nchunks_m * nchunks_n;
900        let concurrency = nth.min(total);
901        (0..total).into_par_iter().try_for_each(|idx| {
902            let im = idx % nchunks_m;
903            let in_ = idx / nchunks_m;
904            let ia_start = im * dr_m;
905            let ia_end = (ia_start + dr_m).min(n_panels_m);
906            let ib_start = in_ * dr_n;
907            let ib_end = (ib_start + dr_n).min(n_panels_n);
908            run_chunk(ia_start, ia_end, ib_start, ib_end, concurrency)
909        })
910    };
911    if use_global { body() } else { pool.unwrap().install(body) }
912}
913
914#[cfg(test)]
915mod blocked_walk_tests {
916    use super::*;
917    use std::collections::HashSet;
918
919    fn collect(
920        m: Range<usize>,
921        n: Range<usize>,
922        blk: usize,
923        blk_outer: usize,
924        col_outer: bool,
925    ) -> Vec<(usize, usize)> {
926        let mut v = Vec::new();
927        for_each_blocked_tile(m, n, blk, blk_outer, col_outer, |ia, ib| {
928            v.push((ia, ib));
929            Ok(())
930        })
931        .unwrap();
932        v
933    }
934
935    /// Every tile of the rectangle is visited exactly once, for both inner orders
936    /// and a range of (blk, blk_outer) — single-tier (outer = MAX), two-tier, and
937    /// degenerate edges. Coverage being a permutation is what makes the walk
938    /// bit-exact with the naive loop. Offset rectangles are the dispatch chunks.
939    #[test]
940    fn covers_every_tile_once() {
941        for &(m, n) in &[(1, 1), (3, 5), (16, 16), (40, 7), (7, 40), (80, 80)] {
942            for &(m0, n0) in &[(0, 0), (3, 11)] {
943                // usize::MAX is how both tiers say "do not block"; on an offset
944                // rectangle the edge arithmetic must not overflow past the end.
945                for &blk in &[1, 3, 16, usize::MAX] {
946                    for &blk_outer in &[blk, blk.saturating_add(1), 64, usize::MAX] {
947                        for &col_outer in &[false, true] {
948                            let tiles = collect(m0..m0 + m, n0..n0 + n, blk, blk_outer, col_outer);
949                            assert_eq!(
950                                tiles.len(),
951                                m * n,
952                                "m={m} n={n} blk={blk} outer={blk_outer}"
953                            );
954                            let set: HashSet<_> = tiles.iter().copied().collect();
955                            assert_eq!(
956                                set.len(),
957                                m * n,
958                                "duplicate tiles m={m} n={n} blk={blk} outer={blk_outer}"
959                            );
960                            for ia in m0..m0 + m {
961                                for ib in n0..n0 + n {
962                                    assert!(set.contains(&(ia, ib)), "missing ({ia},{ib})");
963                                }
964                            }
965                        }
966                    }
967                }
968            }
969        }
970    }
971
972    /// With no outer tier (blk_outer = MAX) the two-tier walk must emit the exact
973    /// same order as the original single-level blocked loop — guarantees the L3
974    /// path is a pure no-op on hardware without a detectable L3.
975    #[test]
976    fn outer_max_matches_single_level() {
977        for &(m, n) in &[(40, 7), (80, 80), (13, 29)] {
978            for &blk in &[1, 4, 16] {
979                for &col_outer in &[false, true] {
980                    let two_tier = collect(0..m, 0..n, blk, usize::MAX, col_outer);
981                    let mut single = Vec::new();
982                    let mut jb = 0;
983                    while jb < n {
984                        let jb_end = (jb + blk).min(n);
985                        let mut ja = 0;
986                        while ja < m {
987                            let ja_end = (ja + blk).min(m);
988                            if col_outer {
989                                for ib in jb..jb_end {
990                                    for ia in ja..ja_end {
991                                        single.push((ia, ib));
992                                    }
993                                }
994                            } else {
995                                for ia in ja..ja_end {
996                                    for ib in jb..jb_end {
997                                        single.push((ia, ib));
998                                    }
999                                }
1000                            }
1001                            ja = ja_end;
1002                        }
1003                        jb = jb_end;
1004                    }
1005                    assert_eq!(two_tier, single, "m={m} n={n} blk={blk} col_outer={col_outer}");
1006                }
1007            }
1008        }
1009    }
1010
1011    /// The outer tier engages only when the packed working set spills the LLC.
1012    /// A grid that already fits stays single-level (the reorder buys no reuse and
1013    /// only hurts prefetch — the voicecom_float/Orin regression).
1014    #[test]
1015    fn outer_tier_gated_on_working_set_spilling_llc() {
1016        let llc = 2 * 1024 * 1024; // 2 MiB, f32 (elem = 4)
1017        // Small grid: (64·8 + 8·8)·64·4 ≈ 144 KiB ⇒ fits ⇒ no outer tier.
1018        assert!(!outer_tier_pays(64, 8, 8, 8, 64, 4, llc));
1019        // Large grid: (256·8 + 256·8)·256·4 ≈ 4 MiB ⇒ spills ⇒ engage.
1020        assert!(outer_tier_pays(256, 256, 8, 8, 256, 4, llc));
1021        // A boundary working set equal to the LLC does not spill it.
1022        assert!(!outer_tier_pays(1, 0, llc, 0, 1, 1, llc));
1023        // Unknown LLC (0) never engages, whatever the grid.
1024        assert!(!outer_tier_pays(4096, 4096, 8, 8, 4096, 4, 0));
1025        // k = 0 (empty reduction) has no working set ⇒ never engages.
1026        assert!(!outer_tier_pays(4096, 4096, 8, 8, 0, 4, llc));
1027    }
1028
1029    /// Inner blocking engages only when the operand the walk re-streams — A for a
1030    /// column-outer order, B for a row-outer one — spills L2. A streamed operand
1031    /// that fits is re-read from cache, so blocking only hurts prefetch.
1032    #[test]
1033    fn inner_tier_gated_on_streamed_operand_spilling_l2() {
1034        let l2 = 1024 * 1024; // 1 MiB, f32 (elem = 4)
1035        // inception Conv2d_4a_3x3 grid (16×12 kernel), k=720.
1036        // col_outer streams A (m side, panels=12 r=16): 12·16·720·4 ≈ 540 KiB ⇒ fits.
1037        assert!(!inner_tier_pays(12, 16, 720, 4, l2));
1038        // row_outer streams B (n side, panels=421 r=12): 421·12·720·4 ≈ 14.5 MiB ⇒ spills.
1039        assert!(inner_tier_pays(421, 12, 720, 4, l2));
1040        // A large square (m side, panels=256 r=16, k=512): 256·16·512·4 ≈ 8 MiB ⇒ spills.
1041        assert!(inner_tier_pays(256, 16, 512, 4, l2));
1042        // Undetectable L2 (0) never engages — degrades to the naive loop.
1043        assert!(!inner_tier_pays(4096, 16, 4096, 4, 0));
1044        // k = 0 (empty reduction) has no working set.
1045        assert!(!inner_tier_pays(4096, 16, 0, 4, l2));
1046    }
1047
1048    /// Grids, kernel aspect ratios and thread counts worth checking the chunk
1049    /// grid against: skewed both ways, square, prime-ish, and the degenerate
1050    /// single-panel cases.
1051    #[cfg(feature = "multithread-mm")]
1052    const GRIDS: &[(usize, usize)] = &[
1053        (1, 1),
1054        (1, 5),
1055        (5, 1),
1056        (2, 3),
1057        (3, 3),
1058        (16, 96),
1059        (96, 16),
1060        (17, 17),
1061        (64, 64),
1062        (32, 384),
1063        (128, 128),
1064        (1, 4096),
1065        (4096, 1),
1066        (9, 1000),
1067    ];
1068
1069    #[cfg(feature = "multithread-mm")]
1070    const RATIOS: &[(usize, usize)] = &[(8, 8), (16, 4), (32, 32), (64, 1)];
1071
1072    /// The four numbers `chunk_grid` returns must tile the panel grid exactly:
1073    /// `chunked_dispatch_rayon` turns them into work items, so an empty chunk is
1074    /// a wasted dispatch, an overlap would double-compute a tile, and a gap would
1075    /// leave part of C uninitialised.
1076    #[cfg(feature = "multithread-mm")]
1077    #[test]
1078    fn chunk_grid_tiles_the_panel_grid() {
1079        for &(m, n) in GRIDS {
1080            for &(mr, nr) in RATIOS {
1081                for nth in [1usize, 2, 3, 4, 6, 8, 16, 64] {
1082                    for cpt in [1, CHUNKS_PER_THREAD] {
1083                        let (cm, cn, dr_m, dr_n) = chunk_grid(m, n, mr, nr, nth, cpt);
1084                        let ctx =
1085                            format!("{m}x{n} panels, {mr}x{nr} kernel, {nth} threads, cpt {cpt}");
1086                        let mut seen = vec![false; m * n];
1087                        for idx in 0..cm * cn {
1088                            let (im, in_) = (idx % cm, idx / cm);
1089                            let (a0, a1) = (im * dr_m, (im * dr_m + dr_m).min(m));
1090                            let (b0, b1) = (in_ * dr_n, (in_ * dr_n + dr_n).min(n));
1091                            assert!(a0 < a1 && b0 < b1, "empty chunk {idx} in {ctx}");
1092                            for ia in a0..a1 {
1093                                for ib in b0..b1 {
1094                                    assert!(!seen[ia * n + ib], "tile ({ia},{ib}) twice in {ctx}");
1095                                    seen[ia * n + ib] = true;
1096                                }
1097                            }
1098                        }
1099                        assert!(seen.iter().all(|s| *s), "tile left out in {ctx}");
1100                    }
1101                }
1102            }
1103        }
1104    }
1105
1106    /// Enough chunks to keep every thread fed, whenever the grid has that many
1107    /// panels to go round. Recounting the chunks from the edges is what makes this
1108    /// hold: naming more chunks than the edges cover would idle the difference.
1109    ///
1110    /// Only at the slack count. At `cpt == 1` the dispatch asks for exactly `nth`
1111    /// chunks and the `div_ceil` rounding can only give back fewer — a 1x5 panel
1112    /// grid over 4 threads lands 3 chunks — so a gated dispatch can leave a thread
1113    /// idle. That is the price the gate pays, and it buys the operand re-reads it
1114    /// saves; [`chunks_per_thread`] only takes it where those re-reads cost more.
1115    #[cfg(feature = "multithread-mm")]
1116    #[test]
1117    fn chunk_grid_feeds_every_thread() {
1118        for &(m, n) in GRIDS {
1119            for &(mr, nr) in RATIOS {
1120                for nth in [1usize, 2, 3, 4, 6, 8, 16, 64] {
1121                    let (cm, cn, ..) = chunk_grid(m, n, mr, nr, nth, CHUNKS_PER_THREAD);
1122                    assert!(
1123                        cm * cn >= nth.min(m * n),
1124                        "{cm}x{cn} chunks for {nth} threads on {m}x{n} panels"
1125                    );
1126                }
1127            }
1128        }
1129    }
1130
1131    /// The gate is a property of the problem, not only of the machine. On a part
1132    /// too small to absorb the re-reads, a dispatch whose packed operands stay
1133    /// under the slack budget still gets the full chunk count — that is the
1134    /// MobileNet case, which paid a regression when the gate looked at the
1135    /// machine alone — while one above it drops to one chunk per thread, which is
1136    /// the InceptionV3 case the gate exists for.
1137    #[cfg(feature = "multithread-mm")]
1138    #[test]
1139    fn chunk_gate_reads_the_problem_not_just_the_machine() {
1140        let small_llc = 512 * 1024;
1141        let slack = CHUNK_SLACK_OPERAND_BYTES;
1142        // MobileNet v2 pointwise, f32: 96x16x12544 packs to well under a megabyte.
1143        assert_eq!(
1144            resolve_chunks_per_thread(None, small_llc, slack, 806 * 1024),
1145            CHUNKS_PER_THREAD
1146        );
1147        // InceptionV3 conv, f32: 384x4032x64 packs to 7.2 MB.
1148        assert_eq!(resolve_chunks_per_thread(None, small_llc, slack, 7 * 1024 * 1024), 1);
1149        // A machine with cache to spare takes the slack either way, which is what
1150        // keeps this inert on the m1-max / i9 / Orin numbers.
1151        for bytes in [806 * 1024, 7 * 1024 * 1024] {
1152            let big_llc = CHUNK_SLACK_LLC_BYTES;
1153            assert_eq!(resolve_chunks_per_thread(None, big_llc, slack, bytes), CHUNKS_PER_THREAD);
1154        }
1155    }
1156
1157    /// An undetected cache reads as 0, which must not read as "small problem":
1158    /// the gate has to fall to one chunk per thread there, as it would on the
1159    /// smallest part it can see.
1160    #[cfg(feature = "multithread-mm")]
1161    #[test]
1162    fn chunk_gate_overrides_and_undetected_cache() {
1163        let slack = CHUNK_SLACK_OPERAND_BYTES;
1164        assert_eq!(resolve_chunks_per_thread(None, 0, slack, 7 * 1024 * 1024), 1);
1165        // The override wins over both, and never names zero chunks.
1166        assert_eq!(resolve_chunks_per_thread(Some(1), CHUNK_SLACK_LLC_BYTES, slack, 0), 1);
1167        assert_eq!(resolve_chunks_per_thread(Some(8), 0, slack, usize::MAX), 8);
1168        assert_eq!(resolve_chunks_per_thread(Some(0), 0, slack, usize::MAX), 1);
1169    }
1170
1171    /// The footprint the gate reads is what the packers actually wrote: both
1172    /// operands padded out to whole panels, over the full depth.
1173    #[cfg(feature = "multithread-mm")]
1174    #[test]
1175    fn packed_operand_bytes_counts_whole_panels() {
1176        // 32x8 panels of a 12x8 kernel over k=4032, f32.
1177        assert_eq!(packed_operand_bytes(32, 8, 12, 8, 4032, 4), (32 * 12 + 8 * 8) * 4032 * 4);
1178        // Saturating, so a degenerate shape gates conservatively rather than wrapping.
1179        assert_eq!(packed_operand_bytes(usize::MAX, 1, 12, 8, 4032, 4), usize::MAX);
1180    }
1181
1182    /// The grid is shaped to minimise packed-operand re-reads: A is read once per
1183    /// column of chunks and B once per row, so `nchunks_n·m + nchunks_m·n` is what
1184    /// the shape trades off. It must never cost more than a band across either
1185    /// axis at the same chunk count, which on a square grid costs 1.5x.
1186    #[cfg(feature = "multithread-mm")]
1187    #[test]
1188    fn chunk_grid_shape_beats_a_band_on_operand_traffic() {
1189        let traffic = |cm: usize, cn: usize, m: usize, n: usize| cn * m + cm * n;
1190        for &(m, n) in GRIDS {
1191            for &(mr, nr) in RATIOS {
1192                for nth in [2usize, 4, 8, 16] {
1193                    let (cm, cn, ..) = chunk_grid(m, n, mr, nr, nth, CHUNKS_PER_THREAD);
1194                    let chunks = cm * cn;
1195                    // Only a band that fits along the axis is a real alternative:
1196                    // one clamped shorter would be a different chunk count, and a
1197                    // smaller chunk count trivially re-reads less.
1198                    if chunks > m || chunks > n {
1199                        continue;
1200                    }
1201                    let (m_ext, n_ext) = (m * mr, n * nr);
1202                    let ours = traffic(cm, cn, m_ext, n_ext);
1203                    let band_m = traffic(chunks, 1, m_ext, n_ext);
1204                    let band_n = traffic(1, chunks, m_ext, n_ext);
1205                    assert!(
1206                        ours <= band_m.min(band_n),
1207                        "{cm}x{cn} costs {ours}, bands cost {band_m}/{band_n} \
1208                         on {m}x{n} panels, {mr}x{nr} kernel, {nth} threads"
1209                    );
1210                }
1211            }
1212        }
1213    }
1214}