okami.mom/strata

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

Niko1221Merge f-own-2a (7c09c4a75) into f-own-int: the Strata quant layer and the x86 CPU rows9c143c403

main
13.8 KiB292 linesraw
1// src/kernels/cpu/iq_avx1_parity.cpp - the AVX1 expert kernels (iq_avx1.cpp) against ggml-cpu's dots and
2// against themselves at every token count.  No GPU, no model: random blocks (every grid index and sign
3// pattern occurs) and random activations quantized the way the engine quantizes them.
4//
5//     iq_avx1_parity            IQ3_XXS/IQ3_S/IQ2_S/IQ4_XS gate/up rows and IQ4_NL/Q2_0 down rows:
6//                               every row bit for bit the same kernel's one-token row (#152), and rel <= 1e-5
7//                               against ggml-cpu's vec_dot (the scalar _generic the engine runs without these).
8//     iq_avx1_parity --bench [--mb 128] [--nt 1,2,4] [--cpu N]
9//                               ms per expert on one thread: ggml-cpu's per-token dot vs the iq128 kernel over
10//                               --mb MB of expert blobs (more than any L3: the weights stream from DRAM as in
11//                               decode), for the nt in --nt.
12//
13// Runs on any CPU with AVX (the kernels are compiled for SSE4.2 + AVX); on an AVX2 machine it checks the
14// older-CPU path exactly as an AVX-only machine runs it (the engine's dispatch gate is separate: this calls
15// the kernels directly).
16#include "strata/kernels/cpu/iq_avx1.hpp"
17#include "strata/kernels/cpu/native_expert.hpp"
18#include "strata/kernels/cpu/expert_layout.hpp"
19
20#include "ggml.h"
21#include "ggml-cpu.h"
22
23#include <algorithm>
24#include <chrono>
25#include <cmath>
26#include <cstdint>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <string>
31#include <vector>
32
33#if !defined(_WIN32)
34#include <sched.h>
35#endif
36
37namespace cpu = strata::kernels::cpu;
38using Clock = std::chrono::steady_clock;
39
40namespace {
41
42constexpr int kH = 2560, kFF = 640;   // the experts' geometry: n_embd, expert width (as iq_avx2_parity)
43constexpr int kMaxT = 8;
44
45uint64_t mix(uint64_t& s) {   // splitmix64
46    uint64_t z = (s += 0x9E3779B97F4A7C15ull);
47    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
48    z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
49    return z ^ (z >> 31);
50}
51
52const ggml_type_traits_cpu* traits_cpu(int type) { return ggml_get_type_traits_cpu((ggml_type) type); }
53
54// random bytes, then a sane fp16 scale at the front of every block (iq_avx2_parity's)
55void fill_blocks(uint8_t* p, size_t bytes, int type, uint64_t& seed) {
56    for (size_t i = 0; i < bytes; i += 8) {
57        const uint64_t v = mix(seed);
58        std::memcpy(p + i, &v, std::min<size_t>(8, bytes - i));
59    }
60    const size_t bs = ggml_type_size((ggml_type) type);
61    for (size_t o = 0; o + bs <= bytes; o += bs) {
62        const float d = (0.5f + (float) (mix(seed) >> 40) * (1.f / 16777216.f)) * 1e-3f;
63        const ggml_fp16_t h = ggml_fp32_to_fp16(d);
64        std::memcpy(p + o, &h, 2);
65    }
66}
67
68void fill_blob(uint8_t* blob, const cpu::NativeFmt& f, uint64_t& seed) {
69    fill_blocks(blob, f.down_off, f.gu_type, seed);                        // the gate and up rows
70    fill_blocks(blob + f.down_off, f.bytes - f.down_off, f.d_type, seed);  // the down rows
71}
72
73struct Case {
74    int gu, dn;
75    const char* name;
76};
77
78const Case kCases[] = {
79    {18, 20, "iq3_xxs/iq4_nl"}, {21, 20, "iq3_s/iq4_nl"}, {22, 20, "iq2_s/iq4_nl"}, {23, 20, "iq4_xs/iq4_nl"},
80    {18, 42, "iq3_xxs/q2_0"},   {21, 42, "iq3_s/q2_0"},   {22, 42, "iq2_s/q2_0"},   {23, 42, "iq4_xs/q2_0"},
81};
82
83// one expert, nt tokens of quantized activations, and the reference rows
84struct Fixture {
85    cpu::NativeFmt f;
86    std::vector<uint8_t> blob;
87    std::vector<std::vector<uint8_t>> act, hq;          // per token
88    std::vector<std::vector<float>> x, h;
89    std::vector<float> ff_ref, out_ref;                 // [t][row]
90};
91
92void make_fixture(Fixture& fx, int gu, int dn, int nt, uint64_t& seed) {
93    std::string err;
94    if (!cpu::native_fmt(gu, dn, kH, kFF, fx.f, err)) { std::fprintf(stderr, "native_fmt: %s\n", err.c_str()); std::exit(1); }
95    fx.blob.resize(fx.f.bytes);
96    fill_blob(fx.blob.data(), fx.f, seed);
97    fx.act.resize(nt); fx.hq.resize(nt); fx.x.resize(nt); fx.h.resize(nt);
98    for (int t = 0; t < nt; ++t) {
99        fx.act[t].resize(fx.f.act_bytes); fx.hq[t].resize(fx.f.h_bytes);
100        fx.x[t].resize(kH); fx.h[t].resize(kFF);
101        for (int i = 0; i < kH; ++i) fx.x[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0);
102        for (int i = 0; i < kFF; ++i) fx.h[t][i] = (float) ((mix(seed) >> 40) * 0x1p-24 * 2.0 - 1.0);
103        cpu::native_quant_act(fx.f, fx.x[t].data(), fx.act[t].data());
104        cpu::native_quant_h(fx.f, fx.h[t].data(), fx.hq[t].data());
105    }
106    // reference rows: ggml-cpu's own dots, per token (what the engine runs without the iq128 kernels)
107    const ggml_vec_dot_t gu_dot = traits_cpu(gu)->vec_dot;
108    const ggml_vec_dot_t dn_dot = traits_cpu(dn)->vec_dot;
109    fx.ff_ref.resize((size_t) nt * kFF); fx.out_ref.resize((size_t) nt * kH);
110    for (int t = 0; t < nt; ++t) {
111        for (int r = 0; r < kFF; ++r) {
112            float g = 0.f, u = 0.f;
113            gu_dot(kH, &g, 0, fx.blob.data() + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1);
114            gu_dot(kH, &u, 0, fx.blob.data() + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, fx.act[t].data(), 0, 1);
115            fx.ff_ref[(size_t) t * kFF + r] = (g / (1.f + std::exp(-g))) * u;
116        }
117        for (int r = 0; r < kH; ++r) {
118            float s = 0.f;
119            dn_dot(kFF, &s, 0, fx.blob.data() + fx.f.down_off + (size_t) r * fx.f.d_row, 0, fx.hq[t].data(), 0, 1);
120            fx.out_ref[(size_t) t * kH + r] = s;
121        }
122    }
123}
124
125int failures = 0;
126
127void check(const char* what, const std::vector<float>& got, const std::vector<float>& ref, bool exact) {
128    if (exact) {   // bit-exact (iq_avx2_parity's rows_differ)
129        size_t d = 0;
130        for (size_t i = 0; i < ref.size(); ++i) d += std::memcmp(&got[i], &ref[i], sizeof(float)) != 0;
131        if (d) { std::printf("  FAIL %s: %zu of %zu rows differ\n", what, d, ref.size()); ++failures; }
132        return;
133    }
134    // the repo's bar (iq_avx2_parity's rel): aggregate sum|diff| / sum|ref| <= 1e-5
135    double num = 0, den = 0;
136    for (size_t i = 0; i < ref.size(); ++i) {
137        num += std::fabs((double) got[i] - (double) ref[i]);
138        den += std::fabs((double) ref[i]);
139    }
140    const double r = num / (den + 1e-30);
141    if (!(r <= 1e-5)) { std::printf("  FAIL %s: rel %.3e > 1e-5 vs ggml-cpu\n", what, r); ++failures; }
142}
143
144// ---- the checks
145void run_checks() {
146    for (const Case& c : kCases) {
147        uint64_t seed = 0x5EED1234u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn;
148        Fixture fx;
149        make_fixture(fx, c.gu, c.dn, kMaxT, seed);
150        const void* actp[kMaxT]; const void* hqp[kMaxT];
151        std::vector<float> ff[kMaxT], out[kMaxT];
152        float* ffp[kMaxT]; float* outp[kMaxT];
153        for (int t = 0; t < kMaxT; ++t) {
154            actp[t] = fx.act[t].data(); hqp[t] = fx.hq[t].data();
155            ff[t].resize(kFF); out[t].resize(kH);
156            ffp[t] = ff[t].data(); outp[t] = out[t].data();
157        }
158        // gate/up: nt = 1..8, every width bit-identical to that token's nt = 1 row (#152), all rel <= 1e-5 vs ggml
159        std::vector<std::vector<float>> ff1(kMaxT), out1(kMaxT);
160        for (int nt = 1; nt <= kMaxT; ++nt) {
161            cpu::iq128_gu_rows(c.gu, fx.blob.data(), fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF);
162            for (int t = 0; t < nt; ++t) {
163                char what[96];
164                std::snprintf(what, sizeof what, "%s gu nt=%d vs ggml", c.name, nt);
165                check(what, ff[t], std::vector<float>(fx.ff_ref.begin() + (size_t) t * kFF,
166                                                      fx.ff_ref.begin() + (size_t) (t + 1) * kFF), false);
167                if (nt == 1) ff1[t] = ff[t];
168                else {
169                    std::snprintf(what, sizeof what, "%s gu nt=%d token %d vs its nt=1 row", c.name, nt, t);
170                    check(what, ff[t], ff1[t], true);
171                }
172            }
173        }
174        // down
175        for (int nt = 1; nt <= kMaxT; ++nt) {
176            cpu::iq128_down_rows(c.dn, fx.blob.data() + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH);
177            for (int t = 0; t < nt; ++t) {
178                char what[96];
179                std::snprintf(what, sizeof what, "%s down nt=%d vs ggml", c.name, nt);
180                check(what, out[t], std::vector<float>(fx.out_ref.begin() + (size_t) t * kH,
181                                                      fx.out_ref.begin() + (size_t) (t + 1) * kH), false);
182                if (nt == 1) out1[t] = out[t];
183                else {
184                    std::snprintf(what, sizeof what, "%s down nt=%d token %d vs its nt=1 row", c.name, nt, t);
185                    check(what, out[t], out1[t], true);
186                }
187            }
188        }
189        std::printf("  %-16s checked (gu %d, down %d)\n", c.name, c.gu, c.dn);
190    }
191}
192
193// ---- the bench: ms per expert, the weights streamed from DRAM
194void run_bench(int mb, const std::vector<int>& nts) {
195    for (const Case& c : kCases) {
196        uint64_t seed = 0xBEEF0000u + (uint64_t) c.gu * 1000 + (uint64_t) c.dn;
197        Fixture fx;
198        make_fixture(fx, c.gu, c.dn, 1, seed);
199        const size_t per = fx.f.bytes;
200        const int nexp = (int) ((size_t) mb * 1024 * 1024 / per);
201        std::vector<uint8_t> blob((size_t) nexp * per);
202        for (int e = 0; e < nexp; ++e) std::memcpy(blob.data() + (size_t) e * per, fx.blob.data(), per);
203        // vary the blocks a little so the run is not one blob repeated (the same bytes hit the same caches)
204        for (int e = 1; e < nexp; ++e) {
205            uint64_t s2 = seed + (uint64_t) e * 7919;
206            const size_t o = (size_t) e * per;
207            for (size_t i = 0; i + 8 <= per; i += 128) {
208                const uint64_t v = mix(s2);
209                std::memcpy(blob.data() + o + i, &v, 8);   // keep block scales (first 2 bytes of each block)
210            }
211        }
212        for (int nt : nts) {
213            if (nt > kMaxT) continue;
214            const void* actp[kMaxT]; const void* hqp[kMaxT];
215            float* ffp[kMaxT]; float* outp[kMaxT];
216            std::vector<std::vector<float>> ff(kMaxT, std::vector<float>(kFF)), out(kMaxT, std::vector<float>(kH));
217            Fixture fx8;   // nt tokens of activations
218            uint64_t s8 = seed + 0x1234;
219            make_fixture(fx8, c.gu, c.dn, nt, s8);
220            for (int t = 0; t < nt; ++t) {
221                actp[t] = fx8.act[t].data(); hqp[t] = fx8.hq[t].data();
222                ffp[t] = ff[t].data(); outp[t] = out[t].data();
223            }
224            const ggml_vec_dot_t gu_dot = traits_cpu(c.gu)->vec_dot, dn_dot = traits_cpu(c.dn)->vec_dot;
225            // ggml-cpu's path (what the engine runs today on this CPU): per-token dots over every row
226            auto t0 = Clock::now();
227            for (int e = 0; e < nexp; ++e) {
228                for (int r = 0; r < kFF; ++r) {
229                    for (int t = 0; t < nt; ++t) {
230                        float g = 0.f, u = 0.f;
231                        gu_dot(kH, &g, 0, blob.data() + (size_t) e * per + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1);
232                        gu_dot(kH, &u, 0, blob.data() + (size_t) e * per + fx.f.up_off + (size_t) r * fx.f.gu_row, 0, (const uint8_t*) actp[t], 0, 1);
233                        ff[t][r] = (g / (1.f + std::exp(-g))) * u;
234                    }
235                }
236                for (int r = 0; r < kH; ++r) {
237                    for (int t = 0; t < nt; ++t) {
238                        float s = 0.f;
239                        dn_dot(kFF, &s, 0, blob.data() + (size_t) e * per + fx.f.down_off + (size_t) r * fx.f.d_row, 0, (const uint8_t*) hqp[t], 0, 1);
240                        out[t][r] = s;
241                    }
242                }
243            }
244            const double ms_ggml = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
245            t0 = Clock::now();
246            for (int e = 0; e < nexp; ++e) {
247                cpu::iq128_gu_rows(c.gu, blob.data() + (size_t) e * per, fx.f.gu_row, fx.f.up_off, kH, actp, nt, ffp, 0, kFF);
248                cpu::iq128_down_rows(c.dn, blob.data() + (size_t) e * per + fx.f.down_off, fx.f.d_row, kFF, hqp, nt, outp, 0, kH);
249            }
250            const double ms_iq = std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
251            std::printf("  %-16s nt=%d  ggml %8.2f ms/expert   iq128 %6.2f ms/expert   %.1fx\n",
252                        c.name, nt, ms_ggml / nexp, ms_iq / nexp, ms_ggml / ms_iq);
253        }
254    }
255}
256
257}  // namespace
258
259int main(int argc, char** argv) {
260    ggml_cpu_init();   // the oracle's own tables (native_fmt used to do it; the pool no longer calls ggml-cpu with STRATA_OWN_CPU_QUANT)
261    bool bench = false;
262    int mb = 128, cpu_pin = -1;
263    std::vector<int> nts = {1, 2, 4};
264    for (int i = 1; i < argc; ++i) {
265        std::string a = argv[i];
266        if (a == "--bench") bench = true;
267        else if (a == "--mb" && i + 1 < argc) mb = std::atoi(argv[++i]);
268        else if (a == "--cpu" && i + 1 < argc) cpu_pin = std::atoi(argv[++i]);
269        else if (a == "--nt" && i + 1 < argc) {
270            nts.clear();
271            const char* p = argv[++i];
272            while (*p) { nts.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p == ',') ++p; }
273        } else {
274            std::printf("usage: iq_avx1_parity [--bench [--mb N] [--nt 1,2,4] [--cpu N]]\n");
275            return 2;
276        }
277    }
278#if !defined(_WIN32)
279    if (cpu_pin >= 0) {
280        cpu_set_t set;
281        CPU_ZERO(&set);
282        CPU_SET(cpu_pin, &set);
283        if (sched_setaffinity(0, sizeof set, &set) != 0) std::fprintf(stderr, "pinning to CPU %d failed\n", cpu_pin);
284    }
285#endif
286    if (!cpu::cpu_avx1_ok()) { std::printf("iq_avx1_parity: no AVX here, the kernels would not run\n"); return 0; }
287    std::printf("iq_avx1_parity: %s\n", cpu::cpu_avx1_ok() ? "AVX1 kernels checked (128-bit lanes)" : "");
288    if (bench) { run_bench(mb, nts); return failures != 0; }
289    run_checks();
290    std::printf(failures ? "iq_avx1_parity: %d FAILURES\n" : "iq_avx1_parity: all rows match\n", failures);
291    return failures != 0;
292}