okami.mom/strata

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

Niko1221Merge f-022-needsfmt: needs-format issue fixes (#3418, #3417, #3358 tests/build)5a9b4f4fc

main
29.2 KiB565 linesraw
1// src/kernels/cpu/tq_cpu_parity.cpp - the CPU trellis kernels (tq_cpu.hpp: TQ2_T / TQK6 / TQK7) against their scalar
2// reference, against ggml-cpu's own vec_dot and to_float, and their speed.  CPU only (no GPU runtime needed).
3//
4//   tq_cpu_parity                                  every check below for tqk6/tqk7 and tq2_t/tq2_t, plain and Hadamard
5//   tq_cpu_parity --synthetic GU/DOWN              one expert pair (types by ggml name, e.g. tqk6/tqk7)
6//   tq_cpu_parity --synthetic-hadamard GU/DOWN     the same with the block-128 Hadamard rotation of the activations
7//   tq_cpu_parity --bench [--quick] [--only K]     the micro-benchmark (run it pinned: taskset -c <cores>);
8//                                                  --only: the kernels whose name contains K
9//
10// Checks, per matrix (random stream bytes and scales, so every state is reached, and ggml-quantized Gaussian rows):
11//   (1) AVX2 and AVX-512 kernels == the scalar kernel, bit for bit, for groups of 1..8 tokens
12//   (2) a token's row in a group of k == the same token alone, bit for bit (no group-size dependence)
13//   (3) vs ggml-cpu's vec_dot on the same Q8_0 activations: the same integers summed in another float order, so
14//       ~1e-7 relative
15//   (4) vs ggml's to_float weights . the dequantized Q8_0 activations in double: the int16 state table's rounding
16//       (exact for |codebook| >= 2^-3, within 2^-14 below) plus float rounding, ~1e-6 relative
17// and per expert (native_gu_rows -> native_quant_h -> native_down_rows, the engine's entry points, which now take
18// these kernels) against the same expert computed with ggml-cpu's vec_dot: float rounding plus the odd Q8_0
19// rounding flip of the intermediate.
20#include "strata/kernels/cpu/tq_cpu.hpp"
21#include "strata/kernels/cpu/native_expert.hpp"
22#include "strata/kernels/cpu/expert.hpp"
23#include "strata/kernels/cpu/expert_layout.hpp"
24#include "strata/kernels/cpu/hadamard.hpp"
25
26#include "ggml.h"
27#include "ggml-cpu.h"
28
29#include <algorithm>
30#include <atomic>
31#include <chrono>
32#include <cmath>
33#include <cstdio>
34#include <cstdlib>
35#include <cstring>
36#include <functional>
37#include <random>
38#include <string>
39#include <thread>
40#include <vector>
41
42using namespace strata::kernels::cpu;
43
44namespace {
45
46constexpr int H = 2560, FF = 640;
47
48int type_by_name(const std::string& s) {
49    for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
50        const char* n = ggml_type_name((ggml_type) t);
51        if (n != nullptr && s == n) return t;
52    }
53    return -1;
54}
55
56uint16_t f2h(float f) { return ggml_fp32_to_fp16(f); }
57
58// rows x n weights of `type`: random stream bytes and scales (every state reachable, both scale signs), and the
59// last rows (up to 32, ggml's trellis encoder is slow) ggml's own encoding of Gaussian rows
60std::vector<uint8_t> make_matrix(int type, int rows, int n, uint32_t seed) {
61    const size_t rb = ggml_row_size((ggml_type) type, n);
62    std::vector<uint8_t> m(rb * rows);
63    std::mt19937 rng(seed);
64    std::uniform_int_distribution<int> byte(0, 255);
65    std::uniform_real_distribution<float> scale(0.002f, 0.05f);
66    const size_t bsz = rb / (size_t) (n / 128);
67    const int half = rows - std::min(rows / 2, 32);
68    for (int r = 0; r < half; ++r)
69        for (int b = 0; b < n / 128; ++b) {
70            uint8_t* blk = m.data() + (size_t) r * rb + (size_t) b * bsz;
71            const uint16_t d = f2h((byte(rng) & 1 ? -1.f : 1.f) * scale(rng));
72            std::memcpy(blk, &d, 2);
73            for (size_t j = 2; j < bsz; ++j) blk[j] = (uint8_t) byte(rng);
74        }
75    std::normal_distribution<float> nd(0.f, 0.02f);
76    std::vector<float> wf((size_t) (rows - half) * n);
77    for (auto& v : wf) v = nd(rng);
78    ggml_quantize_chunk((ggml_type) type, wf.data(), m.data() + (size_t) half * rb, 0, rows - half, n, nullptr);
79    return m;
80}
81
82std::vector<float> make_x(int n, uint32_t seed) {
83    std::mt19937 rng(seed);
84    std::normal_distribution<float> nd(0.f, 1.f);
85    std::vector<float> x(n);
86    for (auto& v : x) v = nd(rng);
87    x[(size_t) (seed % (uint32_t) n)] = 40.f;   // a massive channel, as the residual stream has
88    return x;
89}
90
91std::vector<uint8_t> q8_0(const std::vector<float>& x) {
92    std::vector<uint8_t> q(ggml_row_size(GGML_TYPE_Q8_0, (int64_t) x.size()));
93    ggml_get_type_traits_cpu(GGML_TYPE_Q8_0)->from_float(x.data(), q.data(), (int64_t) x.size());
94    return q;
95}
96
97bool same_bits(const float* a, const float* b, size_t n) { return std::memcmp(a, b, n * sizeof(float)) == 0; }
98
99// one matrix: checks (1) - (4); returns failures
100int check_matrix(int type, int rows, int n, uint32_t seed, bool hadamard) {
101    int fails = 0;
102    const size_t rb = ggml_row_size((ggml_type) type, n);
103    const auto m = make_matrix(type, rows, n, seed);
104    constexpr int NT = kTqMaxTokens;
105    std::vector<std::vector<uint8_t>> act(NT);
106    std::vector<std::vector<float>> xr(NT);
107    std::vector<float> signs(n);
108    for (int i = 0; i < n; ++i) signs[i] = ((i * 2654435761u) >> 7) & 1 ? -1.f : 1.f;
109    const void* ap[NT];
110    for (int t = 0; t < NT; ++t) {
111        xr[t] = make_x(n, seed * 31 + t);
112        if (hadamard) hadamard_rotate(xr[t].data(), n, 128, signs.data());
113        act[t] = q8_0(xr[t]);
114        ap[t] = act[t].data();
115    }
116    auto run = [&](TqIsa isa, int nt, const void* const* a, std::vector<float>& o) {
117        o.assign((size_t) nt * rows, 0.f);
118        float* op[NT];
119        for (int t = 0; t < nt; ++t) op[t] = o.data() + (size_t) t * rows;
120        // two row ranges, as the pool splits them
121        tq_rows(isa, type, m.data(), rb, n, a, nt, op, 0, rows / 3);
122        tq_rows(isa, type, m.data(), rb, n, a, nt, op, rows / 3, rows);
123    };
124    std::vector<float> ref, got;
125    run(TqIsa::scalar, NT, ap, ref);
126    // (1) every ISA this CPU has, every group size, == scalar bit for bit; (2) group-size independence
127    for (TqIsa isa : {TqIsa::scalar, TqIsa::avx2, TqIsa::avx512}) {
128        if (!tq_isa_ok(isa)) { std::printf("    %-6s not on this CPU: skipped\n", tq_isa_name(isa)); continue; }
129        bool ok = true;
130        for (int nt = 1; nt <= NT; ++nt)
131            for (int t0 = 0; t0 + nt <= NT; t0 += nt) {
132                run(isa, nt, ap + t0, got);
133                ok = ok && same_bits(got.data(), ref.data() + (size_t) t0 * rows, (size_t) nt * rows);
134            }
135        std::printf("    %-6s groups of 1..%d tokens vs the scalar kernel's 8-token run: %s\n", tq_isa_name(isa), NT,
136                    ok ? "bitwise equal" : "DIFFERENT");
137        fails += !ok;
138    }
139    // (3) ggml-cpu's vec_dot, (4) to_float in double
140    const auto* tc = ggml_get_type_traits_cpu((ggml_type) type);
141    const auto* tt = ggml_get_type_traits((ggml_type) type);
142    const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);
143    double num3 = 0, num4 = 0, den = 0, max3 = 0;
144    std::vector<float> wf(n), af(n);
145    for (int t = 0; t < 2; ++t) {
146        q8t->to_float(act[t].data(), af.data(), n);
147        for (int r = 0; r < rows; ++r) {
148            float g = 0;
149            tc->vec_dot(n, &g, 0, m.data() + (size_t) r * rb, 0, act[t].data(), 0, 1);
150            tt->to_float(m.data() + (size_t) r * rb, wf.data(), n);
151            double d = 0, mag = 0;
152            for (int i = 0; i < n; ++i) { d += (double) wf[i] * af[i]; mag += std::fabs((double) wf[i] * af[i]); }
153            const double ours = ref[(size_t) t * rows + r];
154            num3 += (ours - g) * (ours - g);
155            num4 += (ours - d) * (ours - d);
156            den += d * d;
157            max3 = std::max(max3, std::fabs(ours - g) / (mag + 1e-30));
158        }
159    }
160    const double r3 = std::sqrt(num3 / den), r4 = std::sqrt(num4 / den);
161    const bool ok3 = r3 < 1e-5 && max3 < 1e-5, ok4 = r4 < 1e-4;
162    std::printf("    vs ggml-cpu vec_dot: rel %.2e (worst row %.2e of sum|w a|) %s | vs to_float in double: rel %.2e %s\n",
163                r3, max3, ok3 ? "ok" : "FAILED", r4, ok4 ? "ok" : "FAILED");
164    return fails + !ok3 + !ok4;
165}
166
167// a whole expert through the engine's entry points vs the same expert on ggml-cpu's vec_dot
168int check_expert(int gu, int dn, bool hadamard) {
169    NativeFmt f;
170    std::string err;
171    if (!native_fmt(gu, dn, H, FF, f, err)) { std::printf("native_fmt: %s\n", err.c_str()); return 1; }
172    std::vector<float> sh(H), sf(FF);
173    for (int i = 0; i < H; ++i) sh[i] = (i * 7 % 3) ? 1.f : -1.f;
174    for (int i = 0; i < FF; ++i) sf[i] = (i * 5 % 3) ? -1.f : 1.f;
175    if (hadamard) {
176        f.had_block = 128;
177        f.had_gu = f.had_d = true;
178        f.gu_signs = sh.data();
179        f.d_signs = sf.data();
180    }
181    std::vector<uint8_t> blob(f.bytes);
182    const auto g = make_matrix(gu, FF, H, 101), u = make_matrix(gu, FF, H, 202), d = make_matrix(dn, H, FF, 303);
183    std::memcpy(blob.data(), g.data(), g.size());
184    std::memcpy(blob.data() + f.up_off, u.data(), u.size());
185    std::memcpy(blob.data() + f.down_off, d.data(), d.size());
186    constexpr int NT = 3;
187    double worst = 0;
188    bool bitwise_group = true;
189    std::vector<std::vector<float>> outs(NT, std::vector<float>(H));
190    std::vector<std::vector<uint8_t>> acts(NT, std::vector<uint8_t>(kNativeActBytes));
191    std::vector<std::vector<float>> ffs(NT, std::vector<float>(FF));
192    std::vector<std::vector<uint8_t>> hqs(NT, std::vector<uint8_t>(kNativeHBytes));
193    const void* a[NT];
194    float* ffp[NT];
195    const void* hp[NT];
196    float* op[NT];
197    for (int t = 0; t < NT; ++t) {
198        const auto x = make_x(H, 7 + t);
199        native_quant_act(f, x.data(), acts[t].data());
200        a[t] = acts[t].data();
201        ffp[t] = ffs[t].data();
202        hp[t] = hqs[t].data();
203        op[t] = outs[t].data();
204    }
205    native_gu_rows(f, blob.data(), a, NT, ffp, 0, FF);
206    for (int t = 0; t < NT; ++t) native_quant_h(f, ffs[t].data(), hqs[t].data());
207    native_down_rows(f, blob.data(), hp, NT, op, 0, H);
208    const auto* tg = ggml_get_type_traits_cpu((ggml_type) gu);
209    const auto* td = ggml_get_type_traits_cpu((ggml_type) dn);
210    for (int t = 0; t < NT; ++t) {
211        std::vector<float> ff(FF), out(H);
212        for (int r = 0; r < FF; ++r) {
213            float gg = 0, uu = 0;
214            tg->vec_dot(H, &gg, 0, blob.data() + (size_t) r * f.gu_row, 0, a[t], 0, 1);
215            tg->vec_dot(H, &uu, 0, blob.data() + f.up_off + (size_t) r * f.gu_row, 0, a[t], 0, 1);
216            ff[r] = (gg / (1.f + std::exp(-gg))) * uu;
217        }
218        std::vector<uint8_t> hq(kNativeHBytes);
219        native_quant_h(f, ff.data(), hq.data());
220        for (int r = 0; r < H; ++r)
221            td->vec_dot(FF, &out[r], 0, blob.data() + f.down_off + (size_t) r * f.d_row, 0, hq.data(), 0, 1);
222        double num = 0, den = 0;
223        for (int r = 0; r < H; ++r) { num += std::pow((double) outs[t][r] - out[r], 2); den += (double) out[r] * out[r]; }
224        worst = std::max(worst, std::sqrt(num / den));
225        // the same token alone through the engine path: the same bits as in the group of three
226        std::vector<float> ff1(FF), o1(H);
227        float* f1[1] = {ff1.data()};
228        float* o1p[1] = {o1.data()};
229        const void* a1[1] = {a[t]};
230        native_gu_rows(f, blob.data(), a1, 1, f1, 0, FF);
231        std::vector<uint8_t> h1(kNativeHBytes);
232        native_quant_h(f, ff1.data(), h1.data());
233        const void* h1p[1] = {h1.data()};
234        native_down_rows(f, blob.data(), h1p, 1, o1p, 0, H);
235        bitwise_group = bitwise_group && same_bits(o1.data(), outs[t].data(), H);
236    }
237    const bool ok = worst < 2e-3 && bitwise_group;
238    std::printf("  expert %s/%s%s through native_gu_rows/native_down_rows (%s, %s): vs ggml-cpu vec_dot rel %.2e, "
239                "alone vs in a group of %d: %s  %s\n",
240                ggml_type_name((ggml_type) gu), ggml_type_name((ggml_type) dn), hadamard ? " +hadamard" : "",
241                tq_kernels_enabled() ? "tq kernels" : "ggml-cpu", tq_isa_name(tq_isa()), worst, NT,
242                bitwise_group ? "bitwise equal" : "DIFFERENT", ok ? "ok" : "FAILED");
243    return ok ? 0 : 1;
244}
245
246int synthetic(int gu, int dn, bool hadamard) {
247    int fails = 0;
248    std::printf("%s/%s%s (tq kernels: %s, best ISA here %s)\n", ggml_type_name((ggml_type) gu),
249                ggml_type_name((ggml_type) dn), hadamard ? " +hadamard" : "", tq_kernels_enabled() ? "on" : "off",
250                tq_isa_name(tq_isa()));
251    std::printf("  %s, 96 rows of %d (gate/up shape)\n", ggml_type_name((ggml_type) gu), H);
252    fails += check_matrix(gu, 96, H, 1000 + gu, hadamard);
253    std::printf("  %s, 256 rows of %d (down shape)\n", ggml_type_name((ggml_type) dn), FF);
254    fails += check_matrix(dn, 256, FF, 2000 + dn, hadamard);
255    fails += check_expert(gu, dn, hadamard);
256    return fails;
257}
258
259// ------------------------------------------------------------------------------------------------ the benchmark
260
261double now_us() {
262    return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count();
263}
264
265struct BenchExpert {
266    std::vector<uint8_t> gu, dn;   // gate rows then up rows; down rows
267    size_t gu_row, d_row;
268};
269
270// one variant: compute one expert (gate+up rows, then down rows) for `nt` tokens
271using ExpertFn = std::function<void(const BenchExpert&, int nt)>;
272
273// the core clock right now: a chain of dependent adds runs at one per cycle (GCC / Clang on x86-64; 0 elsewhere)
274double core_ghz() {
275#if defined(__GNUC__) && defined(__x86_64__)
276    uint64_t x = 0;
277    const long n = 1000000;
278    const double t0 = now_us();
279    for (long i = 0; i < n; ++i) __asm__ volatile("add $1, %0\n\tadd $1, %0\n\tadd $1, %0\n\tadd $1, %0" : "+r"(x));
280    return 4.0 * n / ((now_us() - t0) * 1e3);
281#else
282    return 0.0;
283#endif
284}
285
286constexpr double kBlocksPerExpert = 2.0 * FF * (H / 128) + (double) H * (FF / 128);   // 128-weight blocks
287
288// one slice of `ms` milliseconds cycling over the experts: ns per expert call and the clock around it (negated when
289// the clock moved by more than 5% during the slice: such samples count only when a variant has no other)
290std::pair<double, double> time_slice(const std::vector<BenchExpert>& ex, const ExpertFn& fn, int nt, double ms,
291                                     size_t& next) {
292    const double g0 = core_ghz();
293    int it = 0;
294    const double t0 = now_us();
295    double t1 = t0;
296    do {
297        fn(ex[next++ % ex.size()], nt);
298        ++it;
299        t1 = now_us();
300    } while (t1 - t0 < ms * 1000.0 || it < 2);
301    const double g1 = core_ghz();
302    const double ghz = 0.5 * (g0 + g1);
303    return {(t1 - t0) * 1e3 / it, ghz > 0 && std::fabs(g1 - g0) > 0.05 * g0 ? -ghz : ghz};
304}
305
306double median(std::vector<double> v) {
307    if (v.empty()) return 0.0;
308    std::sort(v.begin(), v.end());
309    return v[v.size() / 2];
310}
311
312// `threads` threads, each cycling over its own experts: aggregate weight GB/s
313double time_parallel(const std::vector<BenchExpert>& ex, const ExpertFn& fn, int threads, double ms) {
314    std::atomic<long> done{0};
315    std::atomic<bool> stop{false};
316    std::vector<std::thread> th;
317    const double t0 = now_us();
318    for (int k = 0; k < threads; ++k)
319        th.emplace_back([&, k] {
320            long c = 0;
321            for (size_t i = (size_t) k; !stop.load(std::memory_order_relaxed); i += (size_t) threads, ++c)
322                fn(ex[i % ex.size()], 1);
323            done += c;
324        });
325    std::this_thread::sleep_for(std::chrono::milliseconds((int) ms));
326    stop = true;
327    for (auto& t : th) t.join();
328    const double us = now_us() - t0;
329    const double bytes = (double) (ex[0].gu_row * 2 * FF + ex[0].dn.size()) * (double) done.load();
330    return bytes / (us * 1e3);
331}
332
333int bench(bool quick, const std::string& only) {
334    const int ncold = quick ? 48 : 96;   // ~50-130 MB of weights: past the last-level cache
335    std::printf("CPU: %s | AVX-512 kernels: %s, AVX2: %s | ggml-cpu built for this CPU (-march=native unless "
336                "STRATA_PORTABLE)\n", cpu_name().c_str(), cpu_avx512_ok() ? "yes" : "no", cpu_avx2_ok() ? "yes" : "no");
337    std::printf("expert = gate+up %d x %d and down %d x %d of one type, %d distinct experts cycled (their weights come "
338                "from DRAM, as a cache miss's do)\n\n", FF, H, H, FF, ncold);
339    struct Variant { std::string name; int type; ExpertFn fn; bool ok; };
340    std::vector<Variant> vars;
341    auto add_tq = [&](int type) {
342        for (TqIsa isa : {TqIsa::scalar, TqIsa::avx2, TqIsa::avx512}) {
343            vars.push_back({std::string("strata ") + tq_isa_name(isa), type,
344                            [type, isa](const BenchExpert& e, int nt) {
345                                thread_local std::vector<uint8_t> a, h;
346                                thread_local std::vector<float> ff, out;
347                                a.resize(ggml_row_size(GGML_TYPE_Q8_0, H) * kTqMaxTokens);
348                                h.resize(ggml_row_size(GGML_TYPE_Q8_0, FF) * kTqMaxTokens);
349                                ff.resize((size_t) FF * kTqMaxTokens);
350                                out.resize((size_t) H * kTqMaxTokens);
351                                const void* ap[kTqMaxTokens];
352                                const void* hp[kTqMaxTokens];
353                                float* fp[kTqMaxTokens];
354                                float* op[kTqMaxTokens];
355                                for (int t = 0; t < nt; ++t) {
356                                    ap[t] = a.data() + t * ggml_row_size(GGML_TYPE_Q8_0, H);
357                                    hp[t] = h.data() + t * ggml_row_size(GGML_TYPE_Q8_0, FF);
358                                    fp[t] = ff.data() + (size_t) t * FF;
359                                    op[t] = out.data() + (size_t) t * H;
360                                }
361                                tq_gu_rows(isa, type, e.gu.data(), e.gu_row, e.gu_row * FF, H, ap, nt, fp, 0, FF);
362                                tq_rows(isa, type, e.dn.data(), e.d_row, FF, hp, nt, op, 0, H);
363                            },
364                            tq_isa_ok(isa)});
365        }
366        vars.push_back({"ggml-cpu vec_dot", type,
367                        [type](const BenchExpert& e, int nt) {
368                            const auto* tc = ggml_get_type_traits_cpu((ggml_type) type);
369                            thread_local std::vector<uint8_t> a(ggml_row_size(GGML_TYPE_Q8_0, H)),
370                                h(ggml_row_size(GGML_TYPE_Q8_0, FF));
371                            thread_local std::vector<float> ff(FF), out(H);
372                            for (int t = 0; t < nt; ++t) {
373                                for (int r = 0; r < FF; ++r) {
374                                    float g, u;
375                                    tc->vec_dot(H, &g, 0, e.gu.data() + (size_t) r * e.gu_row, 0, a.data(), 0, 1);
376                                    tc->vec_dot(H, &u, 0, e.gu.data() + (size_t) (FF + r) * e.gu_row, 0, a.data(), 0, 1);
377                                    ff[r] = (g / (1.f + std::exp(-g))) * u;
378                                }
379                                for (int r = 0; r < H; ++r)
380                                    tc->vec_dot(FF, &out[r], 0, e.dn.data() + (size_t) r * e.d_row, 0, h.data(), 0, 1);
381                            }
382                        },
383                        true});
384    };
385    auto add_q2 = [&](bool avx512) {
386        vars.push_back({avx512 ? "strata Q2_0 avx512" : "strata Q2_0 avx2", 42,
387                        [avx512](const BenchExpert& e, int nt) {
388                            thread_local ActQ a1[MAXT], a2[MAXT];
389                            thread_local bool init = false;
390                            if (!init) {   // real scales and codes (the kernel reads every field)
391                                const auto x = make_x(H, 3), h = make_x(FF, 4);
392                                for (int t = 0; t < MAXT; ++t) { act_quant_q8_1_avx2(x.data(), H, a1[t]); act_quant_q8_1_avx2(h.data(), FF, a2[t]); }
393                                init = true;
394                            }
395                            thread_local float g[MAXT][FF], u[MAXT][FF], out[MAXT][H];
396                            const ActQ* ap[MAXT];
397                            const ActQ* hp[MAXT];
398                            float* gp[MAXT];
399                            float* up[MAXT];
400                            float* op[MAXT];
401                            for (int t = 0; t < nt; ++t) { ap[t] = &a1[t]; hp[t] = &a2[t]; gp[t] = g[t]; up[t] = u[t]; op[t] = out[t]; }
402                            auto rows = avx512 ? q2_0_gguf_rows_multi : q2_0_gguf_rows_multi_avx2;
403                            rows(e.gu.data(), e.gu_row, H / 64, ap, nt, gp, 0, FF);
404                            rows(e.gu.data() + e.gu_row * FF, e.gu_row, H / 64, ap, nt, up, 0, FF);
405                            for (int t = 0; t < nt; ++t)
406                                for (int r = 0; r < FF; ++r) g[t][r] = (g[t][r] / (1.f + std::exp(-g[t][r]))) * u[t][r];
407                            rows(e.dn.data(), e.d_row, FF / 64, hp, nt, op, 0, H);
408                        },
409                        avx512 ? cpu_avx512_ok() : cpu_avx2_ok()});
410    };
411    for (int type : {145, 146, 144}) add_tq(type);
412    add_q2(false);
413    add_q2(true);
414    // the Q2_0 pack's own AVX-512 kernel (the repacked 1,382,400-byte blob that setup makes on AVX-512 CPUs)
415    vars.push_back({"strata Q2_0 avx512 pack", 42,
416                    [](const BenchExpert& e, int nt) {
417                        thread_local ActQ a1, a2;
418                        thread_local bool init = false;
419                        if (!init) {
420                            const auto x = make_x(H, 3), h = make_x(FF, 4);
421                            act_quant_q8_1(x.data(), H, a1);
422                            act_quant_q8_1(h.data(), FF, a2);
423                            init = true;
424                        }
425                        thread_local float ff[FF], out[H];
426                        for (int t = 0; t < nt; ++t) {   // its multi-token kernels are the same per token
427                            s2_expert_gu_rows(e.gu.data(), a1, ff, 0, FF);
428                            s2_expert_down_rows(e.gu.data(), a2, out, 0, H);
429                        }
430                    },
431                    cpu_avx512_ok()});
432
433    auto make_experts = [&](int type, int count) {
434        std::vector<BenchExpert> v((size_t) count);
435        for (int k = 0; k < count; ++k) {
436            BenchExpert& e = v[(size_t) k];
437            e.gu_row = ggml_row_size((ggml_type) type, H);
438            e.d_row = ggml_row_size((ggml_type) type, FF);
439            // (Q2_0: room for one repacked blob too, which the pack kernel reads from the same buffer)
440            e.gu.resize(type == 42 ? std::max(e.gu_row * 2 * FF, (size_t) BLOB) : e.gu_row * 2 * FF);
441            e.dn.resize(e.d_row * H);
442            std::mt19937 rng(77 + k);
443            for (auto& b : e.gu) b = (uint8_t) rng();
444            for (auto& b : e.dn) b = (uint8_t) rng();
445            // sane fp16 scales at every block start (Q2_0: 18-byte blocks, TQ: 26/30/34)
446            const size_t bsz = type == 42 ? 18 : ggml_row_size((ggml_type) type, 128);
447            const uint16_t d = f2h(0.01f);
448            for (size_t o = 0; o + bsz <= e.gu.size(); o += bsz) std::memcpy(e.gu.data() + o, &d, 2);
449            for (size_t o = 0; o + bsz <= e.dn.size(); o += bsz) std::memcpy(e.dn.data() + o, &d, 2);
450            if (type == 42) {   // the same bytes also hold one repacked Q2_0 blob (codes, then fp16 scales)
451                for (size_t o = O_GU_SCALES; o + 2 <= BLOB; o += 2) std::memcpy(e.gu.data() + o, &d, 2);
452            }
453        }
454        return v;
455    };
456    // Single thread, the variants of a type interleaved in short slices over several rounds (this machine's clock
457    // moves; a slice whose clock moved is dropped), medians reported: ns and core cycles per 128-weight block, us
458    // per expert, weight GB/s; and per token in a group of three (a verify window's tokens routed to one expert).
459    // The activations are zero-filled (the kernels do not branch on values) except Q2_0's, which are real.
460    const int rounds = quick ? 5 : 15;
461    const double slice_ms = quick ? 40 : 60;
462    std::printf("%-6s %-24s %9s %8s %8s %8s | %10s %8s\n", "type", "kernel", "us/expert", "ns/blk", "cyc/blk", "GB/s",
463                "x3: us/tok", "cyc/blk");
464    for (int type : {145, 146, 144, 42}) {
465        const auto cold = make_experts(type, ncold);
466        const double eb = (double) (cold[0].gu_row * 2 * FF + cold[0].dn.size());   // weight bytes per expert
467        std::vector<const Variant*> vs;
468        for (const auto& v : vars)
469            if (v.type == type && v.name.find(only) != std::string::npos) {
470                if (v.ok) vs.push_back(&v);
471                else std::printf("%-6s %-24s (not on this CPU)\n", ggml_type_name((ggml_type) type), v.name.c_str());
472            }
473        std::vector<std::vector<double>> ns1(vs.size()), cy1(vs.size()), ns3(vs.size()), cy3(vs.size());
474        std::vector<std::vector<double>> ns1m(vs.size()), cy1m(vs.size()), ns3m(vs.size()), cy3m(vs.size());
475        size_t next = 0;
476        for (auto* v : vs) v->fn(cold[0], 3);   // warm-up: tables, buffers
477        for (int r = 0; r < rounds; ++r)
478            for (size_t k = 0; k < vs.size(); ++k) {
479                const bool slow = vs[k]->name.find("scalar") != std::string::npos;
480                const auto a = time_slice(cold, vs[k]->fn, 1, slow ? slice_ms / 2 : slice_ms, next);
481                const auto b = time_slice(cold, vs[k]->fn, 3, slow ? slice_ms / 2 : slice_ms, next);
482                if (a.second >= 0) { ns1[k].push_back(a.first); cy1[k].push_back(a.first * a.second); }
483                else { ns1m[k].push_back(a.first); cy1m[k].push_back(-a.first * a.second); }
484                if (b.second >= 0) { ns3[k].push_back(b.first); cy3[k].push_back(b.first * b.second); }
485                else { ns3m[k].push_back(b.first); cy3m[k].push_back(-b.first * b.second); }
486            }
487        std::vector<size_t> steady(vs.size());
488        for (size_t k = 0; k < vs.size(); ++k) {
489            steady[k] = ns1[k].size();
490            if (ns1[k].empty()) { ns1[k] = ns1m[k]; cy1[k] = cy1m[k]; }
491            if (ns3[k].empty()) { ns3[k] = ns3m[k]; cy3[k] = cy3m[k]; }
492        }
493        for (size_t k = 0; k < vs.size(); ++k) {
494            const double n1 = median(ns1[k]), c1 = median(cy1[k]), n3 = median(ns3[k]), c3 = median(cy3[k]);
495            std::printf("%-6s %-24s %9.1f %8.1f %8.1f %8.2f | %10.1f %8.1f   (%zu/%d steady)\n",
496                        ggml_type_name((ggml_type) type), vs[k]->name.c_str(), n1 / 1e3, n1 / kBlocksPerExpert,
497                        c1 / kBlocksPerExpert, eb / n1, n3 / 3e3, c3 / kBlocksPerExpert, steady[k], rounds);
498        }
499        std::fflush(stdout);
500    }
501    // several workers at once (as the pool runs a layer's misses): aggregate GB/s on the cold set
502    const int nthr = (int) std::max(1u, std::min(4u, std::thread::hardware_concurrency()));
503    std::printf("\n%d threads at once, cold experts, one token: aggregate weight GB/s (us per expert per thread)\n", nthr);
504    for (int type : {145, 146, 144, 42}) {
505        const auto cold = make_experts(type, ncold);
506        const double eb = (double) (cold[0].gu_row * 2 * FF + cold[0].dn.size());
507        std::vector<const Variant*> vs;
508        for (const auto& v : vars)
509            if (v.type == type && v.ok && v.name.find("scalar") == std::string::npos && v.name.find(only) != std::string::npos)
510                vs.push_back(&v);
511        std::vector<std::vector<double>> g(vs.size());
512        for (int r = 0; r < (quick ? 2 : 4); ++r)
513            for (size_t k = 0; k < vs.size(); ++k) g[k].push_back(time_parallel(cold, vs[k]->fn, nthr, quick ? 150 : 250));
514        for (size_t k = 0; k < vs.size(); ++k) {
515            const double gbs = median(g[k]);
516            std::printf("%-6s %-24s %8.2f GB/s (%7.1f us per expert per thread)\n", ggml_type_name((ggml_type) type),
517                        vs[k]->name.c_str(), gbs, eb / (gbs * 1e3) * nthr);
518        }
519        std::fflush(stdout);
520    }
521    // the per-token Hadamard rotation of one layer's activation (once per token per layer, shared by its experts)
522    {
523        std::vector<float> x = make_x(H, 5), s(H, 1.f);
524        const int it = 20000;
525        const double t0 = now_us();
526        for (int i = 0; i < it; ++i) hadamard_rotate(x.data(), H, 128, s.data());
527        std::printf("\nHadamard rotation of one %d-wide activation (block 128): %.2f us\n", H, (now_us() - t0) / it);
528    }
529    return 0;
530}
531
532}  // namespace
533
534int main(int argc, char** argv) {
535    ggml_cpu_init();
536    if (GGML_TYPE_COUNT <= 146) {
537        std::fprintf(stderr, "this ggml has no trellis types (build with STRATA_GGML_DIR = the agention llama.cpp fork): skipped\n");
538        return 77;   // ctest SKIP_RETURN_CODE: a plain ggml is not a failure (#3358)
539    }
540    if (argc >= 2 && std::strcmp(argv[1], "--bench") == 0) {   // --bench [--quick] [--only <kernel name part>]
541        bool quick = false;
542        std::string only;
543        for (int i = 2; i < argc; ++i) {
544            if (std::strcmp(argv[i], "--quick") == 0) quick = true;
545            else if (std::strcmp(argv[i], "--only") == 0 && i + 1 < argc) only = argv[++i];
546        }
547        return bench(quick, only);
548    }
549    if (argc >= 3 && (std::strcmp(argv[1], "--synthetic") == 0 || std::strcmp(argv[1], "--synthetic-hadamard") == 0)) {
550        const std::string pair = argv[2];
551        const size_t sl = pair.find('/');
552        const int gu = type_by_name(pair.substr(0, sl)), dn = sl == std::string::npos ? gu : type_by_name(pair.substr(sl + 1));
553        if (!tq_supported(gu) || !tq_supported(dn)) { std::fprintf(stderr, "not a trellis pair: %s\n", argv[2]); return 2; }
554        const int f = synthetic(gu, dn, std::strcmp(argv[1], "--synthetic-hadamard") == 0);
555        std::printf("%d failures\n", f);
556        return f ? 1 : 0;
557    }
558    int f = 0;
559    for (bool had : {false, true}) {
560        f += synthetic(145, 146, had);   // Gyro-S
561        f += synthetic(144, 144, had);   // Gyro-M
562    }
563    std::printf("%d failures\n", f);
564    return f ? 1 : 0;
565}