okami.mom/strata

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

Niko1221Merge f-own-3v (ebfc6e62f) into f-own-int: the BF16 rounding default of the CPU tower and the MSVC fix in vit_ref.cppc2b701be3

main
17.6 KiB374 linesraw
1// tools/vision/own/vit_ref.cpp - see vit_ref.h
2#include "vit_ref.h"
3
4#include <algorithm>
5#include <atomic>
6#include <cmath>
7#include <cstdlib>
8#include <cstring>
9#include <thread>
10
11namespace strata_vit {
12
13namespace {
14
15template <class F>
16void parallel_for(int n, int nth, F f) {
17    if (nth <= 1 || n <= 1) {
18        for (int i = 0; i < n; ++i) f(i);
19        return;
20    }
21    nth = std::min(nth, n);
22    std::atomic<int> next{0};
23    auto worker = [&]() {
24        for (int i; (i = next.fetch_add(1)) < n;) f(i);
25    };
26    std::vector<std::thread> ts;
27    ts.reserve((size_t) nth - 1);
28    for (int t = 1; t < nth; ++t) ts.emplace_back(worker);
29    worker();
30    for (auto& t : ts) t.join();
31}
32
33// R rows of A against two rows of W: out[r][c] = dot(a_r, w_c)
34template <int R>
35inline void tile(const float* a, size_t lda, const float* w0, const float* w1, int K, float out[R][2]) {
36    float acc[R][2][8];
37    for (int r = 0; r < R; ++r)
38        for (int c = 0; c < 2; ++c)
39            for (int l = 0; l < 8; ++l) acc[r][c][l] = 0.0f;
40    int k = 0;
41    for (; k + 8 <= K; k += 8) {
42        for (int r = 0; r < R; ++r) {
43            const float* ar = a + (size_t) r * lda + k;
44            for (int l = 0; l < 8; ++l) {
45                acc[r][0][l] += ar[l] * w0[k + l];
46                acc[r][1][l] += ar[l] * w1[k + l];
47            }
48        }
49    }
50    for (int r = 0; r < R; ++r)
51        for (int c = 0; c < 2; ++c) {
52            float s = ((acc[r][c][0] + acc[r][c][4]) + (acc[r][c][1] + acc[r][c][5])) + ((acc[r][c][2] + acc[r][c][6]) + (acc[r][c][3] + acc[r][c][7]));
53            const float* w = c ? w1 : w0;
54            for (int kk = k; kk < K; ++kk) s += a[(size_t) r * lda + kk] * w[kk];
55            out[r][c] = s;
56        }
57}
58
59// C[M][N] = A[M][K] * W[N][K]^T (+ bias[N]); A rows lda apart, C rows ldc apart
60void gemm(const float* A, size_t lda, int M, int K, const float* W, int N, const float* bias, float* C, size_t ldc, int nth) {
61    const int chunk = std::max(4, ((M + nth * 2 - 1) / (nth * 2) + 3) / 4 * 4);
62    const int nchunks = (M + chunk - 1) / chunk;
63    parallel_for(nchunks, nth, [&](int ci) {
64        const int m0 = ci * chunk, m1 = std::min(M, m0 + chunk);
65        for (int n0 = 0; n0 < N; n0 += 8) {
66            const int n1 = std::min(N, n0 + 8);
67            for (int n = n0; n < n1; n += 2) {
68                const bool two = n + 1 < N;
69                const float* w0 = W + (size_t) n * K;
70                const float* w1 = two ? w0 + K : w0;
71                int m = m0;
72                for (; m + 4 <= m1; m += 4) {
73                    float o[4][2];
74                    tile<4>(A + (size_t) m * lda, lda, w0, w1, K, o);
75                    for (int r = 0; r < 4; ++r) {
76                        C[(size_t) (m + r) * ldc + n] = o[r][0] + (bias ? bias[n] : 0.0f);
77                        if (two) C[(size_t) (m + r) * ldc + n + 1] = o[r][1] + (bias ? bias[n + 1] : 0.0f);
78                    }
79                }
80                for (; m < m1; ++m) {
81                    float o[1][2];
82                    tile<1>(A + (size_t) m * lda, lda, w0, w1, K, o);
83                    C[(size_t) m * ldc + n] = o[0][0] + (bias ? bias[n] : 0.0f);
84                    if (two) C[(size_t) m * ldc + n + 1] = o[0][1] + (bias ? bias[n + 1] : 0.0f);
85                }
86            }
87        }
88    });
89}
90
91// y = LayerNorm(x) * w + b, per row of D, the sums in double (as ggml's norm)
92void layer_norm(const float* x, float* y, int rows, int D, const float* w, const float* b, float eps, int nth) {
93    parallel_for(rows, nth, [&](int r) {
94        const float* xr = x + (size_t) r * D;
95        double s = 0;
96        for (int i = 0; i < D; ++i) s += xr[i];
97        const float mean = (float) (s / D);
98        double v = 0;
99        for (int i = 0; i < D; ++i) { const double d = xr[i] - mean; v += d * d; }
100        const float scale = 1.0f / std::sqrt((float) (v / D) + eps);
101        float* yr = y + (size_t) r * D;
102        for (int i = 0; i < D; ++i) yr[i] = (xr[i] - mean) * scale * w[i] + b[i];
103    });
104}
105
106inline float gelu_tanh(float x) {
107    return 0.5f * x * (1.0f + std::tanh(0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x)));
108}
109
110void gelu_inplace(float* x, size_t n, int nth) {
111    const int blocks = (int) ((n + 4095) / 4096);
112    parallel_for(blocks, nth, [&](int bi) {
113        const size_t i0 = (size_t) bi * 4096, i1 = std::min(n, i0 + 4096);
114        for (size_t i = i0; i < i1; ++i) x[i] = gelu_tanh(x[i]);
115    });
116}
117
118inline float dot(const float* a, const float* b, int n) {
119    float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
120    int i = 0;
121    for (; i + 8 <= n; i += 8)
122        for (int l = 0; l < 8; ++l) acc[l] += a[i + l] * b[i + l];
123    float s = ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7]));
124    for (; i < n; ++i) s += a[i] * b[i];
125    return s;
126}
127
128// round to nearest even to BF16 / F16 and back (the values a 16-bit GEMM input has)
129inline float round_bf16(float f) {
130    uint32_t u;
131    std::memcpy(&u, &f, 4);
132    if ((u & 0x7fffffffu) > 0x7f800000u) return f;
133    u += 0x7fffu + ((u >> 16) & 1u);
134    u &= 0xffff0000u;
135    std::memcpy(&f, &u, 4);
136    return f;
137}
138
139inline float round_f16(float f) {
140    uint32_t u;
141    std::memcpy(&u, &f, 4);
142    const uint32_t sign = u & 0x80000000u;
143    const float a = std::fabs(f);
144    if (!(a < 65520.0f)) return f;                         // inf, nan, and what rounds to inf are left alone (not met in a tower)
145    if (a < 6.103515625e-05f) {                            // subnormal half: a multiple of 2^-24
146        const float q = std::nearbyint(a * 16777216.0f) / 16777216.0f;
147        return sign ? -q : q;
148    }
149    int e;
150    std::frexp(a, &e);                                     // a = m * 2^e, m in [0.5, 1): the half's ulp is 2^(e-11)
151    const float ulp = std::ldexp(1.0f, e - 11);
152    const float q = std::nearbyint(a / ulp) * ulp;
153    return sign ? -q : q;
154}
155
156void round_inplace(float* p, size_t n, int kind, int nth) {
157    if (kind == 0) return;
158    const int blocks = (int) ((n + 8191) / 8192);
159    parallel_for(blocks, nth, [&](int bi) {
160        const size_t i0 = (size_t) bi * 8192, i1 = std::min(n, i0 + 8192);
161        for (size_t i = i0; i < i1; ++i) p[i] = kind == 1 ? round_bf16(p[i]) : round_f16(p[i]);
162    });
163}
164
165bool read_t(const Gguf& gg, const std::string& name, std::vector<float>& dst, std::string& err) {
166    const GgufTensorInfo* t = gg.tensor(name);
167    if (!t) { err = "the mmproj file lacks the tensor " + name; return false; }
168    dst.resize((size_t) t->nelem());
169    return gg.read_f32(*t, dst.data(), err);
170}
171
172}  // namespace
173
174double cosine(const float* a, const float* b, size_t n) {
175    double ab = 0, aa = 0, bb = 0;
176    for (size_t i = 0; i < n; ++i) { ab += (double) a[i] * b[i]; aa += (double) a[i] * a[i]; bb += (double) b[i] * b[i]; }
177    return aa > 0 && bb > 0 ? ab / std::sqrt(aa * bb) : 0.0;
178}
179
180bool VitRef::load(const Gguf& gg, const VitGeometry& g, std::string& err) {
181    g_ = g;
182    std::string why;
183    if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; }
184    // the two temporal taps of the patch embedding are summed: a still picture is fed to both
185    std::vector<float> w0, w1;
186    if (!read_t(gg, "v.patch_embd.weight", w0, err)) return false;
187    if (g.patch_taps == 2) {
188        if (!read_t(gg, "v.patch_embd.weight.1", w1, err)) return false;
189        for (size_t i = 0; i < w0.size(); ++i) w0[i] += w1[i];
190    }
191    patch_w_ = std::move(w0);
192    if (!read_t(gg, "v.patch_embd.bias", patch_b_, err) || !read_t(gg, "v.position_embd.weight", pos_, err) ||
193        !read_t(gg, "v.post_ln.weight", post_w_, err) || !read_t(gg, "v.post_ln.bias", post_b_, err) ||
194        !read_t(gg, "mm.0.weight", mm0_w_, err) || !read_t(gg, "mm.0.bias", mm0_b_, err) ||
195        !read_t(gg, "mm.2.weight", mm2_w_, err) || !read_t(gg, "mm.2.bias", mm2_b_, err))
196        return false;
197    act_round_ = 0;
198    if (const char* e = std::getenv("STRATA_VIT_REF_ROUND"); e && std::atoi(e) != 0) {
199        const GgufTensorInfo* t = gg.tensor("v.blk.0.attn_qkv.weight");
200        act_round_ = t && t->type == GT_BF16 ? 1 : t && t->type == GT_F16 ? 2 : 0;
201    }
202    layers_.assign((size_t) g.layers, Layer{});
203    for (int il = 0; il < g.layers; ++il) {
204        Layer& L = layers_[(size_t) il];
205        const std::string p = "v.blk." + std::to_string(il) + ".";
206        if (!read_t(gg, p + "ln1.weight", L.ln1_w, err) || !read_t(gg, p + "ln1.bias", L.ln1_b, err) ||
207            !read_t(gg, p + "ln2.weight", L.ln2_w, err) || !read_t(gg, p + "ln2.bias", L.ln2_b, err) ||
208            !read_t(gg, p + "attn_qkv.weight", L.qkv_w, err) || !read_t(gg, p + "attn_qkv.bias", L.qkv_b, err) ||
209            !read_t(gg, p + "attn_out.weight", L.o_w, err) || !read_t(gg, p + "attn_out.bias", L.o_b, err) ||
210            !read_t(gg, p + "ffn_up.weight", L.up_w, err) || !read_t(gg, p + "ffn_up.bias", L.up_b, err) ||
211            !read_t(gg, p + "ffn_down.weight", L.down_w, err) || !read_t(gg, p + "ffn_down.bias", L.down_b, err))
212            return false;
213    }
214    return true;
215}
216
217bool VitRef::encode(const PreparedImage& img, int threads, std::vector<float>& rows, int& nx, int& ny, std::string& err) const {
218    const VitGeometry& g = g_;
219    const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn;
220    if (layers_.empty()) { err = "the tower is not loaded"; return false; }
221    if (HD > 128) { err = "head size above 128 is not handled by the reference"; return false; }
222    if (img.w <= 0 || img.h <= 0 || img.w % g.align() != 0 || img.h % g.align() != 0) { err = "the picture size is not a multiple of patch * merge"; return false; }
223    const int nth = threads > 0 ? threads : (int) std::max(1u, std::thread::hardware_concurrency());
224    const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2;
225    nx = pw / 2;
226    ny = ph / 2;
227
228    // ---- positions of the tokens (merge order: 2x2 blocks row by row, inside a block dy outer, dx inner) ----
229    std::vector<int> ty((size_t) N), tx((size_t) N);
230    for (int t = 0; t < N; ++t) {
231        const int b = t / 4, r = t % 4;
232        ty[(size_t) t] = 2 * (b / nbx) + r / 2;
233        tx[(size_t) t] = 2 * (b % nbx) + r % 2;
234    }
235
236    // ---- patch embedding: im2col in merge order, one GEMM ----
237    const int K0 = 3 * P * P;
238    std::vector<float> A((size_t) N * K0);
239    const size_t plane = (size_t) img.w * img.h;
240    parallel_for(N, nth, [&](int t) {
241        float* a = &A[(size_t) t * K0];
242        const int py = ty[(size_t) t], px = tx[(size_t) t];
243        for (int c = 0; c < 3; ++c)
244            for (int ky = 0; ky < P; ++ky)
245                std::memcpy(a + (size_t) c * P * P + (size_t) ky * P, &img.chw[c * plane + (size_t) (py * P + ky) * img.w + (size_t) px * P], (size_t) P * sizeof(float));
246    });
247    std::vector<float> x((size_t) N * D);
248    gemm(A.data(), (size_t) K0, N, K0, patch_w_.data(), D, patch_b_.data(), x.data(), (size_t) D, nth);
249    A.clear();
250    A.shrink_to_fit();
251
252    // ---- the position table resized to the patch grid (bilinear, align corners: ggml's upscale with the same float maths), added ----
253    {
254        const int G = g.pos_grid;
255        float sfx = (float) pw / G, sfy = (float) ph / G;
256        if (pw > 1 && G > 1) sfx = (float) (pw - 1) / (G - 1);
257        if (ph > 1 && G > 1) sfy = (float) (ph - 1) / (G - 1);
258        parallel_for(N, nth, [&](int t) {
259            const float fy = (float) ty[(size_t) t] / sfy, fx = (float) tx[(size_t) t] / sfx;
260            int y0 = (int) std::floor(fy), x0 = (int) std::floor(fx);
261            int y1 = y0 + 1, x1 = x0 + 1;
262            y0 = std::max(0, std::min(y0, G - 1)); y1 = std::max(0, std::min(y1, G - 1));
263            x0 = std::max(0, std::min(x0, G - 1)); x1 = std::max(0, std::min(x1, G - 1));
264            const float dy = std::max(0.0f, std::min(fy - (float) y0, 1.0f)), dx = std::max(0.0f, std::min(fx - (float) x0, 1.0f));
265            const float* a = &pos_[((size_t) y0 * G + x0) * D];
266            const float* b = &pos_[((size_t) y0 * G + x1) * D];
267            const float* c = &pos_[((size_t) y1 * G + x0) * D];
268            const float* d = &pos_[((size_t) y1 * G + x1) * D];
269            float* xr = &x[(size_t) t * D];
270            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;
271        });
272    }
273
274    // ---- rotary tables: pair j of a head (elements j and j + HD/2), j < HD/4 turns with the row, the rest with the column ----
275    const int half = HD / 2, quarter = HD / 4;
276    std::vector<float> inv_freq((size_t) quarter);
277    {
278        const float theta_scale = std::pow(g.rope_theta, -2.0f / (float) half);
279        float th = 1.0f;
280        for (int j = 0; j < quarter; ++j) { inv_freq[(size_t) j] = th; th *= theta_scale; }
281    }
282    std::vector<float> rcos((size_t) N * half), rsin((size_t) N * half);
283    parallel_for(N, nth, [&](int t) {
284        for (int j = 0; j < half; ++j) {
285            const float pos = (float) (j < quarter ? ty[(size_t) t] : tx[(size_t) t]);
286            const float ang = pos * inv_freq[(size_t) (j % quarter)];
287            rcos[(size_t) t * half + j] = std::cos(ang);
288            rsin[(size_t) t * half + j] = std::sin(ang);
289        }
290    });
291
292    // ---- the layers ----
293    std::vector<float> h((size_t) N * D), qkv((size_t) N * 3 * D), ctx((size_t) N * D), tmp((size_t) N * D), up((size_t) N * F);
294    const float kq_scale = 1.0f / std::sqrt((float) HD);
295    for (const Layer& L : layers_) {
296        layer_norm(x.data(), h.data(), N, D, L.ln1_w.data(), L.ln1_b.data(), g.eps, nth);
297        round_inplace(h.data(), h.size(), act_round_, nth);
298        gemm(h.data(), (size_t) D, N, D, L.qkv_w.data(), 3 * D, L.qkv_b.data(), qkv.data(), (size_t) 3 * D, nth);
299        // rotary on q and k
300        parallel_for(N, nth, [&](int t) {
301            float* row = &qkv[(size_t) t * 3 * D];
302            const float* cs = &rcos[(size_t) t * half];
303            const float* sn = &rsin[(size_t) t * half];
304            for (int part = 0; part < 2; ++part)
305                for (int hh = 0; hh < H; ++hh) {
306                    float* v = row + (size_t) part * D + (size_t) hh * HD;
307                    for (int j = 0; j < half; ++j) {
308                        const float a = v[j], b = v[j + half];
309                        v[j] = a * cs[j] - b * sn[j];
310                        v[j + half] = a * sn[j] + b * cs[j];
311                    }
312                }
313        });
314        round_inplace(qkv.data(), qkv.size(), act_round_ ? 2 : 0, nth);   // (diagnostic) mtmd's flash attention holds q, k, v in F16
315        // global attention, 4 queries at a time per head
316        static constexpr int QB = 4;      // static constexpr, not const: MSVC does not treat a const local used inside the lambda as a constant (C2131 at acc[QB][128])
317        const int nqb = (N + QB - 1) / QB;
318        parallel_for(H * nqb, nth, [&](int task) {
319            const int hh = task / nqb, q0 = (task % nqb) * QB, nq = std::min(QB, N - q0);
320            std::vector<float> sc((size_t) QB * N);
321            const size_t stride = (size_t) 3 * D;
322            const float* qb = qkv.data() + (size_t) hh * HD;
323            const float* kb = qkv.data() + (size_t) D + (size_t) hh * HD;
324            const float* vb = qkv.data() + (size_t) 2 * D + (size_t) hh * HD;
325            for (int j = 0; j < N; ++j) {
326                const float* kj = kb + (size_t) j * stride;
327                for (int qi = 0; qi < nq; ++qi) sc[(size_t) qi * N + j] = dot(qb + (size_t) (q0 + qi) * stride, kj, HD) * kq_scale;
328            }
329            for (int qi = 0; qi < nq; ++qi) {
330                float* s = &sc[(size_t) qi * N];
331                float mx = s[0];
332                for (int j = 1; j < N; ++j) mx = std::max(mx, s[j]);
333                double den = 0;
334                for (int j = 0; j < N; ++j) { s[j] = std::exp(s[j] - mx); den += s[j]; }
335                const float inv = (float) (1.0 / den);
336                for (int j = 0; j < N; ++j) s[j] *= inv;
337            }
338            float acc[QB][128];
339            for (int qi = 0; qi < nq; ++qi) for (int i = 0; i < HD; ++i) acc[qi][i] = 0.0f;
340            for (int j = 0; j < N; ++j) {
341                const float* vj = vb + (size_t) j * stride;
342                for (int qi = 0; qi < nq; ++qi) {
343                    const float p = sc[(size_t) qi * N + j];
344                    for (int i = 0; i < HD; ++i) acc[qi][i] += p * vj[i];
345                }
346            }
347            for (int qi = 0; qi < nq; ++qi) std::memcpy(&ctx[(size_t) (q0 + qi) * D + (size_t) hh * HD], acc[qi], (size_t) HD * sizeof(float));
348        });
349        round_inplace(ctx.data(), ctx.size(), act_round_, nth);
350        gemm(ctx.data(), (size_t) D, N, D, L.o_w.data(), D, L.o_b.data(), tmp.data(), (size_t) D, nth);
351        for (size_t i = 0; i < x.size(); ++i) x[i] += tmp[i];
352        layer_norm(x.data(), h.data(), N, D, L.ln2_w.data(), L.ln2_b.data(), g.eps, nth);
353        round_inplace(h.data(), h.size(), act_round_, nth);
354        gemm(h.data(), (size_t) D, N, D, L.up_w.data(), F, L.up_b.data(), up.data(), (size_t) F, nth);
355        gelu_inplace(up.data(), up.size(), nth);
356        round_inplace(up.data(), up.size(), act_round_, nth);
357        gemm(up.data(), (size_t) F, N, F, L.down_w.data(), D, L.down_b.data(), tmp.data(), (size_t) D, nth);
358        for (size_t i = 0; i < x.size(); ++i) x[i] += tmp[i];
359    }
360
361    // ---- post norm and the merger ----
362    layer_norm(x.data(), h.data(), N, D, post_w_.data(), post_b_.data(), g.eps, nth);
363    const int M = N / 4, Kin = 4 * D, Hid = g.merger_hidden, O = g.out_dim;
364    std::vector<float> m1((size_t) M * Hid);
365    round_inplace(h.data(), h.size(), act_round_, nth);
366    gemm(h.data(), (size_t) Kin, M, Kin, mm0_w_.data(), Hid, mm0_b_.data(), m1.data(), (size_t) Hid, nth);
367    gelu_inplace(m1.data(), m1.size(), nth);
368    rows.assign((size_t) M * O, 0.0f);
369    round_inplace(m1.data(), m1.size(), act_round_, nth);
370    gemm(m1.data(), (size_t) Hid, M, Hid, mm2_w_.data(), O, mm2_b_.data(), rows.data(), (size_t) O, nth);
371    return true;
372}
373
374}  // namespace strata_vit