okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2n (ead5a32ae) into f-own-int: the Arm NEON tier of the quant layer0a9381336

main
2.4 KiB76 linesraw
1// src/quant/dispatch.cpp - kernel lookup: the best kernel of an arithmetic contract that this CPU can run.
2#include <algorithm>
3
4#include "registry.hpp"
5#include "strata/quant/act.hpp"
6#include "strata/quant/dot.hpp"
7
8namespace strata::quant {
9namespace {
10
11template <typename K, typename T, int N>
12int gather(const T (&tables)[N], Type t, Arith a, const K** out, int cap, Type K::*field) {
13    int n = 0;
14    for (const T& tb : tables)
15        for (int i = 0; i < tb.n; ++i) {
16            const K& k = tb.v[i];
17            if (k.*field == t && k.arith == a && n < cap) out[n++] = &k;
18        }
19    // best (widest hardware) first
20    std::stable_sort(out, out + n, [](const K* x, const K* y) { return (int) x->isa > (int) y->isa; });
21    return n;
22}
23
24constexpr int kMaxK = 16;
25
26int collect_dots(Type w, Arith a, const DotKernel** out, int cap) {
27    const DotTable tables[] = {
28        generic_dot_table(),
29#ifdef STRATA_QUANT_X86_TIERS
30        avx_dot_table(), avx2_dot_table(), avx512_dot_table(),
31#endif
32#ifdef STRATA_QUANT_ARM_TIERS
33        neon_dot_table(),
34#endif
35    };
36    return gather(tables, w, a, out, cap, &DotKernel::weight);
37}
38
39int collect_acts(Type act, Arith a, const ActKernel** out, int cap) {
40    const ActTable tables[] = {
41        generic_act_table(),
42#ifdef STRATA_QUANT_X86_TIERS
43        avx_act_table(), avx2_act_table(),
44#endif
45#ifdef STRATA_QUANT_ARM_TIERS
46        neon_act_table(),
47#endif
48    };
49    return gather(tables, act, a, out, cap, &ActKernel::act);
50}
51
52}  // namespace
53
54int dot_kernels(Type w, Arith a, const DotKernel** out, int cap) noexcept { return collect_dots(w, a, out, cap); }
55
56const DotKernel* dot_kernel(Type w, Arith a, Isa max_isa) noexcept {
57    const DotKernel* v[kMaxK];
58    const int n = collect_dots(w, a, v, kMaxK);
59    for (int i = 0; i < n; ++i)
60        if ((int) v[i]->isa <= (int) max_isa && isa_ok(v[i]->isa)) return v[i];
61    return nullptr;
62}
63
64const DotKernel* dot_kernel(Type w, Arith a) noexcept { return dot_kernel(w, a, best_isa()); }
65
66const ActKernel* act_kernel(Type act, Arith a, Isa max_isa) noexcept {
67    const ActKernel* v[kMaxK];
68    const int n = collect_acts(act, a, v, kMaxK);
69    for (int i = 0; i < n; ++i)
70        if ((int) v[i]->isa <= (int) max_isa && isa_ok(v[i]->isa)) return v[i];
71    return nullptr;
72}
73
74const ActKernel* act_kernel(Type act, Arith a) noexcept { return act_kernel(act, a, best_isa()); }
75
76}  // namespace strata::quant