okami.mom/strata

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

Niko1221Merge f-own-2n2 8bb2669c0 into f-own-int60bf91db2

main
8.6 KiB182 linesraw
1// src/kernels/cpu/pool_rows_bench.cpp - the CPU expert pool's own row functions (native_gu_rows / native_down_rows), no model, no GPU:
2// (1) bits: every token's gate/up and down rows against ggml-cpu's own one-row dot and the same SwiGLU, at 1..16 tokens per expert;
3// (2) speed: one thread, E experts streamed from memory, ns per expert for gate/up and down at each token count.
4// With STRATA_OWN_CPU_QUANT the rows run on the Strata quant layer and (1) checks them against ggml-cpu; without it both sides are ggml-cpu.
5// Comparing the two builds' (2) is the pool-level A/B of the layer against ggml-cpu (OWN-2N2: the arm64 gap sat in this loop, not in a dot).
6//
7// usage: pool_rows_bench [--check-only] [--rounds N] [--experts E] [--nt 1,2,4,8,16] [--pair gu/down ...]   (pairs by ggml type name, e.g. iq3_s/iq4_nl)
8// exit status 1 on any differing row.
9#include "strata/kernels/cpu/native_expert.hpp"
10
11#include "ggml-cpu.h"
12#include "ggml.h"
13
14#include <algorithm>
15#include <chrono>
16#include <cmath>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <string>
21#include <vector>
22
23namespace cpu = strata::kernels::cpu;
24
25namespace {
26
27double now() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
28
29struct Rng {
30    uint64_t s = 0x9E3779B97F4A7C15ull;
31    float gauss() {
32        float a = 0;
33        for (int i = 0; i < 4; ++i) {
34            s ^= s >> 12; s ^= s << 25; s ^= s >> 27;
35            a += (float) ((s * 0x2545F4914F6CDD1Dull) >> 40) / 16777216.0f - 0.5f;
36        }
37        return a;
38    }
39};
40
41int type_by_name(const std::string& n) {
42    for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
43        const char* tn = ggml_type_name((ggml_type) t);
44        if (tn != nullptr && n == tn) return t;
45    }
46    return -1;
47}
48
49void quantize_rows(int type, const float* src, uint8_t* dst, int64_t rows, int64_t n) {
50    ggml_quantize_init((ggml_type) type);
51    std::vector<float> im((size_t) n, 1.f);
52    ggml_quantize_chunk((ggml_type) type, src, dst, 0, rows, n, ggml_quantize_requires_imatrix((ggml_type) type) ? im.data() : nullptr);
53}
54
55float ggml_dot(int type, int n, const void* w, const void* a) {
56    float s = 0.f;
57    ggml_get_type_traits_cpu((ggml_type) type)->vec_dot(n, &s, 0, w, 0, a, 0, 1);
58    return s;
59}
60
61double median(std::vector<double> v) {
62    std::sort(v.begin(), v.end());
63    return v[v.size() / 2];
64}
65
66}  // namespace
67
68int main(int argc, char** argv) {
69    int rounds = 9, E = 48;
70    bool check_only = false;
71    std::vector<int> nts = {1, 2, 3, 4, 8, 16};
72    std::vector<std::string> pairs;
73    int64_t n_embd = 2048, n_ff = 768;
74    for (int i = 1; i < argc; ++i) {
75        const std::string a = argv[i];
76        if (a == "--check-only") check_only = true;
77        else if (a == "--rounds" && i + 1 < argc) rounds = std::atoi(argv[++i]);
78        else if (a == "--experts" && i + 1 < argc) E = std::max(1, std::atoi(argv[++i]));
79        else if (a == "--embd" && i + 1 < argc) n_embd = std::atoll(argv[++i]);
80        else if (a == "--ff" && i + 1 < argc) n_ff = std::atoll(argv[++i]);
81        else if (a == "--nt" && i + 1 < argc) {
82            nts.clear();
83            for (const char* p = argv[++i]; *p;) { nts.push_back(std::max(1, std::min(16, std::atoi(p)))); while (*p && *p != ',') ++p; if (*p) ++p; }
84        } else if (a == "--pair" && i + 1 < argc) pairs.push_back(argv[++i]);
85        else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
86    }
87    if (pairs.empty()) pairs = {"iq3_s/iq4_nl", "iq2_s/iq4_nl", "iq3_xxs/iq4_nl", "iq2_xxs/q5_0", "iq4_xs/q5_0", "q4_K/q5_0"};
88    ggml_cpu_init();
89#if defined(STRATA_OWN_CPU_QUANT)
90    const char* lib = "the quant layer";
91#else
92    const char* lib = "ggml-cpu";
93#endif
94    std::printf("pool_rows_bench: rows on %s, n_embd %lld, n_ff %lld, %d experts, %d rounds, one thread\n", lib, (long long) n_embd, (long long) n_ff, E,
95                rounds);
96    int failures = 0;
97    Rng rng;
98    for (const std::string& pr : pairs) {
99        const size_t sl = pr.find('/');
100        const int gt = type_by_name(pr.substr(0, sl)), dt = sl == std::string::npos ? -1 : type_by_name(pr.substr(sl + 1));
101        cpu::NativeFmt f;
102        std::string err;
103        if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, n_embd, n_ff, f, err)) {
104            std::printf("  %-16s skipped: %s\n", pr.c_str(), err.empty() ? "unknown type" : err.c_str());
105            continue;
106        }
107        // one expert's weights from gaussian floats, copied into E blobs (distinct memory: the timing streams like the pool's experts)
108        std::vector<uint8_t> one(f.bytes, 0);
109        {
110            std::vector<float> w((size_t) (n_ff * n_embd));
111            for (auto& v : w) v = rng.gauss();
112            quantize_rows(gt, w.data(), one.data(), n_ff, n_embd);
113            for (auto& v : w) v = rng.gauss();
114            quantize_rows(gt, w.data(), one.data() + f.up_off, n_ff, n_embd);
115            std::vector<float> d((size_t) (n_embd * n_ff));
116            for (auto& v : d) v = rng.gauss();
117            quantize_rows(dt, d.data(), one.data() + f.down_off, n_embd, n_ff);
118        }
119        const size_t stride = (f.bytes + 4095) / 4096 * 4096;
120        std::vector<uint8_t> blobs(stride * (size_t) E);
121        for (int e = 0; e < E; ++e) std::memcpy(blobs.data() + stride * (size_t) e, one.data(), f.bytes);
122        // 16 tokens' activations and hiddens
123        constexpr int MT = 16;
124        std::vector<std::vector<uint8_t>> act(MT, std::vector<uint8_t>(f.act_bytes)), hq(MT, std::vector<uint8_t>(f.h_bytes));
125        std::vector<std::vector<float>> ff(MT, std::vector<float>((size_t) n_ff)), out(MT, std::vector<float>((size_t) n_embd));
126        for (int t = 0; t < MT; ++t) {
127            std::vector<float> x((size_t) n_embd), h((size_t) n_ff);
128            for (auto& v : x) v = rng.gauss();
129            for (auto& v : h) v = 0.25f * rng.gauss();
130            cpu::native_quant_act(f, x.data(), act[t].data());
131            cpu::native_quant_h(f, h.data(), hq[t].data());
132        }
133        const void* ap[MT];
134        const void* hp[MT];
135        float* fp[MT];
136        float* op[MT];
137        for (int t = 0; t < MT; ++t) { ap[t] = act[t].data(); hp[t] = hq[t].data(); fp[t] = ff[t].data(); op[t] = out[t].data(); }
138        // (1) bits at every token count (arm64: every row goes through the one-row dot loop; on x86 the multi-token kernels sum differently and
139        // have their own parity programs, so only the speed part runs there)
140        int bad = 0;
141#if defined(__aarch64__) || defined(_M_ARM64)
142        for (const int nt : nts) {
143            cpu::native_gu_rows(f, one.data(), ap, nt, fp, 0, (int) n_ff);
144            cpu::native_down_rows(f, one.data(), hp, nt, op, 0, (int) n_embd);
145            for (int t = 0; t < nt; ++t) {
146                for (int64_t r = 0; r < n_ff; ++r) {
147                    const float g = ggml_dot(gt, (int) n_embd, one.data() + (size_t) r * f.gu_row, ap[t]);
148                    const float u = ggml_dot(gt, (int) n_embd, one.data() + f.up_off + (size_t) r * f.gu_row, ap[t]);
149                    const float want = (g / (1.f + std::exp(-g))) * u;
150                    if (std::memcmp(&want, &ff[t][(size_t) r], sizeof want) != 0) ++bad;
151                }
152                for (int64_t r = 0; r < n_embd; ++r) {
153                    const float want = ggml_dot(dt, (int) n_ff, one.data() + f.down_off + (size_t) r * f.d_row, hp[t]);
154                    if (std::memcmp(&want, &out[t][(size_t) r], sizeof want) != 0) ++bad;
155                }
156            }
157        }
158        std::printf("  %-16s bits vs ggml-cpu's one-row dot at %zu token counts: %s (%d rows differ)\n", pr.c_str(), nts.size(), bad ? "DIFFER" : "identical",
159                    bad);
160#else
161        std::printf("  %-16s bits: not checked on this ISA (see native_arithmetic_parity)\n", pr.c_str());
162#endif
163        failures += bad != 0;
164        if (check_only) continue;
165        // (2) speed
166        for (const int nt : nts) {
167            std::vector<double> tg, td;
168            for (int rd = 0; rd < rounds; ++rd) {
169                const double t0 = now();
170                for (int e = 0; e < E; ++e) cpu::native_gu_rows(f, blobs.data() + stride * (size_t) e, ap, nt, fp, 0, (int) n_ff);
171                const double t1 = now();
172                for (int e = 0; e < E; ++e) cpu::native_down_rows(f, blobs.data() + stride * (size_t) e, hp, nt, op, 0, (int) n_embd);
173                const double t2 = now();
174                tg.push_back((t1 - t0) / E * 1e9);
175                td.push_back((t2 - t1) / E * 1e9);
176            }
177            std::printf("    nt %2d  gate/up %10.0f ns/expert  down %10.0f ns/expert  (median of %d)\n", nt, median(tg), median(td), rounds);
178        }
179    }
180    std::printf("pool_rows_bench: %s\n", failures ? "FAILED" : "all rows identical");
181    return failures ? 1 : 0;
182}