okami.mom/strata

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

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

main
12.4 KiB246 linesraw
1// src/kernels/cpu/kq_window_bench.cpp - round 0216: the CPU pool's share of a decode window, replayed without a GPU.
2//
3// kq_cpu_bench times one format pair; a decode window is 48 layers back to back, each layer a different format pair, ~12 missed experts a layer
4// of 1-4 token rows each, split over the pool's threads with a join between gate/up and down.  This runs that shape on the engine's own entry points
5// (native_gu_rows + native_down_rows) over DRAM-sized expert memory: for every layer the pair is that layer's (native_experts.txt of the pack), the
6// number of distinct missed experts and each one's token rows are drawn to match what the engine logs (STRATA_DECODE_TIMING: "CPU experts X (Y entries)"),
7// and the experts are picked at random from a per-pair arena of several GB, so every expert is a cold read.  Output: ms per window and per layer.
8//
9//   kq_window_bench --layers PACK/native_experts.txt [--windows 60] [--threads 8] [--distinct 11.6] [--rows 1.7] [--arena-mb 2048] [--reps 3]
10//
11// It is a replay with synthetic routing calibrated on observed means, not an engine run: it says what the kernels do to the pool's time, not what a
12// request's tokens/s do.
13#include "strata/kernels/cpu/expert_layout.hpp"
14#include "strata/kernels/cpu/native_expert.hpp"
15
16#include "ggml.h"
17#include "ggml-cpu.h"
18
19#include <algorithm>
20#include <atomic>
21#include <chrono>
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <map>
27#include <memory>
28#include <random>
29#include <string>
30#include <thread>
31#include <vector>
32
33namespace cpu = strata::kernels::cpu;
34
35namespace {
36
37constexpr int64_t kH = 2560, kFF = 640;
38constexpr int kMaxT = 8;
39
40struct Pair {
41    cpu::NativeFmt f;
42    std::unique_ptr<uint8_t[]> mem;
43    uint8_t* blobs = nullptr;
44    size_t E = 0;
45};
46
47struct Barrier {   // spinning sense-reversing barrier: the pool's workers spin briefly between phases too
48    explicit Barrier(int n) : n_(n) {}
49    void wait() {
50        const int s = sense_.load(std::memory_order_acquire);
51        if (count_.fetch_add(1, std::memory_order_acq_rel) + 1 == n_) {
52            count_.store(0, std::memory_order_relaxed);
53            sense_.fetch_add(1, std::memory_order_release);
54        } else {
55            while (sense_.load(std::memory_order_acquire) == s) { }
56        }
57    }
58    int n_;
59    std::atomic<int> count_{0}, sense_{0};
60};
61
62struct Task { int pair; size_t blob; int nt; };
63
64}  // namespace
65
66int main(int argc, char** argv) {
67    setvbuf(stdout, nullptr, _IONBF, 0);
68    std::string layers_file, dump_trace;
69    int windows = 60, threads = 8, reps = 3;
70    double distinct = 11.6, rows_mean = 1.7, arena_mb = 2048;
71    unsigned seed = 7;
72    for (int i = 1; i < argc; ++i) {
73        const std::string a = argv[i];
74        const bool more = i + 1 < argc;
75        if (a == "--layers" && more) layers_file = argv[++i];
76        else if (a == "--windows" && more) windows = std::atoi(argv[++i]);
77        else if (a == "--threads" && more) threads = std::atoi(argv[++i]);
78        else if (a == "--distinct" && more) distinct = std::atof(argv[++i]);
79        else if (a == "--rows" && more) rows_mean = std::atof(argv[++i]);
80        else if (a == "--arena-mb" && more) arena_mb = std::atof(argv[++i]);
81        else if (a == "--reps" && more) reps = std::atoi(argv[++i]);
82        else if (a == "--dump-trace" && more) dump_trace = argv[++i];
83        else if (a == "--seed" && more) seed = (unsigned) std::atoi(argv[++i]);
84        else { std::fprintf(stderr, "usage: kq_window_bench --layers native_experts.txt [--windows 60] [--threads 8] [--distinct 11.6] [--rows 1.7] [--arena-mb 2048] [--reps 3]\n"); return 2; }
85    }
86    if (layers_file.empty()) { std::fprintf(stderr, "kq_window_bench: --layers is required\n"); return 2; }
87    ggml_cpu_init();
88    // layer -> pair
89    std::vector<int> layer_pair;
90    std::vector<std::pair<int, int>> pair_types;
91    {
92        std::FILE* fp = std::fopen(layers_file.c_str(), "r");
93        if (!fp) { std::fprintf(stderr, "cannot open %s\n", layers_file.c_str()); return 2; }
94        char line[512];
95        while (std::fgets(line, sizeof line, fp)) {
96            int l, g, d;
97            if (std::sscanf(line, "%d %d %d", &l, &g, &d) == 3) {
98                auto it = std::find(pair_types.begin(), pair_types.end(), std::make_pair(g, d));
99                int idx = (int) (it - pair_types.begin());
100                if (it == pair_types.end()) pair_types.push_back({g, d});
101                if ((int) layer_pair.size() <= l) layer_pair.resize((size_t) l + 1, 0);
102                layer_pair[(size_t) l] = idx;
103            }
104        }
105        std::fclose(fp);
106    }
107    const int L = (int) layer_pair.size();
108    std::vector<Pair> pairs(pair_types.size());
109    std::mt19937 rng(1234);
110    std::normal_distribution<float> nd(0.f, 0.02f);
111    std::vector<float> row((size_t) std::max(kH, kFF));
112    const std::vector<float> imatrix((size_t) std::max(kH, kFF), 1.0f);
113    for (size_t p = 0; p < pairs.size(); ++p) {
114        std::string err;
115        Pair& P = pairs[p];
116        if (!cpu::native_fmt(pair_types[p].first, pair_types[p].second, kH, kFF, P.f, err)) { std::fprintf(stderr, "pair %zu: %s\n", p, err.c_str()); return 2; }
117        ggml_quantize_init((ggml_type) P.f.gu_type);
118        ggml_quantize_init((ggml_type) P.f.d_type);
119        P.E = std::max<size_t>(64, (size_t) (arena_mb * 1048576.0) / P.f.bytes);
120        P.mem.reset(new uint8_t[P.E * P.f.bytes + 4096]);
121        P.blobs = (uint8_t*) (((uintptr_t) P.mem.get() + 4095) & ~(uintptr_t) 4095);
122        const size_t U = std::min<size_t>(16, P.E);
123        auto quant = [&](int type, uint8_t* dst, int64_t n) {
124            ggml_quantize_chunk((ggml_type) type, row.data(), dst, 0, 1, n, ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr);
125        };
126        for (size_t e = 0; e < U; ++e) {
127            uint8_t* b = P.blobs + e * P.f.bytes;
128            for (int64_t r = 0; r < 2 * kFF; ++r) { for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng); quant(P.f.gu_type, b + (size_t) r * P.f.gu_row, kH); }
129            for (int64_t r = 0; r < kH; ++r) { for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng); quant(P.f.d_type, b + P.f.down_off + (size_t) r * P.f.d_row, kFF); }
130        }
131        for (size_t e = U; e < P.E; ++e) std::memcpy(P.blobs + e * P.f.bytes, P.blobs + (e % U) * P.f.bytes, P.f.bytes);
132    }
133    // activations per pair (kMaxT tokens), quantized the way the pool does
134    struct Act { std::vector<std::vector<uint8_t>> x, h; };
135    std::vector<Act> acts(pairs.size());
136    std::normal_distribution<float> xd(0.f, 1.f);
137    for (size_t p = 0; p < pairs.size(); ++p) {
138        acts[p].x.assign(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes));
139        acts[p].h.assign(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
140        for (int t = 0; t < kMaxT; ++t) {
141            std::vector<float> x(kH), h(kFF);
142            for (auto& v : x) v = xd(rng);
143            for (auto& v : h) v = 0.3f * xd(rng);
144            cpu::native_quant_act(pairs[p].f, x.data(), acts[p].x[(size_t) t].data());
145            cpu::native_quant_h(pairs[p].f, h.data(), acts[p].h[(size_t) t].data());
146        }
147    }
148    // the windows: per layer a list of (pair, blob, rows)
149    std::mt19937 wr(seed);
150    std::vector<std::vector<std::vector<Task>>> win((size_t) windows, std::vector<std::vector<Task>>((size_t) L));
151    const double q = 1.0 - 1.0 / rows_mean;   // rows - 1 ~ geometric: mean rows = 1 / (1 - q)
152    long long n_exp = 0, n_rows = 0;
153    for (int w = 0; w < windows; ++w)
154        for (int l = 0; l < L; ++l) {
155            std::poisson_distribution<int> pd(distinct);
156            const int ne = std::max(1, std::min(24, pd(wr)));
157            for (int e = 0; e < ne; ++e) {
158                int nt = 1;
159                std::uniform_real_distribution<double> u(0.0, 1.0);
160                while (nt < 4 && u(wr) < q) ++nt;
161                const int p = layer_pair[(size_t) l];
162                win[(size_t) w][(size_t) l].push_back({p, (size_t) (wr() % pairs[(size_t) p].E), nt});
163                ++n_exp;
164                n_rows += nt;
165            }
166        }
167    if (!dump_trace.empty()) {   // the synthetic windows in the STRATA_ROUTE_DUMP text form (every expert a miss), for replay_place.py
168        std::FILE* tf = std::fopen(dump_trace.c_str(), "w");
169        if (tf) {
170            for (int w = 0; w < windows; ++w)
171                for (int l = 0; l < L; ++l) {
172                    const auto& tk = win[(size_t) w][(size_t) l];
173                    int rows = 0;
174                    for (const Task& t : tk) rows += t.nt;
175                    std::fprintf(tf, "%d %d %d %d |", l, 3, (int) tk.size(), (int) tk.size());
176                    for (size_t i = 0; i < tk.size(); ++i) std::fprintf(tf, " %d:%d:0", (int) i, tk[i].nt);
177                    std::fputc(10, tf);
178                }
179            std::fclose(tf);
180        }
181    }
182    std::printf("kq_window_bench: %s, %d layers, %zu format pairs, %d windows, %d threads, %.0f MB arena per pair; %.2f experts/layer, %.2f rows/expert\n",
183                cpu::cpu_name().c_str(), L, pairs.size(), windows, threads, arena_mb, (double) n_exp / ((double) windows * L), (double) n_rows / (double) n_exp);
184    for (size_t p = 0; p < pairs.size(); ++p) {
185        int nl = 0;
186        for (int l = 0; l < L; ++l) nl += layer_pair[(size_t) l] == (int) p;
187        std::printf("  pair %s/%s: %d layers\n", ggml_type_name((ggml_type) pairs[p].f.gu_type), ggml_type_name((ggml_type) pairs[p].f.d_type), nl);
188    }
189    // the run: every thread takes tasks of a layer phase from a shared counter, a barrier joins the phases
190    Barrier bar(threads);
191    std::atomic<int> next{0};
192    std::atomic<int> cur_w{0};
193    std::vector<double> ms;
194    constexpr int kGuChunk = 160, kDnChunk = 640;   // rows per task: gate/up 640 rows in 4, down 2560 rows in 4
195    for (int rep = 0; rep < reps; ++rep) {
196        std::atomic<bool> stop{false};
197        double wall = 0;
198        auto work = [&](int tid) {
199            std::vector<float> ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH);
200            float* ff[kMaxT];
201            float* out[kMaxT];
202            for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
203            const auto t0 = std::chrono::steady_clock::now();
204            for (int w = 0; w < windows; ++w) {
205                for (int l = 0; l < L; ++l) {
206                    const auto& tasks = win[(size_t) w][(size_t) l];
207                    const int nT = (int) tasks.size();
208                    for (int phase = 0; phase < 2; ++phase) {
209                        if (tid == 0) next.store(0, std::memory_order_relaxed);
210                        bar.wait();
211                        const int chunk = phase == 0 ? kGuChunk : kDnChunk;
212                        const int rows = phase == 0 ? (int) kFF : (int) kH;
213                        const int per = (rows + chunk - 1) / chunk;
214                        for (;;) {
215                            const int k = next.fetch_add(1, std::memory_order_relaxed);
216                            if (k >= nT * per) break;
217                            const Task& tk = tasks[(size_t) (k / per)];
218                            const int r0 = (k % per) * chunk, r1 = std::min(rows, r0 + chunk);
219                            Pair& P = pairs[(size_t) tk.pair];
220                            const uint8_t* blob = P.blobs + tk.blob * P.f.bytes;
221                            const void* ap[kMaxT];
222                            const void* hp[kMaxT];
223                            for (int t = 0; t < tk.nt; ++t) { ap[t] = acts[(size_t) tk.pair].x[(size_t) t].data(); hp[t] = acts[(size_t) tk.pair].h[(size_t) t].data(); }
224                            if (phase == 0) cpu::native_gu_rows(P.f, blob, ap, tk.nt, ff, r0, r1);
225                            else cpu::native_down_rows(P.f, blob, hp, tk.nt, out, r0, r1);
226                        }
227                        bar.wait();
228                    }
229                }
230            }
231            if (tid == 0) wall = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
232            volatile float sink = outb[0] + ffb[0];
233            (void) sink;
234        };
235        std::vector<std::thread> th;
236        for (int t = 1; t < threads; ++t) th.emplace_back(work, t);
237        work(0);
238        for (auto& x : th) x.join();
239        ms.push_back(wall / windows);
240        std::printf("  rep %d: %.2f ms per window (%.3f ms per layer)\n", rep, wall / windows, wall / windows / L);
241    }
242    std::sort(ms.begin(), ms.end());
243    std::printf("median %.2f ms per window\n", ms[ms.size() / 2]);
244    (void) cur_w;
245    return 0;
246}