okami.mom/strata

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

Niko1221Merge f-0216-cpu into f-0216-allf2eedfe9f

main
11.8 KiB224 linesraw
1// src/kernels/cpu/kq_cpu_bench.cpp - MODEL-UPDATE: how close the CPU pool's expert rows come to the RAM bandwidth, per
2// expert format.  No GPU, no model: --mb MB of expert blobs (ggml-quantized random weights, far more than any L3) are
3// computed by T threads at once through the engine's own entry points (native_gu_rows + native_down_rows, the pool's
4// calls), each thread walking its own experts, nt tokens per expert - the decode case, where every CPU expert is a
5// fresh read from DRAM.  Prints the weight bytes per second against the --ram-gbs given (a separate read test).
6//
7//     kq_cpu_bench [--pairs q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl] [--threads 1,8,16,32] [--nt 1,2,4]
8//                  [--mb 4096] [--reps 3] [--ram-gbs N] [--part both|gu|down] [--hot K]
9//
10// --part times only the gate/up rows (gu) or only the down rows (down); --hot K walks only K distinct expert blobs over and
11// over (K=1: one expert, cache-resident: the arithmetic and instruction throughput; the default walks --mb of blobs: DRAM).
12#include "strata/kernels/cpu/expert_layout.hpp"
13#include "strata/kernels/cpu/native_expert.hpp"
14
15#include "ggml.h"
16#include "ggml-cpu.h"
17
18#include <algorithm>
19#include <atomic>
20#include <chrono>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <memory>
26#include <random>
27#include <string>
28#include <thread>
29#include <vector>
30
31namespace cpu = strata::kernels::cpu;
32
33namespace {
34
35constexpr int64_t kH = 2560, kFF = 640;
36constexpr int kMaxT = 8;
37
38int type_of(const std::string& s) {
39    for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
40        const char* n = ggml_type_name((ggml_type) t);
41        if (n != nullptr && s == n) return t;
42    }
43    return -1;
44}
45
46std::vector<std::string> split(const std::string& s) {
47    std::vector<std::string> v;
48    size_t from = 0;
49    for (;;) {
50        const size_t c = s.find(',', from);
51        v.push_back(s.substr(from, c == std::string::npos ? std::string::npos : c - from));
52        if (c == std::string::npos) break;
53        from = c + 1;
54    }
55    return v;
56}
57
58// one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random
59// weights quantized by ggml (valid scales, as a real file has).  ggml_quantize_chunk, not the CPU traits' from_float:
60// ggml-cpu has no from_float for the i-quants (IQ3_S called a null pointer: an access violation on Windows)
61void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) {
62    std::normal_distribution<float> nd(0.f, 0.02f);
63    std::vector<float> row((size_t) std::max(kH, kFF));
64    const std::vector<float> imatrix((size_t) std::max(kH, kFF), 1.0f);
65    auto quant = [&](int type, uint8_t* dst, int64_t n) {
66        ggml_quantize_chunk((ggml_type) type, row.data(), dst, 0, 1, n,
67                            ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr);
68    };
69    for (int64_t r = 0; r < 2 * kFF; ++r) {
70        for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng);
71        quant(f.gu_type, blob + (size_t) r * f.gu_row, kH);
72    }
73    for (int64_t r = 0; r < kH; ++r) {
74        for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng);
75        quant(f.d_type, blob + f.down_off + (size_t) r * f.d_row, kFF);
76    }
77}
78
79}  // namespace
80
81int main(int argc, char** argv) {
82    setvbuf(stdout, nullptr, _IONBF, 0);
83    std::vector<std::string> pairs = split("q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl");
84    std::vector<int> threads = {1, 8, 16, 32}, nts = {1, 2, 4};
85    int mb = 4096, reps = 3, hot = 0;
86    double ram = 0;
87    std::string part = "both";
88    for (int i = 1; i < argc; ++i) {
89        const std::string a = argv[i];
90        const bool more = i + 1 < argc;
91        auto ints = [](const std::string& s) { std::vector<int> v; for (auto& x : split(s)) v.push_back(std::atoi(x.c_str())); return v; };
92        if (a == "--pairs" && more) pairs = split(argv[++i]);
93        else if (a == "--threads" && more) threads = ints(argv[++i]);
94        else if (a == "--nt" && more) nts = ints(argv[++i]);
95        else if (a == "--mb" && more) mb = std::atoi(argv[++i]);
96        else if (a == "--reps" && more) reps = std::max(1, std::atoi(argv[++i]));
97        else if (a == "--ram-gbs" && more) ram = std::atof(argv[++i]);
98        else if (a == "--part" && more) part = argv[++i];
99        else if (a == "--hot" && more) hot = std::max(0, std::atoi(argv[++i]));
100        else {
101            std::fprintf(stderr, "usage: kq_cpu_bench [--pairs a/b,...] [--threads 1,8] [--nt 1,2,4] [--mb 4096] [--reps 3] [--ram-gbs N]\n");
102            return 2;
103        }
104    }
105    const bool do_gu = part != "down", do_down = part != "gu";
106    ggml_cpu_init();
107    std::printf("kq_cpu_bench: %s (avx2 %d, avx512 %d), %d MB of blobs per format\n", cpu::cpu_name().c_str(),
108                (int) cpu::cpu_avx2_ok(), (int) cpu::cpu_avx512_ok(), mb);
109    for (const std::string& pair : pairs) {
110        const size_t slash = pair.find('/');
111        const int gt = slash == std::string::npos ? -1 : type_of(pair.substr(0, slash));
112        const int dt = slash == std::string::npos ? -1 : type_of(pair.substr(slash + 1));
113        cpu::NativeFmt f;
114        std::string err;
115        if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, kH, kFF, f, err)) {
116            std::printf("%s: %s\n", pair.c_str(), err.empty() ? "unknown types" : err.c_str());
117            continue;
118        }
119        ggml_quantize_init((ggml_type) gt);   // the i-quants' quantizers need their grids first
120        ggml_quantize_init((ggml_type) dt);
121        const size_t E = std::max<size_t>(64, ((size_t) mb << 20) / f.bytes);
122        std::unique_ptr<uint8_t[]> mem(new uint8_t[E * f.bytes + 4096]);
123        uint8_t* blobs = (uint8_t*) (((uintptr_t) mem.get() + 4095) & ~(uintptr_t) 4095);
124        {   // 16 distinct experts, copied over the whole buffer (the bytes in DRAM are what is measured)
125            std::mt19937 rng(1234 + gt * 64 + dt);
126            const size_t U = std::min<size_t>(16, E);
127            for (size_t e = 0; e < U; ++e) make_blob(f, blobs + e * f.bytes, rng);
128            for (size_t e = U; e < E; ++e) std::memcpy(blobs + e * f.bytes, blobs + (e % U) * f.bytes, f.bytes);
129        }
130        // activations: kMaxT tokens of x (n_embd) and h (n_ff), quantized the way the pool quantizes them
131        std::mt19937 rng(77);
132        std::normal_distribution<float> nd(0.f, 1.f);
133        std::vector<std::vector<uint8_t>> xa(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes)),
134            ha(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
135        const void* act[kMaxT];
136        const void* hq[kMaxT];
137        // a Q2_0 down takes the pool's own path (pool.cpp, run_split_multi_native and drain mode 6): the activation
138        // as an ActQ (act_quant_any) and Strata's Q2_0 rows (q2_rows_any), not ggml-cpu's Q2_0 dot
139        const bool q2_down = cpu::q2_native_kernels(f.d_type);
140        std::vector<cpu::ActQ> h2(q2_down ? kMaxT : 0);
141        const cpu::ActQ* a2[kMaxT] = {};
142        // a Q2_0 gate/up the same (pool.cpp mode 5): x as an ActQ, gate and up on q2_rows_any, then SwiGLU
143        const bool q2_gu = cpu::q2_native_kernels(f.gu_type);
144        std::vector<cpu::ActQ> x2(q2_gu ? kMaxT : 0);
145        const cpu::ActQ* ax[kMaxT] = {};
146        for (int t = 0; t < kMaxT; ++t) {
147            std::vector<float> x(kH), h(kFF);
148            for (auto& v : x) v = nd(rng);
149            for (auto& v : h) v = 0.1f * nd(rng);
150            if (q2_gu) {
151                cpu::act_quant_any(x.data(), (int) kH, x2[(size_t) t]);
152                ax[t] = &x2[(size_t) t];
153            } else {
154                cpu::native_quant_act(f, x.data(), xa[t].data());
155            }
156            if (q2_down) {
157                cpu::act_quant_any(h.data(), (int) kFF, h2[(size_t) t]);
158                a2[t] = &h2[(size_t) t];
159            } else {
160                cpu::native_quant_h(f, h.data(), ha[t].data());
161            }
162            act[t] = xa[t].data();
163            hq[t] = ha[t].data();
164        }
165        std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)%s%s\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6,
166                    q2_gu ? ", Q2_0 gate/up" : "", q2_down ? ", Q2_0 down on Strata's rows (the pool's path)" : "");
167        const double part_bytes = do_gu && do_down ? (double) f.bytes : do_gu ? (double) f.down_off : (double) (f.bytes - f.down_off);
168        for (int nt : nts) {
169            for (int T : threads) {
170                if (T < 1) continue;
171                std::vector<double> gbs;
172                for (int rep = 0; rep < reps; ++rep) {
173                    std::atomic<size_t> next{0};
174                    auto work = [&] {
175                        std::vector<float> ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH);
176                        std::vector<float> gb(q2_gu ? (size_t) kMaxT * kFF : 0), ub(q2_gu ? (size_t) kMaxT * kFF : 0);
177                        float* gp[kMaxT] = {};
178                        float* up[kMaxT] = {};
179                        if (q2_gu)
180                            for (int t = 0; t < kMaxT; ++t) { gp[t] = &gb[(size_t) t * kFF]; up[t] = &ub[(size_t) t * kFF]; }
181                        float* ff[kMaxT];
182                        float* out[kMaxT];
183                        for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
184                        std::vector<std::vector<uint8_t>> hb(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
185                        for (;;) {
186                            const size_t e = next.fetch_add(1);
187                            if (e >= E) break;
188                            const uint8_t* blob = blobs + (hot > 0 ? e % (size_t) hot : e) * f.bytes;
189                            if (!do_gu) {
190                            } else if (q2_gu) {
191                                cpu::q2_rows_any(blob, f.gu_row, (int) (kH / 64), ax, nt, gp, 0, (int) kFF);
192                                cpu::q2_rows_any(blob + f.up_off, f.gu_row, (int) (kH / 64), ax, nt, up, 0, (int) kFF);
193                                for (int t = 0; t < nt; ++t)
194                                    for (int64_t r = 0; r < kFF; ++r)
195                                        ff[t][r] = (gp[t][r] / (1.f + std::exp(-gp[t][r]))) * up[t][r];
196                            } else {
197                                cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF);
198                            }
199                            if (!do_down) {
200                            } else if (q2_down)
201                                cpu::q2_rows_any(blob + f.down_off, f.d_row, (int) (f.n_ff / 64), a2, nt, out, 0, (int) kH);
202                            else
203                                cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH);
204                        }
205                        volatile float sink = outb[0] + ffb[0];
206                        (void) sink;
207                    };
208                    const auto t0 = std::chrono::steady_clock::now();
209                    std::vector<std::thread> th;
210                    for (int k = 0; k < T; ++k) th.emplace_back(work);
211                    for (auto& x : th) x.join();
212                    const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
213                    gbs.push_back(E * part_bytes / s / 1e9);
214                }
215                std::sort(gbs.begin(), gbs.end());
216                const double med = gbs[gbs.size() / 2];
217                std::printf("  nt %d threads %2d: %6.1f GB/s of weights (%.3f ms per expert per thread)%s\n", nt, T, med,
218                            part_bytes / (med * 1e9 / T) * 1e3,
219                            ram > 0 ? (" = " + std::to_string((int) std::lround(100 * med / ram)) + "% of RAM").c_str() : "");
220            }
221        }
222    }
223    return 0;
224}