okami.mom/strata

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

Niko1221Merge f-vit-exact: the picture reader follows the float32 reference closer on the CPU and on the GPU60d431e2a

main
23.1 KiB405 linesraw
1// tools/vision/own/vit_cpu.cpp - see vit_cpu.h
2#include "vit_cpu.h"
3
4#include <algorithm>
5#include <chrono>
6#include <cmath>
7#include <cstdio>
8#include <cstdlib>
9#include <cstring>
10#include <thread>
11
12namespace strata_vit {
13
14namespace {
15
16constexpr int kKC = 256;        // the k block of a matrix product: a packed weight panel is kKC x (2 tiles) floats
17constexpr int kQB = 48;         // the unit of query rows of an attention task (a multiple of every tier's MR)
18constexpr int kQBDefault = 96;  // query rows of an attention task: every task streams all of a head's K and V once, so 96 halves that traffic against 48
19                                // (MSVC, Ryzen 5 7600, big1024: 0.988 of mtmd-CPU's time against 1.000 with 48 in the same session; RESULTS-OWN-3V.md D2)
20constexpr int kTK = 256;        // keys per attention tile
21constexpr int kRowsChunk = 4096;   // rows of the activations that are live at once outside the attention
22
23struct Mat {                     // a weight matrix [rows = out][cols = in]
24    std::vector<uint16_t> pk;    // BF16 / F16 matrices as 16-bit panels [ceil(rows / NR)][cols][NR] (the rows past `rows` zero), made at load; the stored copy is not kept
25    std::vector<float> f32;      // anything else (F32, Q8_0 expanded)
26    int kind = 0;                // 0 float32, 1 BF16, 2 F16
27    int rows = 0, cols = 0;
28    const void* data() const { return f32.data(); }       // kind 0 only (the 16-bit matrices live in pk)
29};
30
31struct Layer {
32    std::vector<float> ln1_w, ln1_b, ln2_w, ln2_b, qkv_b, o_b, up_b, down_b;
33    Mat qkv, o, up, down;
34};
35
36}  // namespace
37
38struct VitCpu::Impl {
39    VitGeometry g;
40    const CpuOps* ops = nullptr;
41    int act_round = 0;                  // STRATA_VIT_REF_ROUND: 0 none, 1 BF16, 2 F16 (the weight's type)
42    std::vector<float> patch_b, pos, post_w, post_b, mm0_b, mm2_b;
43    Mat patch_w, mm0, mm2;
44    std::vector<Layer> layers;
45    std::unique_ptr<Team> team;
46    int team_threads = 0;
47
48    bool read_f(const Gguf& gg, const std::string& name, std::vector<float>& dst, std::string& err) {
49        const GgufTensorInfo* t = gg.tensor(name);
50        if (!t) { err = "the mmproj file lacks the tensor " + name; return false; }
51        dst.resize((size_t) t->nelem());
52        return gg.read_f32(*t, dst.data(), err);
53    }
54    bool read_m(const Gguf& gg, const std::string& name, Mat& m, std::string& err) {
55        const GgufTensorInfo* t = gg.tensor(name);
56        if (!t || t->ne.size() != 2) { err = "the mmproj file lacks the matrix " + name; return false; }
57        m.cols = (int) t->ne[0];
58        m.rows = (int) t->ne[1];
59        const size_t n = (size_t) t->nelem();
60        if (t->type == GT_F16 || t->type == GT_BF16) {
61            m.kind = t->type == GT_BF16 ? 1 : 2;
62            std::vector<uint16_t> raw(n);
63            if (!gg.read_raw(*t, raw.data(), err)) return false;
64            // panels of NR rows, k-major inside a panel: a product task converts a [kc][NR] slice to float with one contiguous pass
65            const int NR = ops->NR;
66            const size_t ptiles = ((size_t) m.rows + NR - 1) / NR;
67            m.pk.assign(ptiles * (size_t) m.cols * NR, 0);
68            for (int r = 0; r < m.rows; ++r) {
69                const uint16_t* src = &raw[(size_t) r * m.cols];
70                uint16_t* dst = &m.pk[(size_t) (r / NR) * m.cols * NR + (size_t) (r % NR)];
71                for (int k = 0; k < m.cols; ++k) dst[(size_t) k * NR] = src[k];
72            }
73            return true;
74        }
75        m.kind = 0;
76        m.f32.resize(n);
77        return gg.read_f32(*t, m.f32.data(), err);
78    }
79
80    template <class F>
81    void run(int n, F f) { team->run(n, [&](int task, int thr) { f(task, thr); }); }
82
83    // rows of simple per-row work, 16 rows per task
84    template <class F>
85    void rows_par(int n, F f) {
86        const int per = 16, tasks = (n + per - 1) / per;
87        team->run(tasks, [&](int task, int) {
88            const int r1 = std::min(n, (task + 1) * per);
89            for (int r = task * per; r < r1; ++r) f(r);
90        });
91    }
92
93    void round_inplace(float* p, size_t n, int kind) {
94        if (kind == 0) return;
95        const size_t blk = 16384;
96        const int tasks = (int) ((n + blk - 1) / blk);
97        team->run(tasks, [&](int task, int) {
98            const size_t i0 = (size_t) task * blk, i1 = std::min(n, i0 + blk);
99            ops->round16(p + i0, i1 - i0, kind);
100        });
101    }
102
103    // C[M][w.rows] (init-mode, see CpuOps::gemm) = A[M][w.cols] * w^T (+ bias), optionally GELU on the result
104    void linear(const Mat& w, const float* A, size_t lda, int M, float* C, size_t ldc, int init, const float* bias, bool gelu, std::vector<std::vector<float>>& scratch) {
105        const int NR = ops->NR, PW = 2 * NR, K = w.cols, N = w.rows;
106        const int npan = (N + PW - 1) / PW;
107        const int target = 4 * team->size();
108        int mslabs = std::max(1, std::min((target + npan - 1) / npan, (M + 47) / 48));
109        const int slab = (((M + mslabs - 1) / mslabs) + ops->MR - 1) / ops->MR * ops->MR;
110        mslabs = (M + slab - 1) / slab;
111        team->run(npan * mslabs, [&](int task, int thr) {
112            const int p = task % npan, s = task / npan;
113            const int m0 = s * slab, mr = std::min(slab, M - m0);
114            const int n0 = p * PW, nv = std::min(PW, N - n0);
115            float* buf = scratch[(size_t) thr].data();
116            for (int k0 = 0; k0 < K; k0 += kKC) {
117                const int kc = std::min(kKC, K - k0);
118                for (int t = 0; t < 2; ++t) {
119                    const int tv = std::max(0, std::min(NR, nv - t * NR));
120                    if (tv <= 0) continue;
121                    if (w.kind == 0) ops->pack_w(w.data(), 0, (size_t) K, n0 + t * NR, tv, k0, kc, buf + (size_t) t * kKC * NR);
122                    else ops->conv(&w.pk[((size_t) (p * 2 + t) * K + (size_t) k0) * NR], w.kind, (size_t) kc * NR, buf + (size_t) t * kKC * NR);
123                }
124                for (int t = 0; t < 2; ++t) {
125                    const int tv = std::max(0, std::min(NR, nv - t * NR));
126                    if (tv <= 0) continue;
127                    const int col = n0 + t * NR;
128                    ops->gemm(A + (size_t) m0 * lda + k0, lda, mr, buf + (size_t) t * kKC * NR, (size_t) NR, kc, tv, C + (size_t) m0 * ldc + col, ldc,
129                              k0 == 0 ? init : 1, bias ? bias + col : nullptr);
130                }
131            }
132            if (gelu) ops->gelu(C + (size_t) m0 * ldc + n0, ldc, mr, nv);
133        });
134    }
135};
136
137VitCpu::VitCpu() : impl_(new Impl()) {}
138VitCpu::~VitCpu() = default;
139const VitGeometry& VitCpu::geometry() const { return impl_->g; }
140const char* VitCpu::isa_name() const { return impl_->ops ? impl_->ops->name : "none"; }
141
142bool VitCpu::load(const Gguf& gg, const VitGeometry& g, std::string& err) {
143    Impl& m = *impl_;
144    std::string why;
145    if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; }
146    m.g = g;
147    m.ops = &cpu_ops(quant::best_isa());
148    // the patch embedding: the two temporal taps summed (a still picture is fed to both), kept float32 (a small matrix)
149    {
150        const GgufTensorInfo* t0 = gg.tensor("v.patch_embd.weight");
151        if (!t0) { err = "the mmproj file lacks v.patch_embd.weight"; return false; }
152        std::vector<float> w((size_t) t0->nelem());
153        if (!gg.read_f32(*t0, w.data(), err)) return false;
154        if (w.size() != (size_t) g.width * 3 * g.patch * g.patch) { err = "the patch embedding has an unexpected size"; return false; }
155        if (g.patch_taps == 2) {
156            const GgufTensorInfo* t1 = gg.tensor("v.patch_embd.weight.1");
157            std::vector<float> w1(w.size());
158            if (!t1 || !gg.read_f32(*t1, w1.data(), err)) { if (err.empty()) err = "the mmproj file lacks v.patch_embd.weight.1"; return false; }
159            for (size_t i = 0; i < w.size(); ++i) w[i] += w1[i];
160        }
161        m.patch_w.kind = 0;
162        m.patch_w.rows = g.width;
163        m.patch_w.cols = 3 * g.patch * g.patch;
164        m.patch_w.f32 = std::move(w);
165    }
166    if (!m.read_f(gg, "v.patch_embd.bias", m.patch_b, err) || !m.read_f(gg, "v.position_embd.weight", m.pos, err) || !m.read_f(gg, "v.post_ln.weight", m.post_w, err) ||
167        !m.read_f(gg, "v.post_ln.bias", m.post_b, err) || !m.read_m(gg, "mm.0.weight", m.mm0, err) || !m.read_f(gg, "mm.0.bias", m.mm0_b, err) ||
168        !m.read_m(gg, "mm.2.weight", m.mm2, err) || !m.read_f(gg, "mm.2.bias", m.mm2_b, err))
169        return false;
170    m.layers.assign((size_t) g.layers, Layer{});
171    for (int il = 0; il < g.layers; ++il) {
172        Layer& L = m.layers[(size_t) il];
173        const std::string p = "v.blk." + std::to_string(il) + ".";
174        if (!m.read_f(gg, p + "ln1.weight", L.ln1_w, err) || !m.read_f(gg, p + "ln1.bias", L.ln1_b, err) || !m.read_f(gg, p + "ln2.weight", L.ln2_w, err) ||
175            !m.read_f(gg, p + "ln2.bias", L.ln2_b, err) || !m.read_m(gg, p + "attn_qkv.weight", L.qkv, err) || !m.read_f(gg, p + "attn_qkv.bias", L.qkv_b, err) ||
176            !m.read_m(gg, p + "attn_out.weight", L.o, err) || !m.read_f(gg, p + "attn_out.bias", L.o_b, err) || !m.read_m(gg, p + "ffn_up.weight", L.up, err) ||
177            !m.read_f(gg, p + "ffn_up.bias", L.up_b, err) || !m.read_m(gg, p + "ffn_down.weight", L.down, err) || !m.read_f(gg, p + "ffn_down.bias", L.down_b, err))
178            return false;
179    }
180    m.act_round = vit_cpu_round_kind(m.layers.empty() ? 0 : m.layers[0].qkv.kind, std::getenv("STRATA_VIT_REF_ROUND"));
181    return true;
182}
183
184int vit_cpu_round_kind(int weight_kind, const char* env) {
185    // No rounding by default, for every weight type: the tower then follows the float32 reference (VitRef).  Until 11-14 BF16 weights (Qwen3.8) rounded
186    // the matrix inputs to BF16 by default, which matched llama.cpp's reader on code4217.png (0.9997) but not float32: 16 pictures, 12,308 tokens, 45 under
187    // cosine 0.99 against VitRef with the rounding, 0 without (code4217 token 47: 0.627 -> 1.000).  STRATA_VIT_REF_ROUND=1 brings the rounding back.
188    // float32 or Q8_0-expanded matrices have no 16-bit type to round to.
189    if (weight_kind != 1 && weight_kind != 2) return 0;
190    if (env && *env) return std::atoi(env) != 0 ? weight_kind : 0;
191    return 0;
192}
193
194bool VitCpu::encode(const PreparedImage& img, int threads, std::vector<float>& rows, int& nx, int& ny, std::string& err) {
195    Impl& m = *impl_;
196    const VitGeometry& g = m.g;
197    if (m.layers.empty()) { err = "the tower is not loaded"; return false; }
198    const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn;
199    if (HD > 128 || HD % 4 != 0) { err = "this head size is not handled by the CPU tower"; return false; }
200    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; }
201    int nth = threads > 0 ? threads : (int) std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
202    if (!m.team || m.team_threads != nth) { m.team.reset(new Team(nth)); m.team_threads = nth; }
203    const CpuOps& ops = *m.ops;
204    // STRATA_VIT_PROF=1 (a diagnostic, stderr only, off by default): the time of each stage (every stage ends with its team run, so no extra wait)
205    static const bool prof = std::getenv("STRATA_VIT_PROF") != nullptr;
206    double pt[12] = {0};
207    auto pclock = [] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); };
208    double pmark = prof ? pclock() : 0.0;
209    auto stage = [&](int s) {
210        if (!prof) return;
211        const double t = pclock();
212        pt[s] += t - pmark;
213        pmark = t;
214    };
215    const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2;
216    nx = pw / 2;
217    ny = ph / 2;
218    const int R = std::min(N, kRowsChunk);
219
220    std::vector<int> ty((size_t) N), tx((size_t) N);
221    for (int t = 0; t < N; ++t) {
222        const int b = t / 4, r = t % 4;
223        ty[(size_t) t] = 2 * (b / nbx) + r / 2;
224        tx[(size_t) t] = 2 * (b % nbx) + r % 2;
225    }
226    std::vector<std::vector<float>> scratch((size_t) nth, std::vector<float>((size_t) kKC * 2 * ops.NR));
227
228    // ---- patch embedding: im2col of a chunk of rows in merge order, one product; then the position table (bilinear, align corners) ----
229    const int K0 = 3 * P * P;
230    std::vector<float> x((size_t) N * D);
231    {
232        std::vector<float> A((size_t) R * K0);
233        const size_t plane = (size_t) img.w * img.h;
234        for (int r0 = 0; r0 < N; r0 += R) {
235            const int rn = std::min(R, N - r0);
236            m.rows_par(rn, [&](int i) {
237                const int t = r0 + i;
238                float* a = &A[(size_t) i * K0];
239                const int py = ty[(size_t) t], px = tx[(size_t) t];
240                for (int c = 0; c < 3; ++c)
241                    for (int ky = 0; ky < P; ++ky)
242                        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));
243            });
244            m.linear(m.patch_w, A.data(), (size_t) K0, rn, x.data() + (size_t) r0 * D, (size_t) D, 0, m.patch_b.data(), false, scratch);
245        }
246    }
247    {
248        const int G = g.pos_grid;
249        float sfx = (float) pw / G, sfy = (float) ph / G;
250        if (pw > 1 && G > 1) sfx = (float) (pw - 1) / (G - 1);
251        if (ph > 1 && G > 1) sfy = (float) (ph - 1) / (G - 1);
252        m.rows_par(N, [&](int t) {
253            const float fy = (float) ty[(size_t) t] / sfy, fx = (float) tx[(size_t) t] / sfx;
254            int y0 = (int) std::floor(fy), x0 = (int) std::floor(fx), y1 = y0 + 1, x1 = x0 + 1;
255            y0 = std::max(0, std::min(y0, G - 1)); y1 = std::max(0, std::min(y1, G - 1));
256            x0 = std::max(0, std::min(x0, G - 1)); x1 = std::max(0, std::min(x1, G - 1));
257            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));
258            const float* a = &m.pos[((size_t) y0 * G + x0) * D];
259            const float* b = &m.pos[((size_t) y0 * G + x1) * D];
260            const float* c = &m.pos[((size_t) y1 * G + x0) * D];
261            const float* d = &m.pos[((size_t) y1 * G + x1) * D];
262            ops.pos_add(&x[(size_t) t * D], a, b, c, d, dx, dy, D);      // a tier kernel: its result depends on multiply-add contraction (cpu_tier.h)
263        });
264    }
265
266    // ---- 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 ----
267    const int half = HD / 2, quarter = HD / 4;
268    std::vector<float> rc((size_t) ph * quarter), rs((size_t) ph * quarter), cc((size_t) pw * quarter), cs((size_t) pw * quarter);
269    {
270        const float theta_scale = std::pow(g.rope_theta, -2.0f / (float) half);
271        std::vector<float> inv((size_t) quarter);
272        float th = 1.0f;
273        for (int j = 0; j < quarter; ++j) { inv[(size_t) j] = th; th *= theta_scale; }
274        for (int p = 0; p < ph; ++p)
275            for (int j = 0; j < quarter; ++j) { const float a = (float) p * inv[(size_t) j]; rc[(size_t) p * quarter + j] = std::cos(a); rs[(size_t) p * quarter + j] = std::sin(a); }
276        for (int p = 0; p < pw; ++p)
277            for (int j = 0; j < quarter; ++j) { const float a = (float) p * inv[(size_t) j]; cc[(size_t) p * quarter + j] = std::cos(a); cs[(size_t) p * quarter + j] = std::sin(a); }
278    }
279    const float kq_scale = 1.0f / std::sqrt((float) HD);
280    stage(0);
281
282    // ---- the layers ----
283    const size_t slack = 256;                                    // the product with V reads up to a tile past a head's columns
284    std::vector<float> qkv((size_t) N * 3 * D + slack, 0.0f), ctx((size_t) N * D);
285    const int Np = (N + 63) / 64 * 64;
286    std::vector<float> KT((size_t) H * HD * Np, 0.0f);
287    std::vector<float> hbuf((size_t) R * D), up((size_t) R * F);
288    const int OD = (HD + 15) / 16 * 16;
289    // Attention layout (RESULTS-OWN-3V.md D2): V packed per head (VP[h][j][d], rows of HD floats) instead of read in place from the qkv rows (a 3,456-float
290    // stride: one cache line used per row and key); and queries per task. Both change only addresses and the grouping of query rows (every query row's
291    // sums run in the same order), so the results are bit-identical.  STRATA_VIT_CPU_VPACK=0 / STRATA_VIT_CPU_QB=<multiple of 48>: diagnostics.
292    static const bool vpack = [] { const char* e = std::getenv("STRATA_VIT_CPU_VPACK"); return !(e && std::atoi(e) == 0); }();
293    static const int QB = [] { const char* e = std::getenv("STRATA_VIT_CPU_QB"); const int v = e ? std::atoi(e) : 0; return v >= kQB && v % kQB == 0 ? v : kQBDefault; }();
294    const int attn_tasks_q = (N + QB - 1) / QB;
295    std::vector<float> VP(vpack ? (size_t) H * N * HD + slack : 0);
296    std::vector<std::vector<float>> sscr((size_t) nth, std::vector<float>((size_t) QB * kTK + (size_t) QB * OD + 2 * QB));
297    const size_t D3 = (size_t) 3 * D;
298
299    for (const Layer& L : m.layers) {
300        // q, k, v of every token
301        for (int r0 = 0; r0 < N; r0 += R) {
302            const int rn = std::min(R, N - r0);
303            m.rows_par(rn, [&](int i) { ops.layernorm(x.data() + (size_t) (r0 + i) * D, hbuf.data() + (size_t) i * D, D, L.ln1_w.data(), L.ln1_b.data(), g.eps); });
304            m.round_inplace(hbuf.data(), (size_t) rn * D, m.act_round);
305            m.linear(L.qkv, hbuf.data(), (size_t) D, rn, qkv.data() + (size_t) r0 * D3, D3, 0, L.qkv_b.data(), false, scratch);
306        }
307        stage(1);
308        m.rows_par(N, [&](int t) {       // the rotary on q and k (with the attention's scale on q, after the optional 16-bit rounding)
309            float* row = qkv.data() + (size_t) t * D3;
310            const float* c1 = &rc[(size_t) ty[(size_t) t] * quarter];
311            const float* s1 = &rs[(size_t) ty[(size_t) t] * quarter];
312            const float* c2 = &cc[(size_t) tx[(size_t) t] * quarter];
313            const float* s2 = &cs[(size_t) tx[(size_t) t] * quarter];
314            ops.rope_row(row, (size_t) D, H, HD, c1, s1, c2, s2);       // a tier kernel, as pos_add
315            if (m.act_round) ops.round16(row, D3, 2);
316            for (int i = 0; i < D; ++i) row[i] *= kq_scale;
317        });
318        // K transposed per head: KT[h][d][j]
319        {
320            const int jb = 64, njb = (N + jb - 1) / jb;
321            m.team->run(H * njb, [&](int task, int) {
322                const int hh = task / njb, j0 = (task % njb) * jb, j1 = std::min(N, j0 + jb);
323                for (int j = j0; j < j1; ++j) {
324                    const float* kr = qkv.data() + (size_t) j * D3 + D + (size_t) hh * HD;
325                    float* kt = KT.data() + (size_t) hh * HD * Np + j;
326                    for (int d = 0; d < HD; ++d) kt[(size_t) d * Np] = kr[d];
327                    if (vpack) std::memcpy(VP.data() + ((size_t) hh * N + j) * HD, kr + D, sizeof(float) * (size_t) HD);   // v follows k in the row
328                }
329            });
330        }
331        stage(2);
332        // tiled attention with an online softmax: a task is a head and a block of kQB queries
333        m.team->run(H * attn_tasks_q, [&](int task, int thr) {
334            const int hh = task / attn_tasks_q, q0 = (task % attn_tasks_q) * QB, qr = std::min(QB, N - q0);
335            float* S = sscr[(size_t) thr].data();
336            float* O = S + (size_t) QB * kTK;
337            float* mx = O + (size_t) QB * OD;
338            float* ls = mx + QB;
339            std::memset(O, 0, sizeof(float) * (size_t) QB * OD);
340            for (int r = 0; r < QB; ++r) { mx[r] = -3.0e38f; ls[r] = 0.0f; }
341            double ta = 0.0, tb = 0.0, tc = 0.0;
342            const bool pa = prof && thr == 0;      // the split of the attention, sampled on the calling thread's tasks
343            double t0 = pa ? pclock() : 0.0;
344            const float* Q = qkv.data() + (size_t) q0 * D3 + (size_t) hh * HD;
345            const float* KTh = KT.data() + (size_t) hh * HD * Np;
346            const float* Vh = vpack ? VP.data() + (size_t) hh * N * HD : qkv.data() + 2 * (size_t) D + (size_t) hh * HD;
347            const size_t ldv = vpack ? (size_t) HD : D3;
348            for (int j0 = 0; j0 < N; j0 += kTK) {
349                const int tk = std::min(kTK, N - j0);
350                ops.gemm(Q, D3, qr, KTh + j0, (size_t) Np, HD, tk, S, (size_t) kTK, 0, nullptr);
351                if (pa) { const double t = pclock(); ta += t - t0; t0 = t; }
352                ops.softmax_update(S, (size_t) kTK, qr, tk, mx, ls, O, (size_t) OD, HD);
353                if (pa) { const double t = pclock(); tb += t - t0; t0 = t; }
354                ops.gemm(S, (size_t) kTK, qr, Vh + (size_t) j0 * ldv, ldv, tk, HD, O, (size_t) OD, 1, nullptr);
355                if (pa) { const double t = pclock(); tc += t - t0; t0 = t; }
356            }
357            if (pa) { pt[8] += ta; pt[9] += tb; pt[10] += tc; pt[11] += 1.0; }
358            for (int r = 0; r < qr; ++r) {
359                const float inv = 1.0f / ls[r];
360                float* dst = ctx.data() + (size_t) (q0 + r) * D + (size_t) hh * HD;
361                for (int d = 0; d < HD; ++d) dst[d] = O[(size_t) r * OD + d] * inv;
362            }
363        });
364        stage(3);
365        m.round_inplace(ctx.data(), ctx.size(), m.act_round);
366        for (int r0 = 0; r0 < N; r0 += R) {      // x += o(ctx)
367            const int rn = std::min(R, N - r0);
368            m.linear(L.o, ctx.data() + (size_t) r0 * D, (size_t) D, rn, x.data() + (size_t) r0 * D, (size_t) D, 2, L.o_b.data(), false, scratch);
369        }
370        stage(4);
371        for (int r0 = 0; r0 < N; r0 += R) {      // x += down(gelu(up(LN2 x)))
372            const int rn = std::min(R, N - r0);
373            m.rows_par(rn, [&](int i) { ops.layernorm(x.data() + (size_t) (r0 + i) * D, hbuf.data() + (size_t) i * D, D, L.ln2_w.data(), L.ln2_b.data(), g.eps); });
374            m.round_inplace(hbuf.data(), (size_t) rn * D, m.act_round);
375            m.linear(L.up, hbuf.data(), (size_t) D, rn, up.data(), (size_t) F, 0, L.up_b.data(), true, scratch);
376            m.round_inplace(up.data(), (size_t) rn * F, m.act_round);
377            stage(5);
378            m.linear(L.down, up.data(), (size_t) F, rn, x.data() + (size_t) r0 * D, (size_t) D, 2, L.down_b.data(), false, scratch);
379            stage(6);
380        }
381    }
382
383    // ---- post norm and the merger (4 consecutive tokens = one 4D row) ----
384    std::vector<float>& h = ctx;       // the context is no longer needed: the post-norm output takes its place
385    m.rows_par(N, [&](int t) { ops.layernorm(x.data() + (size_t) t * D, h.data() + (size_t) t * D, D, m.post_w.data(), m.post_b.data(), g.eps); });
386    m.round_inplace(h.data(), h.size(), m.act_round);
387    const int M = N / 4, Kin = 4 * D, Hid = g.merger_hidden, O = g.out_dim;
388    rows.assign((size_t) M * O, 0.0f);
389    const int RM = std::max(1, R / 4);
390    std::vector<float> m1((size_t) std::min(M, RM) * Hid);
391    for (int r0 = 0; r0 < M; r0 += RM) {
392        const int rn = std::min(RM, M - r0);
393        m.linear(m.mm0, h.data() + (size_t) r0 * Kin, (size_t) Kin, rn, m1.data(), (size_t) Hid, 0, m.mm0_b.data(), true, scratch);
394        m.round_inplace(m1.data(), (size_t) rn * Hid, m.act_round);
395        m.linear(m.mm2, m1.data(), (size_t) Hid, rn, rows.data() + (size_t) r0 * O, (size_t) O, 0, m.mm2_b.data(), false, scratch);
396    }
397    stage(7);
398    if (prof)
399        std::fprintf(stderr, "vit-cpu-prof N=%d threads=%d isa=%s: patch+pos %.1f, ln+qkv %.1f, rope+KT %.1f, attention %.1f (thread 0, %d tasks: QK %.1f, softmax %.1f, PV %.1f), "
400                             "o-proj %.1f, ln+up+gelu %.1f, down %.1f, post+merger %.1f ms\n",
401                     N, nth, ops.name, pt[0], pt[1], pt[2], pt[3], (int) pt[11], pt[8], pt[9], pt[10], pt[4], pt[5], pt[6], pt[7]);
402    return true;
403}
404
405}  // namespace strata_vit