okami.mom/strata

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

Niko1221Merge f-own-3c 0c83610e5 into f-own-int805e11c3d

main
13.8 KiB283 linesraw
1// tools/vision/own/cpu_kernels_impl.h - the kernels of one ISA tier, written once over a small vector type V.  Included by cpu_kernels_<isa>.cpp after it has
2// defined (before the include):
3//   struct V        float vector of V::W lanes: load(p) (unaligned), store(p), set1(x), zero(), operators + - *, fma(a, b, c) = a*b + c, vmax(a, b), reduce_add(v),
4//                   reduce_max(v), vexp(v) (expf, relative error below 3e-7 on [-87, 88])
5//   void conv16(const void* W, int kind, size_t off, int n, float* out)     n elements from W[off] (kind 1 BF16, 2 F16) to float
6//   STRATA_KN_MR    the rows of the register tile (NR is two vectors)
7// or, instead of struct V (STRATA_KN_RAW; the x86 tiers): the elementwise code below runs on a raw vector type VR with free inline functions VW (lanes),
8//   vr_load, vr_store(p, v), vr_set1, vr_zero, vr_add, vr_sub, vr_mul, vr_div, vr_fma(a, b, c) = a*b + c, vr_max, vr_hadd, vr_hmax, vr_exp, vr_sqrt1, and the tier
9//   brings its own micro (STRATA_KN_HAS_MICRO).  MSVC kept the wrapper struct in memory (RESULTS-OWN-3V.md 12.14); for the other tiers VR is V through the
10//   adapters below.  Both forms are the same operations in the same order, so the results are bit-identical.
11//   STRATA_KN_NAME  the tier's name, STRATA_KN_GETTER the table getter's name
12//   KN_MIN(a, b), KN_MAX(a, b), KN_COPY(dst, src, n floats), KN_ZERO(dst, n floats), V::sqrt1(x) (a correctly rounded float square root)
13// No standard-library header and no inline library function here (cpu_tier.h says why): the wider tiers define the KN_ helpers as their own internal
14// functions; the scalar tier, compiled at the baseline, as std::min / std::max / std::memcpy / std::memset (the code GCC vectorises best there: with
15// look-alike helpers the portable product loop came out partly scalar, 2 to 3 times slower, z440 11-10).
16#pragma once
17
18#include "cpu_tier.h"
19
20namespace strata_vit {
21namespace {      // every tier's kernels are internal to its translation unit (the vector types of the tiers share a name)
22namespace kn {
23
24#ifdef STRATA_KN_RAW
25constexpr int W = VW;
26#else
27constexpr int W = V::W;
28using VR = V;
29inline VR vr_load(const float* p) { return V::load(p); }
30inline void vr_store(float* p, VR v) { v.store(p); }
31inline VR vr_set1(float f) { return V::set1(f); }
32inline VR vr_zero() { return V::zero(); }
33inline VR vr_add(VR a, VR b) { return a + b; }
34inline VR vr_sub(VR a, VR b) { return a - b; }
35inline VR vr_mul(VR a, VR b) { return a * b; }
36inline VR vr_div(VR a, VR b) { return a / b; }
37inline VR vr_fma(VR a, VR b, VR c) { return V::fma(a, b, c); }
38inline VR vr_max(VR a, VR b) { return vmax(a, b); }
39inline float vr_hadd(VR a) { return V::reduce_add(a); }
40inline float vr_hmax(VR a) { return V::reduce_max(a); }
41inline VR vr_exp(VR a) { return vexp(a); }
42inline float vr_sqrt1(float x) { return V::sqrt1(x); }
43#endif
44constexpr int NR = 2 * W;
45constexpr int MRF = STRATA_KN_MR;
46
47// ---- the register-tiled product (a tier may bring its own `micro` with the same summation order: STRATA_KN_HAS_MICRO) ----
48#ifndef STRATA_KN_HAS_MICRO
49template <int MR>
50inline void micro(const float* A, size_t lda, const float* B, size_t ldb, int K, float* C, size_t ldc, int init, const float* bias) {
51    V acc[MR][2];
52    for (int r = 0; r < MR; ++r)
53        for (int c = 0; c < 2; ++c) {
54            V v = V::zero();
55            if (init != 0) v = V::load(C + (size_t) r * ldc + c * W);
56            if (init != 1 && bias) v = v + V::load(bias + c * W);
57            acc[r][c] = v;
58        }
59    for (int k = 0; k < K; ++k) {
60        const V b0 = V::load(B + (size_t) k * ldb), b1 = V::load(B + (size_t) k * ldb + W);
61        for (int r = 0; r < MR; ++r) {
62            const V a = V::set1(A[(size_t) r * lda + k]);
63            acc[r][0] = V::fma(a, b0, acc[r][0]);
64            acc[r][1] = V::fma(a, b1, acc[r][1]);
65        }
66    }
67    for (int r = 0; r < MR; ++r)
68        for (int c = 0; c < 2; ++c) acc[r][c].store(C + (size_t) r * ldc + c * W);
69}
70#endif
71
72// m rows (m <= MRF) of one column tile
73inline void tile_rows(const float* A, size_t lda, int m, const float* B, size_t ldb, int K, float* C, size_t ldc, int init, const float* bias) {
74    int r = 0;
75    for (; r + MRF <= m; r += MRF) micro<MRF>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
76    for (; r + 4 <= m; r += 4) micro<4>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
77    for (; r + 2 <= m; r += 2) micro<2>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
78    for (; r < m; ++r) micro<1>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
79}
80
81#ifdef STRATA_KN_RAW
82// The same product for a column tile of ONE vector (a last tile of at most W columns: the attention's P*V with a head size of 72 has 8 left over): each
83// column's sum is the same FMA chain in the same order as in micro (one lane of the same intrinsics), so the results are bit-identical; half the work of a
84// two-vector tile.  Only in the raw-vector tiers (AVX2, AVX-512), where vr_fma is the micro's own FMA intrinsic.
85template <int MR>
86inline void micro1(const float* A, size_t lda, const float* B, size_t ldb, int K, float* C, size_t ldc, int init, const float* bias) {
87    VR acc[MR];
88    for (int r = 0; r < MR; ++r) {
89        VR v = vr_zero();
90        if (init != 0) v = vr_load(C + (size_t) r * ldc);
91        if (init != 1 && bias) v = vr_add(v, vr_load(bias));
92        acc[r] = v;
93    }
94    for (int k = 0; k < K; ++k) {
95        const VR b0 = vr_load(B + (size_t) k * ldb);
96        for (int r = 0; r < MR; ++r) acc[r] = vr_fma(vr_set1(A[(size_t) r * lda + k]), b0, acc[r]);
97    }
98    for (int r = 0; r < MR; ++r) vr_store(C + (size_t) r * ldc, acc[r]);
99}
100inline void tile_rows1(const float* A, size_t lda, int m, const float* B, size_t ldb, int K, float* C, size_t ldc, int init, const float* bias) {
101    int r = 0;
102    for (; r + MRF <= m; r += MRF) micro1<MRF>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
103    for (; r + 4 <= m; r += 4) micro1<4>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
104    for (; r + 2 <= m; r += 2) micro1<2>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
105    for (; r < m; ++r) micro1<1>(A + (size_t) r * lda, lda, B, ldb, K, C + (size_t) r * ldc, ldc, init, bias);
106}
107#endif
108
109void gemm(const float* A, size_t lda, int M, const float* B, size_t ldb, int K, int N, float* C, size_t ldc, int init, const float* bias) {
110    for (int j0 = 0; j0 < N; j0 += NR) {
111        const int nc = KN_MIN(NR, N - j0);
112        if (nc == NR) {
113            tile_rows(A, lda, M, B + j0, ldb, K, C + j0, ldc, init, bias ? bias + j0 : nullptr);
114        }
115#ifdef STRATA_KN_RAW
116        else if (nc <= W && cpu_tier_one_vector_tail()) {      // a last tile of one vector or less: the one-vector product, through a one-vector buffer
117            float bb[W] = {0}, cb[MRF][W];
118            if (bias) KN_COPY(bb, bias + j0, nc);
119            for (int m0 = 0; m0 < M; m0 += MRF) {
120                const int mr = KN_MIN(MRF, M - m0);
121                for (int r = 0; r < mr; ++r) {
122                    KN_ZERO(cb[r], W);
123                    if (init != 0) KN_COPY(cb[r], C + (size_t) (m0 + r) * ldc + j0, nc);
124                }
125                tile_rows1(A + (size_t) m0 * lda, lda, mr, B + j0, ldb, K, &cb[0][0], W, init, bias ? bb : nullptr);
126                for (int r = 0; r < mr; ++r) KN_COPY(C + (size_t) (m0 + r) * ldc + j0, cb[r], nc);
127            }
128        }
129#endif
130        else {      // the last, partial column tile: through a full-width buffer
131            float bb[NR] = {0}, cb[MRF][NR];
132            if (bias) KN_COPY(bb, bias + j0, nc);
133            for (int m0 = 0; m0 < M; m0 += MRF) {
134                const int mr = KN_MIN(MRF, M - m0);
135                for (int r = 0; r < mr; ++r) {
136                    KN_ZERO(cb[r], NR);
137                    if (init != 0) KN_COPY(cb[r], C + (size_t) (m0 + r) * ldc + j0, nc);
138                }
139                tile_rows(A + (size_t) m0 * lda, lda, mr, B + j0, ldb, K, &cb[0][0], NR, init, bias ? bb : nullptr);
140                for (int r = 0; r < mr; ++r) KN_COPY(C + (size_t) (m0 + r) * ldc + j0, cb[r], nc);
141            }
142        }
143    }
144}
145
146void pack_w(const void* Wm, int kind, size_t ldw, int n0, int nvalid, int k0, int kc, float* dst) {
147    float tmp[1024];
148    for (int c = 0; c < NR; ++c) {
149        if (c >= nvalid) {
150            for (int k = 0; k < kc; ++k) dst[(size_t) k * NR + c] = 0.0f;
151            continue;
152        }
153        const size_t off = (size_t) (n0 + c) * ldw + (size_t) k0;
154        if (kind == 0) {
155            const float* p = (const float*) Wm + off;
156            for (int k = 0; k < kc; ++k) dst[(size_t) k * NR + c] = p[k];
157        } else {
158            for (int k = 0; k < kc; k += 1024) {
159                const int n = KN_MIN(1024, kc - k);
160                conv16(Wm, kind, off + (size_t) k, n, tmp);
161                for (int i = 0; i < n; ++i) dst[(size_t) (k + i) * NR + c] = tmp[i];
162            }
163        }
164    }
165}
166
167void conv(const void* src, int kind, size_t n, float* dst) {
168    for (size_t i = 0; i < n; i += 4096) conv16(src, kind, i, (int) KN_MIN((size_t) 4096, n - i), dst + i);
169}
170
171// ---- elementwise ----
172inline VR gelu_v(VR x) {
173    // 0.5 x (1 + tanh(u)), u = sqrt(2/pi) x (1 + 0.044715 x^2);  tanh(u) = 1 - 2 / (exp(2u) + 1)
174    const VR one = vr_set1(1.0f), two = vr_set1(2.0f);
175    const VR u = vr_mul(vr_mul(vr_set1(0.79788456080286535587989211986876f), x), vr_add(one, vr_mul(vr_mul(vr_set1(0.044715f), x), x)));
176    const VR e = vr_exp(vr_mul(two, u));
177    return vr_mul(vr_mul(vr_set1(0.5f), x), vr_sub(two, vr_div(two, vr_add(e, one))));      // 1 + tanh(u) = 2 - 2 / (exp(2u) + 1)
178}
179
180void gelu(float* x, size_t ldx, int rows, int n) {
181    for (int r = 0; r < rows; ++r) {
182        float* p = x + (size_t) r * ldx;
183        int i = 0;
184        for (; i + W <= n; i += W) vr_store(p + i, gelu_v(vr_load(p + i)));
185        if (i < n) {
186            float buf[W] = {0};
187            KN_COPY(buf, p + i, n - i);
188            vr_store(buf, gelu_v(vr_load(buf)));
189            KN_COPY(p + i, buf, n - i);
190        }
191    }
192}
193
194void layernorm(const float* x, float* y, int D, const float* w, const float* b, float eps) {
195    VR s = vr_zero();
196    int i = 0;
197    for (; i + W <= D; i += W) s = vr_add(s, vr_load(x + i));
198    float sum = vr_hadd(s);
199    for (; i < D; ++i) sum += x[i];
200    const float mean = sum / (float) D;
201    const VR vm = vr_set1(mean);
202    VR q = vr_zero();
203    for (i = 0; i + W <= D; i += W) {
204        const VR d = vr_sub(vr_load(x + i), vm);
205        q = vr_fma(d, d, q);
206    }
207    float ss = vr_hadd(q);
208    for (; i < D; ++i) { const float d = x[i] - mean; ss += d * d; }
209    const float scale = 1.0f / vr_sqrt1(ss / (float) D + eps);
210    const VR vs = vr_set1(scale);
211    for (i = 0; i + W <= D; i += W) vr_store(y + i, vr_add(vr_mul(vr_mul(vr_sub(vr_load(x + i), vm), vs), vr_load(w + i)), vr_load(b + i)));
212    for (; i < D; ++i) y[i] = (x[i] - mean) * scale * w[i] + b[i];
213}
214
215void add(float* x, const float* y, size_t n) {
216    size_t i = 0;
217    for (; i + W <= n; i += W) vr_store(x + i, vr_add(vr_load(x + i), vr_load(y + i)));
218    for (; i < n; ++i) x[i] += y[i];
219}
220
221void round16(float* p, size_t n, int kind) { round_buf(p, n, kind); }
222
223void softmax_update(float* S, size_t lds, int qrows, int nkeys, float* m, float* l, float* O, size_t ldo, int hd) {
224    for (int r = 0; r < qrows; ++r) {
225        float* s = S + (size_t) r * lds;
226        VR mxv = vr_set1(-3.0e38f);
227        int j = 0;
228        for (; j + W <= nkeys; j += W) mxv = vr_max(mxv, vr_load(s + j));
229        float mx = vr_hmax(mxv);
230        for (; j < nkeys; ++j) mx = KN_MAX(mx, s[j]);
231        const float mold = m[r], mnew = KN_MAX(mold, mx);
232        const float alpha = mold < -1.0e38f ? 0.0f : cpu_tier_expf(mold - mnew);
233        float* o = O + (size_t) r * ldo;
234        if (alpha != 1.0f) {
235            const VR va = vr_set1(alpha);
236            int d = 0;
237            for (; d + W <= hd; d += W) vr_store(o + d, vr_mul(vr_load(o + d), va));
238            for (; d < hd; ++d) o[d] *= alpha;
239        }
240        const VR vmn = vr_set1(mnew);
241        VR sv = vr_zero();
242        for (j = 0; j + W <= nkeys; j += W) {
243            const VR p = vr_exp(vr_sub(vr_load(s + j), vmn));
244            vr_store(s + j, p);
245            sv = vr_add(sv, p);
246        }
247        float sum = vr_hadd(sv);
248        for (; j < nkeys; ++j) { s[j] = cpu_tier_expf(s[j] - mnew); sum += s[j]; }
249        l[r] = l[r] * alpha + sum;
250        m[r] = mnew;
251    }
252}
253
254// The rotary and the position add, written as they were in vit_cpu.cpp (the same expressions in the same order), so a tier compiled with the flags vit_cpu.cpp
255// had (-mavx2 -mfma on GCC) contracts them the same way as before: the AVX2 / AVX-512 results stay bit-identical.
256void rope_row(float* row, size_t kstride, int heads, int hd, const float* c1, const float* s1, const float* c2, const float* s2) {
257    const int half = hd / 2, quarter = hd / 4;
258    for (int part = 0; part < 2; ++part)
259        for (int hh = 0; hh < heads; ++hh) {
260            float* v = row + (size_t) part * kstride + (size_t) hh * hd;
261            for (int j = 0; j < half; ++j) {
262                const float co = j < quarter ? c1[j] : c2[j - quarter], si = j < quarter ? s1[j] : s2[j - quarter];
263                const float a = v[j], b = v[j + half];
264                v[j] = a * co - b * si;
265                v[j + half] = a * si + b * co;
266            }
267        }
268}
269
270void pos_add(float* xr, const float* a, const float* b, const float* c, const float* d, float dx, float dy, int D) {
271    for (int i = 0; i < D; ++i) xr[i] += a[i] * (1 - dx) * (1 - dy) + b[i] * dx * (1 - dy) + c[i] * (1 - dx) * dy + d[i] * dx * dy;
272}
273
274}  // namespace kn
275}  // namespace
276
277const CpuOps& STRATA_KN_GETTER() {
278    static const CpuOps ops = {STRATA_KN_NAME, kn::MRF, kn::NR, kn::pack_w, kn::conv, kn::gemm, kn::gelu, kn::layernorm, kn::add, kn::round16, kn::softmax_update,
279                               kn::rope_row, kn::pos_add};
280    return ops;
281}
282
283}  // namespace strata_vit