okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
27.4 KiB584 linesraw
1// src/kernels/cpu/iq_avx2_parity.cpp - the AVX-2 expert kernels' variants (iq_avx2.cpp, q2_avx2.cpp) bit for bit
2// against each other and against ggml-cpu, and their time per expert.  No GPU, no model: random blocks, so every grid
3// index and sign pattern occurs, and random activations quantized the way the engine quantizes them.
4//
5//     iq_avx2_parity [--cpu N]
6//         IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S and IQ4_XS gate/up rows, IQ4_NL and Q2_0 down rows: every variant
7//         this CPU runs, 1..8 tokens, each token's rows bit for bit the scalar variant's rows for that token alone (so
8//         also the same at every width, #152); the scalar rows against ggml-cpu's vec_dot (Q2_0: a double
9//         reference), rel <= 1e-5; and where the engine's dispatch (native_gu_rows) takes the multi-token kernel from
10//         one token on (native_gu_mt_min), each token's rows the same alone and in a group.
11//     iq_avx2_parity --bench [--cpu N] [--nt 1,2,3,4] [--mb 256] [--reps 5] [--pairs iq3_s/iq4_nl,...] [--dispatch]
12//         ms per expert on one thread: each variant, ggml-cpu's per-token dot, and the engine's dispatch
13//         (native_gu_rows, native_down_rows / q2_rows_any) over --mb MB of expert blobs - far more than an L3 holds, so
14//         the weights stream from DRAM as they do in decode.  --dispatch: only the kernels' own dispatch, ggml and the
15//         engine's (the env decides: STRATA_IQ256_GATHER, STRATA_NO_AVXVNNI, STRATA_IQ_MT_MIN), for A/B runs against
16//         another build.  --cpu pins the thread to that logical CPU.
17//
18// Built with -DSTRATA_IQ_PARITY_DISPATCH_ONLY=1 it calls only the kernels' public entry points, so the same program
19// builds on an engine from before the variants (--bench --dispatch against it).
20#include "strata/kernels/cpu/expert.hpp"
21#include "strata/kernels/cpu/expert_layout.hpp"
22#include "strata/kernels/cpu/iq_avx2.hpp"
23#include "strata/kernels/cpu/native_expert.hpp"
24
25#include "ggml.h"
26#include "ggml-cpu.h"
27
28#if defined(_WIN32)
29#ifndef NOMINMAX
30#define NOMINMAX
31#endif
32#ifndef WIN32_LEAN_AND_MEAN
33#define WIN32_LEAN_AND_MEAN
34#endif
35#include <windows.h>
36#include <intrin.h>
37#else
38#include <cpuid.h>
39#include <sched.h>
40#endif
41
42#include <algorithm>
43#include <chrono>
44#include <cmath>
45#include <cstdint>
46#include <cstdio>
47#include <cstdlib>
48#include <cstring>
49#include <functional>
50#include <memory>
51#include <random>
52#include <string>
53#include <vector>
54
55namespace cpu = strata::kernels::cpu;
56using Clock = std::chrono::steady_clock;
57
58namespace {
59
60constexpr int64_t kH = 2560, kFF = 640;   // the experts' geometry: n_embd, expert width
61constexpr int kMaxT = 8;
62
63// ---- the variants: the public dispatch only in a DISPATCH_ONLY build
64#if defined(STRATA_IQ_PARITY_DISPATCH_ONLY)
65constexpr bool kVariants = false;
66int gu_variants() { return 0; }
67int down_variants() { return 0; }
68void gu_rows_v(int, int type, const uint8_t* blob, size_t gu_row, size_t up_off, const void* const* act, int nt,
69               float* const* ff) {
70    cpu::iq256_gu_rows(type, blob, gu_row, up_off, (int) kH, act, nt, ff, 0, (int) kFF);
71}
72void gate_rows_v(int, int type, const uint8_t* w, size_t row_bytes, const void* const* act, int nt, float* const* out) {
73    cpu::iq256_rows(type, w, row_bytes, (int) kH, act, nt, out, 0, (int) kFF);
74}
75void iq4nl_rows_v(int, const uint8_t* w, size_t row_bytes, const void* const* hq, int nt, float* const* out) {
76    cpu::iq4nl256_down_rows(w, row_bytes, (int) kFF, hq, nt, out, 0, (int) kH);
77}
78void q2_rows_v(int, const uint8_t* w, size_t row_bytes, const cpu::ActQ* const* a, int nt, float* const* out) {
79    cpu::q2_0_gguf_rows_multi_avx2(w, row_bytes, (int) (kFF / 64), a, nt, out, 0, (int) kH);
80}
81std::string variant_name(int) { return "dispatch"; }
82#else
83constexpr bool kVariants = true;
84int gu_variants() { return cpu::iq256_variants(); }
85int down_variants() { return cpu::iq256_variants() & cpu::kIq256Vnni; }
86void gu_rows_v(int v, int type, const uint8_t* blob, size_t gu_row, size_t up_off, const void* const* act, int nt,
87               float* const* ff) {
88    cpu::iq256_gu_rows_v(v, type, blob, gu_row, up_off, (int) kH, act, nt, ff, 0, (int) kFF);
89}
90void gate_rows_v(int v, int type, const uint8_t* w, size_t row_bytes, const void* const* act, int nt, float* const* out) {
91    cpu::iq256_rows_v(v, type, w, row_bytes, (int) kH, act, nt, out, 0, (int) kFF);
92}
93void iq4nl_rows_v(int v, const uint8_t* w, size_t row_bytes, const void* const* hq, int nt, float* const* out) {
94    cpu::iq4nl256_down_rows_v(v, w, row_bytes, (int) kFF, hq, nt, out, 0, (int) kH);
95}
96void q2_rows_v(int v, const uint8_t* w, size_t row_bytes, const cpu::ActQ* const* a, int nt, float* const* out) {
97    cpu::q2_0_gguf_rows_multi_avx2_v((v & cpu::kIq256Vnni) != 0, w, row_bytes, (int) (kFF / 64), a, nt, out, 0, (int) kH);
98}
99std::string variant_name(int v) {
100    if (v == 0) return "scalar";
101    std::string s;
102    if (v & cpu::kIq256Gather) s += "gather";
103    if (v & cpu::kIq256Vnni) s += s.empty() ? "vnni" : "+vnni";
104    return s;
105}
106#endif
107
108// every subset of a variant mask, the empty one (scalar) first
109std::vector<int> subsets(int mask) {
110    std::vector<int> v;
111    for (int s = 0; s <= mask; ++s)
112        if ((s & ~mask) == 0) v.push_back(s);
113    return v;
114}
115
116uint64_t mix(uint64_t& s) {   // splitmix64
117    uint64_t z = (s += 0x9E3779B97F4A7C15ull);
118    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
119    z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
120    return z ^ (z >> 31);
121}
122
123const ggml_type_traits_cpu* traits_cpu(int type) { return ggml_get_type_traits_cpu((ggml_type) type); }
124
125// random bytes, then a sane fp16 scale at the front of every block (each format here starts its block with it)
126void fill_blocks(uint8_t* p, size_t bytes, int type, uint64_t& seed) {
127    for (size_t i = 0; i < bytes; i += 8) {
128        const uint64_t v = mix(seed);
129        std::memcpy(p + i, &v, std::min<size_t>(8, bytes - i));
130    }
131    const size_t bs = ggml_type_size((ggml_type) type);
132    for (size_t o = 0; o + bs <= bytes; o += bs) {
133        const float d = (0.5f + (float) (mix(seed) >> 40) * (1.f / 16777216.f)) * 1e-3f;
134        const ggml_fp16_t h = ggml_fp32_to_fp16(d);
135        std::memcpy(p + o, &h, 2);
136    }
137}
138
139void fill_blob(uint8_t* blob, const cpu::NativeFmt& f, uint64_t& seed) {
140    fill_blocks(blob, f.down_off, f.gu_type, seed);                     // the gate and up rows
141    fill_blocks(blob + f.down_off, f.bytes - f.down_off, f.d_type, seed);
142}
143
144// kMaxT tokens: the gate/up activation (ggml's vec_dot type, Q8_K for the i-quants), the down one in ggml's form and in
145// the Q2_0 kernels' form (ActQ), as the engine quantizes them
146struct Acts {
147    std::vector<std::vector<uint8_t>> gu, dn;
148    std::vector<cpu::ActQ> q2;
149    const void* gup[kMaxT];
150    const void* dnp[kMaxT];
151    const cpu::ActQ* q2p[kMaxT];
152    Acts(const cpu::NativeFmt& f, unsigned seed)
153        : gu(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes)), dn(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes)),
154          q2(kMaxT) {
155        std::mt19937 rng(seed);
156        std::normal_distribution<float> nd(0.f, 1.f);
157        std::vector<float> x((size_t) kH), h((size_t) kFF);
158        for (int t = 0; t < kMaxT; ++t) {
159            for (auto& v : x) v = nd(rng);
160            for (auto& v : h) v = 0.05f * nd(rng);
161            cpu::native_quant_act(f, x.data(), gu[(size_t) t].data());
162            cpu::native_quant_h(f, h.data(), dn[(size_t) t].data());
163            if (cpu::cpu_avx2_ok()) cpu::act_quant_any(h.data(), (int) kFF, q2[(size_t) t]);
164            gup[t] = gu[(size_t) t].data();
165            dnp[t] = dn[(size_t) t].data();
166            q2p[t] = &q2[(size_t) t];
167        }
168    }
169};
170
171double rel(const float* a, const float* b, size_t n) {
172    double num = 0, den = 0;
173    for (size_t i = 0; i < n; ++i) { num += std::fabs((double) a[i] - b[i]); den += std::fabs((double) b[i]); }
174    return num / (den + 1e-30);
175}
176
177size_t rows_differ(const float* a, const float* b, size_t n) {
178    size_t d = 0;
179    for (size_t i = 0; i < n; ++i) d += std::memcmp(a + i, b + i, 4) != 0;
180    return d;
181}
182
183unsigned core_type() {   // CPUID 1Ah of the calling thread: 40h performance core, 20h E-core, 0 not reported
184    unsigned r[4] = {0, 0, 0, 0};
185#if defined(_MSC_VER)
186    int x[4];
187    __cpuid(x, 0);
188    if ((unsigned) x[0] < 0x1A) return 0;
189    __cpuidex(x, 0x1A, 0);
190    r[0] = (unsigned) x[0];
191#else
192    unsigned a = 0, b = 0, c = 0, d = 0;
193    __cpuid(0, a, b, c, d);
194    if (a < 0x1A) return 0;
195    __cpuid_count(0x1A, 0, r[0], r[1], r[2], r[3]);
196#endif
197    return r[0] >> 24;
198}
199
200bool pin_to(int cpu_index) {
201#if defined(_WIN32)
202    if (cpu_index < 0 || cpu_index >= 64) return false;
203    return SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR) 1 << cpu_index) != 0;
204#else
205    cpu_set_t s;
206    CPU_ZERO(&s);
207    CPU_SET(cpu_index, &s);
208    return sched_setaffinity(0, sizeof s, &s) == 0;
209#endif
210}
211
212const char* type_name(int type) { return ggml_type_name((ggml_type) type); }
213
214int type_of(const std::string& name) {
215    for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
216        const char* n = ggml_type_name((ggml_type) t);
217        if (n != nullptr && name == n) return t;
218    }
219    return -1;
220}
221
222// ---- parity
223int check_gate_up(int type) {
224    cpu::NativeFmt f;
225    std::string err;
226    if (!cpu::native_fmt(type, 20, kH, kFF, f, err)) {
227        std::printf("  %-8s %s\n", type_name(type), err.c_str());
228        return 1;
229    }
230    std::vector<uint8_t> blob(f.bytes);
231    uint64_t seed = 0x5eed0000ull + (uint64_t) type;
232    fill_blob(blob.data(), f, seed);
233    const Acts a(f, 77u + (unsigned) type);
234    const size_t R = (size_t) kFF;
235    std::vector<float> ref(kMaxT * R);
236    for (int t = 0; t < kMaxT; ++t)
237        for (size_t r = 0; r < R; ++r)
238            traits_cpu(type)->vec_dot((int) kH, &ref[t * R + r], 0, blob.data() + r * f.gu_row, 0, a.gup[t], 0, 1);
239    // the first variant (scalar), each token alone: the rows every variant must give that token at every width
240    std::vector<float> one_g(kMaxT * R), one_ff(kMaxT * R);
241    for (int t = 0; t < kMaxT; ++t) {
242        float* og = &one_g[t * R];
243        float* of = &one_ff[t * R];
244        gate_rows_v(0, type, blob.data(), f.gu_row, &a.gup[t], 1, &og);
245        gu_rows_v(0, type, blob.data(), f.gu_row, f.up_off, &a.gup[t], 1, &of);
246    }
247    int failures = 0;
248    const double r_ggml = rel(one_g.data(), ref.data(), one_g.size());
249    std::printf("  %-8s gate rows vs ggml vec_dot: rel %.2e\n", type_name(type), r_ggml);
250    if (!(r_ggml <= 1e-5)) { std::printf("  %-8s MISMATCH against ggml\n", type_name(type)); ++failures; }
251    if (type == 16 || type == 17 || type == 18 || type == 21 || type == 22) {
252        size_t different = 0;
253        std::vector<float> exact(R);
254        const ggml_vec_dot_t dot = traits_cpu(type)->vec_dot;
255        for (int t = 0; t < kMaxT; ++t) {
256            cpu::iq256_gu_rows_exact_one(type, blob.data(), f.gu_row, f.up_off, (int) kH, a.gup[t],
257                                          exact.data(), 0, (int) kFF);
258            for (size_t r = 0; r < R; ++r) {
259                float g = 0.f, u = 0.f;
260                dot((int) kH, &g, 0, blob.data() + r * f.gu_row, 0, a.gup[t], 0, 1);
261                dot((int) kH, &u, 0, blob.data() + f.up_off + r * f.gu_row, 0, a.gup[t], 0, 1);
262                const float want = (g / (1.f + std::exp(-g))) * u;
263                different += std::memcmp(&exact[r], &want, sizeof(float)) != 0;
264            }
265        }
266        std::printf("  %-8s exact singleton vs ggml: %zu of %zu expert outputs differ bitwise\n",
267                    type_name(type), different, (size_t) kMaxT * R);
268#if defined(STRATA_TEST_GGML_WITHOUT_AVX2)
269        // an older-CPU build (STRATA_ISA_FLOOR): ggml-cpu has no AVX2/FMA there, so its dot is not the AVX2 one these
270        // rows follow; the tolerance check above still applies
271        std::printf("  %-8s exact singleton vs ggml: bit-equality not required (STRATA_ISA_FLOOR build: ggml-cpu "
272                    "without AVX2/FMA)\n", type_name(type));
273#else
274        if (different) ++failures;
275#endif
276    }
277    for (int v : subsets(gu_variants())) {
278        size_t differ = 0;
279        std::vector<float> g(kMaxT * R), ff(kMaxT * R);
280        for (int nt = 1; nt <= kMaxT; ++nt) {
281            float* gp[kMaxT];
282            float* fp[kMaxT];
283            for (int t = 0; t < nt; ++t) { gp[t] = &g[t * R]; fp[t] = &ff[t * R]; }
284            gate_rows_v(v, type, blob.data(), f.gu_row, a.gup, nt, gp);
285            gu_rows_v(v, type, blob.data(), f.gu_row, f.up_off, a.gup, nt, fp);
286            for (int t = 0; t < nt; ++t)
287                differ += rows_differ(gp[t], &one_g[t * R], R) + rows_differ(fp[t], &one_ff[t * R], R);
288        }
289        std::printf("  %-8s %-12s 1..8 tokens: %zu gate / gate+up rows differ from the %s one-token rows\n",
290                    type_name(type), variant_name(v).c_str(), differ, variant_name(0).c_str());
291        if (differ) ++failures;
292    }
293    return failures;
294}
295
296int check_down(int d_type) {
297    cpu::NativeFmt f;
298    std::string err;
299    if (!cpu::native_fmt(16, d_type, kH, kFF, f, err)) {
300        std::printf("  %-8s %s\n", type_name(d_type), err.c_str());
301        return 1;
302    }
303    std::vector<uint8_t> blob(f.bytes);
304    uint64_t seed = 0xd0e50000ull + (uint64_t) d_type;
305    fill_blob(blob.data(), f, seed);
306    const Acts a(f, 91u + (unsigned) d_type);
307    const uint8_t* w = blob.data() + f.down_off;
308    const size_t R = (size_t) kH;
309    std::vector<float> ref(kMaxT * R);
310    if (d_type == 20) {
311        for (int t = 0; t < kMaxT; ++t)
312            for (size_t r = 0; r < R; ++r)
313                traits_cpu(20)->vec_dot((int) kFF, &ref[t * R + r], 0, w + r * f.d_row, 0, a.dnp[t], 0, 1);
314    } else {   // Q2_0 in the GGUF layout against the kernels' own activations: w = d * (code - 1), in double
315        for (int t = 0; t < kMaxT; ++t)
316            for (size_t r = 0; r < R; ++r) {
317                const uint8_t* row = w + r * f.d_row;
318                double s = 0;
319                for (int b = 0; b < (int) (kFF / 64); ++b) {
320                    const float d = ggml_fp16_to_fp32(*(const ggml_fp16_t*) (row + 18 * b));
321                    for (int i = 0; i < 64; ++i) {
322                        const int code = (row[18 * b + 2 + i / 4] >> (2 * (i % 4))) & 3;
323                        const int k = 64 * b + i;
324                        s += (double) d * (code - 1) * a.q2[(size_t) t].scale[k / cpu::QKA] * a.q2[(size_t) t].q[k];
325                    }
326                }
327                ref[t * R + r] = (float) s;
328            }
329    }
330    auto run = [&](int v, int nt, float* const* out) {
331        if (d_type == 20) iq4nl_rows_v(v, w, f.d_row, a.dnp, nt, out);
332        else q2_rows_v(v, w, f.d_row, a.q2p, nt, out);
333    };
334    std::vector<float> one(kMaxT * R);
335    for (int t = 0; t < kMaxT; ++t) {
336        float* o = &one[t * R];
337        if (d_type == 20) iq4nl_rows_v(0, w, f.d_row, &a.dnp[t], 1, &o);
338        else q2_rows_v(0, w, f.d_row, &a.q2p[t], 1, &o);
339    }
340    int failures = 0;
341    const double r_ref = rel(one.data(), ref.data(), one.size());
342    std::printf("  %-8s down rows vs %s: rel %.2e\n", type_name(d_type),
343                d_type == 20 ? "ggml vec_dot" : "a double reference", r_ref);
344    if (!(r_ref <= 1e-5)) { std::printf("  %-8s MISMATCH against the reference\n", type_name(d_type)); ++failures; }
345    for (int v : subsets(down_variants())) {
346        size_t differ = 0;
347        std::vector<float> o(kMaxT * R);
348        for (int nt = 1; nt <= kMaxT; ++nt) {
349            float* op[kMaxT];
350            for (int t = 0; t < nt; ++t) op[t] = &o[t * R];
351            run(v, nt, op);
352            for (int t = 0; t < nt; ++t) differ += rows_differ(op[t], &one[t * R], R);
353        }
354        std::printf("  %-8s %-12s 1..8 tokens: %zu down rows differ from the %s one-token rows\n", type_name(d_type),
355                    variant_name(v).c_str(), differ, variant_name(0).c_str());
356        if (differ) ++failures;
357    }
358    return failures;
359}
360
361#if !defined(STRATA_IQ_PARITY_DISPATCH_ONLY)
362// #152 through the engine's dispatch: where native_gu_rows gives a format the multi-token kernel from one token on
363// (native_gu_mt_min 1: IQ3_S where its grid is gathered, or every format under STRATA_IQ_MT_MIN=1), each token's
364// gate/up rows must be the same alone and in any group.
365int check_engine_width(int type) {
366    const int mt = cpu::native_gu_mt_min(type);
367    if (mt != 1) {
368        std::printf("  %-8s engine: ggml's dot below %d tokens, its one-token rows round differently (#152)\n",
369                    type_name(type), mt);
370        return 0;
371    }
372    cpu::NativeFmt f;
373    std::string err;
374    if (!cpu::native_fmt(type, 20, kH, kFF, f, err)) return 1;
375    std::vector<uint8_t> blob(f.bytes);
376    uint64_t seed = 0xe9900000ull + (uint64_t) type;
377    fill_blob(blob.data(), f, seed);
378    const Acts a(f, 13u + (unsigned) type);
379    const size_t R = (size_t) kFF;
380    std::vector<float> one(kMaxT * R), ff(kMaxT * R);
381    for (int t = 0; t < kMaxT; ++t) {
382        float* o = &one[t * R];
383        cpu::native_gu_rows(f, blob.data(), &a.gup[t], 1, &o, 0, (int) kFF);
384    }
385    size_t differ = 0;
386    for (int nt = 2; nt <= kMaxT; ++nt) {
387        float* fp[kMaxT];
388        for (int t = 0; t < nt; ++t) fp[t] = &ff[t * R];
389        cpu::native_gu_rows(f, blob.data(), a.gup, nt, fp, 0, (int) kFF);
390        for (int t = 0; t < nt; ++t) differ += rows_differ(fp[t], &one[t * R], R);
391    }
392    std::printf("  %-8s engine: multi-token from one token on, 2..8 tokens: %zu gate/up rows differ from the one-token "
393                "rows\n", type_name(type), differ);
394    return differ ? 1 : 0;
395}
396#endif
397
398// ---- bench
399struct Method {
400    std::string name;
401    std::function<void(const uint8_t* blob, int nt)> gu, dn;
402};
403
404std::vector<int> ints(const std::string& s) {
405    std::vector<int> v;
406    size_t from = 0;
407    while (from <= s.size()) {
408        const size_t comma = s.find(',', from);
409        const std::string tok = s.substr(from, comma == std::string::npos ? std::string::npos : comma - from);
410        if (!tok.empty()) v.push_back(std::atoi(tok.c_str()));
411        if (comma == std::string::npos) break;
412        from = comma + 1;
413    }
414    return v;
415}
416
417int bench(const std::vector<std::string>& pairs, const std::vector<int>& nts, int mb, int reps, bool dispatch_only) {
418    for (const std::string& pair : pairs) {
419        const size_t slash = pair.find('/');
420        const int gt = slash == std::string::npos ? -1 : type_of(pair.substr(0, slash));
421        const int dt = slash == std::string::npos ? -1 : type_of(pair.substr(slash + 1));
422        cpu::NativeFmt f;
423        std::string err;
424        if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, kH, kFF, f, err) || !cpu::iq256_supported(gt) ||
425            (dt != 20 && dt != 42)) {
426            std::printf("%s: not a gate/up i-quant with an IQ4_NL or Q2_0 down %s\n", pair.c_str(), err.c_str());
427            return 2;
428        }
429        const size_t E = std::max<size_t>(16, ((size_t) mb << 20) / f.bytes);
430        std::unique_ptr<uint8_t[]> mem(new uint8_t[E * f.bytes + 64]);
431        uint8_t* blobs = (uint8_t*) (((uintptr_t) mem.get() + 63) & ~(uintptr_t) 63);
432        uint64_t seed = 0xbe9c0000ull + (uint64_t) gt * 64 + (uint64_t) dt;
433        for (size_t e = 0; e < E; ++e) fill_blob(blobs + e * f.bytes, f, seed);
434        const Acts a(f, 5u);
435        std::vector<float> ffb(kMaxT * (size_t) kFF), outb(kMaxT * (size_t) kH);
436        float* ff[kMaxT];
437        float* out[kMaxT];
438        for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
439        const ggml_vec_dot_t gdot = traits_cpu(gt)->vec_dot, ddot = traits_cpu(dt)->vec_dot;
440
441        std::vector<Method> ms;
442        auto down_v = [&, dt](int v) {
443            return [&, v, dt](const uint8_t* blob, int nt) {
444                if (dt == 20) iq4nl_rows_v(v, blob + f.down_off, f.d_row, a.dnp, nt, out);
445                else q2_rows_v(v, blob + f.down_off, f.d_row, a.q2p, nt, out);
446            };
447        };
448        if (!dispatch_only && kVariants) {
449            for (int v : subsets(gu_variants() | down_variants()))
450                ms.push_back({variant_name(v),
451                              [&, v, gt](const uint8_t* blob, int nt) { gu_rows_v(v, gt, blob, f.gu_row, f.up_off, a.gup, nt, ff); },
452                              down_v(v)});
453        } else {
454            ms.push_back({"kernels",
455                          [&, gt](const uint8_t* blob, int nt) {
456                              cpu::iq256_gu_rows(gt, blob, f.gu_row, f.up_off, (int) kH, a.gup, nt, ff, 0, (int) kFF);
457                          },
458                          [&, dt](const uint8_t* blob, int nt) {
459                              if (dt == 20) cpu::iq4nl256_down_rows(blob + f.down_off, f.d_row, (int) kFF, a.dnp, nt, out, 0, (int) kH);
460                              else cpu::q2_0_gguf_rows_multi_avx2(blob + f.down_off, f.d_row, (int) (kFF / 64), a.q2p, nt, out, 0, (int) kH);
461                          }});
462        }
463        ms.push_back({"ggml",   // ggml-cpu's dot, token by token: the engine's one-token path (#152's rule)
464                      [&](const uint8_t* blob, int nt) {
465                          for (int64_t r = 0; r < kFF; ++r)
466                              for (int t = 0; t < nt; ++t) {
467                                  float g = 0.f, u = 0.f;
468                                  gdot((int) kH, &g, 0, blob + (size_t) r * f.gu_row, 0, a.gup[t], 0, 1);
469                                  gdot((int) kH, &u, 0, blob + f.up_off + (size_t) r * f.gu_row, 0, a.gup[t], 0, 1);
470                                  ff[t][r] = (g / (1.f + std::exp(-g))) * u;
471                              }
472                      },
473                      [&](const uint8_t* blob, int nt) {
474                          for (int64_t r = 0; r < kH; ++r)
475                              for (int t = 0; t < nt; ++t)
476                                  ddot((int) kFF, &out[t][r], 0, blob + f.down_off + (size_t) r * f.d_row, 0, a.dnp[t], 0, 1);
477                      }});
478        if (gt == 16 || gt == 17 || gt == 18 || gt == 21 || gt == 22)
479            ms.push_back({"exact1", [&, gt](const uint8_t* blob, int nt) {
480                              for (int t = 0; t < nt; ++t)
481                                  cpu::iq256_gu_rows_exact_one(gt, blob, f.gu_row, f.up_off, (int) kH,
482                                                                 a.gup[t], ff[t], 0, (int) kFF);
483                          }, down_v(0)});
484        ms.push_back({"engine",   // what the pool calls: native_gu_rows, native_down_rows or (Q2_0) q2_rows_any
485                      [&](const uint8_t* blob, int nt) { cpu::native_gu_rows(f, blob, a.gup, nt, ff, 0, (int) kFF); },
486                      [&, dt](const uint8_t* blob, int nt) {
487                          if (dt == 42) cpu::q2_rows_any(blob + f.down_off, f.d_row, (int) (kFF / 64), a.q2p, nt, out, 0, (int) kH);
488                          else cpu::native_down_rows(f, blob, a.dnp, nt, out, 0, (int) kH);
489                      }});
490
491        std::printf("\n%s: %zu experts of %.2f MB (%.0f MB), one thread\n", pair.c_str(), E, f.bytes / 1048576.0,
492                    E * (double) f.bytes / 1048576.0);
493        for (int nt : nts) {
494            if (nt < 1 || nt > kMaxT) continue;
495            std::vector<std::vector<double>> tg(ms.size()), td(ms.size());
496            for (int rep = 0; rep < reps; ++rep)
497                for (size_t k = 0; k < ms.size(); ++k) {
498                    const size_t m = (k + (size_t) rep) % ms.size();   // rotate the order from rep to rep
499                    double sg = 0, sd = 0;
500                    for (size_t e = 0; e < E; ++e) {
501                        const uint8_t* blob = blobs + e * f.bytes;
502                        const auto t0 = Clock::now();
503                        ms[m].gu(blob, nt);
504                        const auto t1 = Clock::now();
505                        ms[m].dn(blob, nt);
506                        const auto t2 = Clock::now();
507                        sg += std::chrono::duration<double, std::milli>(t1 - t0).count();
508                        sd += std::chrono::duration<double, std::milli>(t2 - t1).count();
509                    }
510                    tg[m].push_back(sg / (double) E);
511                    td[m].push_back(sd / (double) E);
512                }
513            std::printf("  %d token%s ms per expert, median of %d (min): gate/up, down, total\n", nt, nt == 1 ? "" : "s",
514                        reps);
515            for (size_t m = 0; m < ms.size(); ++m) {
516                auto med = [](std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; };
517                auto mn = [](const std::vector<double>& v) { return *std::min_element(v.begin(), v.end()); };
518                std::vector<double> tot(tg[m].size());
519                for (size_t i = 0; i < tot.size(); ++i) tot[i] = tg[m][i] + td[m][i];
520                std::printf("    %-12s %7.3f (%.3f)  %7.3f (%.3f)  %7.3f (%.3f)\n", ms[m].name.c_str(), med(tg[m]),
521                            mn(tg[m]), med(td[m]), mn(td[m]), med(tot), mn(tot));
522            }
523        }
524    }
525    return 0;
526}
527
528}  // namespace
529
530int main(int argc, char** argv) {
531    setvbuf(stdout, nullptr, _IONBF, 0);
532    bool do_bench = false, dispatch_only = !kVariants;
533    int pin = -1, mb = 256, reps = 5;
534    std::vector<int> nts = {1, 2, 3, 4};
535    std::vector<std::string> pairs = {"iq3_s/iq4_nl", "iq3_xxs/iq4_nl", "iq2_s/q2_0", "iq2_xxs/q2_0"};
536    for (int i = 1; i < argc; ++i) {
537        const std::string a = argv[i];
538        const bool more = i + 1 < argc;
539        if (a == "--bench") do_bench = true;
540        else if (a == "--dispatch") dispatch_only = true;
541        else if (a == "--cpu" && more) pin = std::atoi(argv[++i]);
542        else if (a == "--mb" && more) mb = std::atoi(argv[++i]);
543        else if (a == "--reps" && more) reps = std::max(1, std::atoi(argv[++i]));
544        else if (a == "--nt" && more) nts = ints(argv[++i]);
545        else if (a == "--pairs" && more) {
546            pairs.clear();
547            const std::string s = argv[++i];
548            for (size_t from = 0;;) {
549                const size_t comma = s.find(',', from);
550                pairs.push_back(s.substr(from, comma == std::string::npos ? std::string::npos : comma - from));
551                if (comma == std::string::npos) break;
552                from = comma + 1;
553            }
554        } else {
555            std::fprintf(stderr, "usage: iq_avx2_parity [--cpu N] | --bench [--cpu N] [--nt 1,2,3,4] [--mb 256] "
556                                 "[--reps 5] [--pairs iq3_s/iq4_nl,...] [--dispatch]\n");
557            return 2;
558        }
559    }
560    if (pin >= 0 && !pin_to(pin)) std::printf("iq_avx2_parity: could not pin to CPU %d\n", pin);
561    ggml_cpu_init();
562    auto env = [](const char* k) { const char* v = std::getenv(k); return v ? v : "-"; };
563    std::printf("iq_avx2_parity: %s (avx2 %d, avx512 %d), CPU %d, core type %02Xh\n", cpu::cpu_name().c_str(),
564                (int) cpu::cpu_avx2_ok(), (int) cpu::cpu_avx512_ok(), pin, core_type());
565    std::printf("  STRATA_IQ256_GATHER %s, STRATA_NO_AVXVNNI %s, STRATA_IQ_MT_MIN %s, STRATA_IQ_PREFETCH %s\n",
566                env("STRATA_IQ256_GATHER"), env("STRATA_NO_AVXVNNI"), env("STRATA_IQ_MT_MIN"), env("STRATA_IQ_PREFETCH"));
567    if (!cpu::cpu_avx2_ok()) {
568        std::printf("iq_avx2_parity: no AVX2 here, nothing to check (the engine takes ggml-cpu's dot)\n");
569        return 0;
570    }
571#if !defined(STRATA_IQ_PARITY_DISPATCH_ONLY)
572    std::printf("  variants this CPU runs: %s; this thread's: %s\n",
573                variant_name(cpu::iq256_variants()).c_str(), variant_name(cpu::iq256_variant()).c_str());
574#endif
575    if (do_bench) return bench(pairs, nts, mb, reps, dispatch_only);
576    int failures = 0;
577    for (int type : {16, 17, 22, 18, 21, 23}) failures += check_gate_up(type);
578    for (int type : {20, 42}) failures += check_down(type);
579#if !defined(STRATA_IQ_PARITY_DISPATCH_ONLY)
580    for (int type : {16, 17, 22, 18, 21, 23}) failures += check_engine_width(type);
581#endif
582    std::printf("iq_avx2_parity: %d failures\n", failures);
583    return failures == 0 ? 0 : 1;
584}