okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
16.6 KiB383 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// tests/ds4_mx_bench.cpp - how fast does this CPU run DeepSeek-V4.1-Flash's MXFP4 experts on the CPU lane?
4//
5//   ds4_mx_bench [--threads 1,6,12] [--T 1,2,4,8,16] [--experts 16] [--per-layer 3] [--secs 0.4] [--pf 0]
6//                [--kernels float,avx2,avxvnni,avx512,avx512vnni,ggml,scalar] [--file PATH] [--make-file PATH]
7//
8// Experts of the real shape (gate / up 2304 rows x 5120, down 5120 x 2304, MXFP4: 18.8 MB each) with random codes in
9// anonymous memory (huge pages where the OS gives them), or in a file's mapping (--file: 4 KiB page-cache pages, as the
10// engine reads the GGUF; --make-file writes one).  A "layer" is --per-layer experts, as the lane runs them: the gate /
11// up rows of every expert in 64-row jobs on the pool, then (a barrier) their down rows; the layers walk through the
12// experts, so the weights come from RAM, not the cache.  Prints the weights' GB/s for each kernel x tokens x threads
13// (T tokens a call: each row read once for up to 8 of them), the int8 tiers' agreement with the scalar tier, and the
14// cost of the activation quant and of madvise(WILLNEED) on cached pages.
15#include "../../src/dsv41/ds4_gguf_cpu.hpp"
16#include "../../src/dsv41/ds4_pool.hpp"
17
18#if defined(STRATA_NATIVE_EXPERTS)
19#include "ggml-cpu.h"
20#include "ggml.h"
21#endif
22
23#include <algorithm>
24#include <chrono>
25#include <cmath>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29#include <random>
30#include <string>
31#include <vector>
32
33namespace gg = strata::ds4::gguf;
34namespace os = strata::ds4::os;
35using strata::ds4::Pool;
36
37namespace {
38
39constexpr int E = 5120, FF = 2304, RB = 64;
40const size_t kGr = (size_t) E / 32 * 17, kDr = (size_t) FF / 32 * 17;   // row bytes
41const size_t kMat = kGr * FF;                                           // gate (= up = down) bytes
42const size_t kExpert = 3 * kMat;
43
44double now_s() {
45    return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
46}
47std::vector<int> ints(const std::string& s) {
48    std::vector<int> v;
49    size_t a = 0;
50    while (a < s.size()) {
51        size_t b = s.find(',', a);
52        if (b == std::string::npos) b = s.size();
53        v.push_back(std::atoi(s.substr(a, b - a).c_str()));
54        a = b + 1;
55    }
56    return v;
57}
58std::vector<std::string> words(const std::string& s) {
59    std::vector<std::string> v;
60    size_t a = 0;
61    while (a < s.size()) {
62        size_t b = s.find(',', a);
63        if (b == std::string::npos) b = s.size();
64        v.push_back(s.substr(a, b - a));
65        a = b + 1;
66    }
67    return v;
68}
69
70// the logical CPUs, one of each core first, then their second threads (pinning order)
71std::vector<int> cpu_order() {
72    std::vector<int> first, rest;
73#if defined(_WIN32)
74    DWORD len = 0;
75    GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len);
76    std::vector<uint8_t> buf(len);
77    if (len > 0 && GetLogicalProcessorInformationEx(RelationProcessorCore,
78                                                    (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), &len)) {
79        for (size_t o = 0; o < buf.size();) {
80            auto* e = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) (buf.data() + o);
81            if (e->Processor.GroupCount > 0 && e->Processor.GroupMask[0].Group == 0) {
82                const KAFFINITY m = e->Processor.GroupMask[0].Mask;
83                bool f = true;
84                for (int b = 0; b < 64; ++b)
85                    if ((m >> b) & 1) {
86                        (f ? first : rest).push_back(b);
87                        f = false;
88                    }
89            }
90            o += e->Size;
91        }
92    }
93#else
94    for (int c = 0; c < 1024; ++c) {
95        std::FILE* f = std::fopen(("/sys/devices/system/cpu/cpu" + std::to_string(c) + "/topology/thread_siblings_list").c_str(), "r");
96        if (f == nullptr) break;
97        int s0 = -1;
98        if (std::fscanf(f, "%d", &s0) != 1) s0 = c;
99        std::fclose(f);
100        (s0 == c ? first : rest).push_back(c);
101    }
102#endif
103    if (first.empty())
104        for (unsigned c = 0; c < std::max(1u, std::thread::hardware_concurrency()); ++c) first.push_back((int) c);
105    std::sort(first.begin(), first.end());
106    std::sort(rest.begin(), rest.end());
107    first.insert(first.end(), rest.begin(), rest.end());
108    return first;
109}
110
111void fill_mx(uint8_t* p, size_t bytes, uint64_t seed) {   // random MXFP4 blocks, scales 2^-14 .. 2^-6 as weights'
112    std::mt19937_64 rng(seed);
113    for (size_t b = 0; b + 17 <= bytes; b += 17) {
114        const uint64_t r = rng(), s = rng();
115        p[b] = (uint8_t) (114 + r % 9);
116        std::memcpy(p + b + 1, &r, 8);
117        std::memcpy(p + b + 9, &s, 8);
118    }
119}
120
121enum Kern { kFloat = 100, kGgml = 101 };
122int kern_id(const std::string& s) {
123    if (s == "float") return kFloat;
124    if (s == "ggml") return kGgml;
125    for (int t = 0; t < gg::kMxTiers; ++t)
126        if (s == gg::mx_tier_name(t)) return t;
127    return -1;
128}
129
130struct Acts {   // T tokens' activations of E and FF values in every form a kernel takes
131    int T = 0;
132    std::vector<float> xf, hf;                  // F32 (rounded as q8_round) [T][E], [T][FF]
133    std::vector<uint8_t> xq, hq;                // mx_quant's [T][2E], [T][2FF]
134    std::vector<uint8_t> x8, h8;                // ggml's block_q8_0 [T][E / 32 * 34]
135    void make(int t, uint64_t seed) {
136        T = t;
137        std::mt19937 rng((unsigned) seed);
138        std::normal_distribution<float> nd(0.0f, 1.0f);
139        xf.resize((size_t) T * E);
140        hf.resize((size_t) T * FF);
141        for (auto& v : xf) v = nd(rng);
142        for (auto& v : hf) v = 0.05f * nd(rng);
143        xq.resize((size_t) T * gg::mx_act_bytes(E));
144        hq.resize((size_t) T * gg::mx_act_bytes(FF));
145        x8.resize((size_t) T * E / 32 * 34);
146        h8.resize((size_t) T * FF / 32 * 34);
147        for (int i = 0; i < T; ++i) {
148            gg::mx_quant(&xf[(size_t) i * E], E, &xq[(size_t) i * gg::mx_act_bytes(E)]);
149            gg::mx_quant(&hf[(size_t) i * FF], FF, &hq[(size_t) i * gg::mx_act_bytes(FF)]);
150#if defined(STRATA_NATIVE_EXPERTS)
151            const auto* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
152            q8->from_float(&xf[(size_t) i * E], &x8[(size_t) i * E / 32 * 34], E);
153            q8->from_float(&hf[(size_t) i * FF], &h8[(size_t) i * FF / 32 * 34], FF);
154#endif
155            gg::q8_round(&xf[(size_t) i * E], E, &xf[(size_t) i * E]);
156            gg::q8_round(&hf[(size_t) i * FF], FF, &hf[(size_t) i * FF]);
157        }
158    }
159};
160
161// rows [r0, r1) of one matrix (k values a row) against the T activations, kernel `kern`
162void rows(int kern, const uint8_t* w, size_t rb, int k, int r0, int r1, const Acts& a, float* const* y, int pf) {
163    const bool down = k == FF;
164    if (kern == kFloat) {
165        for (int i0 = 0; i0 < a.T; i0 += 8) {
166            const float* xp[8];
167            const int n = std::min(8, a.T - i0);
168            for (int i = 0; i < n; ++i) xp[i] = (down ? a.hf.data() : a.xf.data()) + (size_t) (i0 + i) * k;
169            gg::mx_cpu_rows(w, rb, k, r0, r1, xp, n, y + i0);
170        }
171        return;
172    }
173    if (kern == kGgml) {
174#if defined(STRATA_NATIVE_EXPERTS)
175        static const ggml_vec_dot_t dot = ggml_get_type_traits_cpu(GGML_TYPE_MXFP4)->vec_dot;
176        const uint8_t* x8 = down ? a.h8.data() : a.x8.data();
177        for (int r = r0; r < r1; ++r)
178            for (int i = 0; i < a.T; ++i) dot(k, &y[i][r - r0], 0, w + (size_t) r * rb, 0, x8 + (size_t) i * k / 32 * 34, 0, 1);
179#endif
180        return;
181    }
182    const void* ap[16];
183    for (int i = 0; i < a.T; ++i) ap[i] = (down ? a.hq.data() : a.xq.data()) + (size_t) i * gg::mx_act_bytes(k);
184    gg::mx_rows_tier(kern, w, rb, k, r0, r1, ap, a.T, y, pf);
185}
186
187struct Bench {
188    const uint8_t* mem = nullptr;
189    int n_exp = 16, per_layer = 3;
190    double secs = 0.4;
191    // GB/s of weights with `pool` (its size the threads), kernel kern, the T tokens of a
192    double run(Pool& pool, int kern, const Acts& a, int pf) {
193        const int GB = FF / RB, DB = E / RB;
194        std::vector<std::vector<float>> ys((size_t) pool.size() * 64);
195        int layer = 0;
196        size_t bytes = 0;
197        auto one_layer = [&] {
198            const int e0 = (layer * per_layer) % n_exp;
199            std::function<void(int)> fgu = [&](int j) {
200                const int e = (e0 + j / (2 * GB)) % n_exp, m = (j / GB) % 2, b = j % GB;
201                float yb[16][RB];
202                float* yp[16];
203                for (int i = 0; i < a.T; ++i) yp[i] = yb[i];
204                rows(kern, mem + (size_t) e * kExpert + (size_t) m * kMat, kGr, E, b * RB, b * RB + RB, a, yp, pf);
205            };
206            pool.run(per_layer * 2 * GB, fgu);
207            std::function<void(int)> fd = [&](int j) {
208                const int e = (e0 + j / DB) % n_exp, b = j % DB;
209                float yb[16][RB];
210                float* yp[16];
211                for (int i = 0; i < a.T; ++i) yp[i] = yb[i];
212                rows(kern, mem + (size_t) e * kExpert + 2 * kMat, kDr, FF, b * RB, b * RB + RB, a, yp, pf);
213            };
214            pool.run(per_layer * DB, fd);
215            bytes += (size_t) per_layer * kExpert;
216            ++layer;
217        };
218        for (int w = 0; w < 2; ++w) one_layer();   // (warm: the threads, the code)
219        bytes = 0;
220        const double t0 = now_s();
221        double t = t0;
222        while (t - t0 < secs) {
223            one_layer();
224            t = now_s();
225        }
226        return bytes / (t - t0) / 1e9;
227    }
228};
229
230
231}  // namespace
232
233int main(int argc, char** argv) {
234    std::vector<int> threads = {1}, Ts = {1, 2, 4, 8, 16}, pfs = {0};
235    std::vector<std::string> kerns = {"float", "avx2", "avxvnni", "avx512", "avx512vnni", "ggml"};
236    std::string file, make_file;
237    Bench B;
238    for (int i = 1; i + 1 < argc; i += 2) {
239        const std::string a = argv[i], v = argv[i + 1];
240        if (a == "--threads") threads = ints(v);
241        else if (a == "--T") Ts = ints(v);
242        else if (a == "--pf") pfs = ints(v);
243        else if (a == "--experts") B.n_exp = std::atoi(v.c_str());
244        else if (a == "--per-layer") B.per_layer = std::atoi(v.c_str());
245        else if (a == "--secs") B.secs = std::atof(v.c_str());
246        else if (a == "--kernels") kerns = words(v);
247        else if (a == "--file") file = v;
248        else if (a == "--make-file") make_file = v;
249    }
250#if defined(STRATA_NATIVE_EXPERTS)
251    ggml_cpu_init();
252#endif
253    const size_t total = (size_t) B.n_exp * kExpert;
254    if (!make_file.empty()) {
255        std::FILE* f = std::fopen(make_file.c_str(), "wb");
256        if (f == nullptr) return 1;
257        std::vector<uint8_t> buf(kExpert);
258        for (int e = 0; e < B.n_exp; ++e) {
259            fill_mx(buf.data(), buf.size(), 1000 + (uint64_t) e);
260            std::fwrite(buf.data(), 1, buf.size(), f);
261        }
262        std::fclose(f);
263        std::printf("wrote %s: %d experts, %.0f MB\n", make_file.c_str(), B.n_exp, total / 1e6);
264        return 0;
265    }
266    os::fd_t fd = os::kBadFd;
267    if (!file.empty()) {
268        fd = os::open_ro(file);
269        if (fd == os::kBadFd || os::file_size(fd) < total) {
270            std::fprintf(stderr, "%s: cannot open, or smaller than %d experts\n", file.c_str(), B.n_exp);
271            return 1;
272        }
273        B.mem = (const uint8_t*) os::map_ro(fd, total);
274        volatile uint64_t s = 0;   // (into the page cache and the mapping)
275        for (size_t o = 0; o < total; o += 4096) s += B.mem[o];
276    } else {
277        uint8_t* m = (uint8_t*) os::anon_alloc(total, -1, 1);
278        if (m == nullptr) return 1;
279        for (int e = 0; e < B.n_exp; ++e) fill_mx(m + (size_t) e * kExpert, kExpert, 1000 + (uint64_t) e);
280        B.mem = m;
281    }
282    std::printf("CPU tiers:");
283    for (int t = 0; t < gg::kMxTiers; ++t)
284        if (gg::mx_tier_ok(t)) std::printf(" %s", gg::mx_tier_name(t));
285    std::printf(" (mx_rows takes %s: %s); weights %s, %d experts (%.0f MB), %d a layer\n", gg::mx_tier_name(gg::mx_tier()),
286                gg::mx_tier_report(), file.empty() ? "anonymous memory" : file.c_str(), B.n_exp, total / 1e6, B.per_layer);
287
288    // ---- the int8 tiers against the scalar tier, and the old F32 path against both (T = 3, 64 rows of each kind)
289    {
290        Acts a;
291        a.make(3, 7);
292        for (int down = 0; down < 2; ++down) {
293            const int k = down ? FF : E;
294            const size_t rb = down ? kDr : kGr;
295            const uint8_t* w = B.mem + (down ? 2 * kMat : 0);
296            float ref[3][RB], got[3][RB];
297            float* rp[3] = {ref[0], ref[1], ref[2]};
298            float* gp[3] = {got[0], got[1], got[2]};
299            rows(gg::kMxScalar, w, rb, k, 0, RB, a, rp, 0);
300            for (int t = 0; t < gg::kMxTiers + 1; ++t) {
301                const int kern = t < gg::kMxTiers ? t : kFloat;
302                if (kern != kFloat && (kern == gg::kMxScalar || !gg::mx_tier_ok(kern))) continue;
303                rows(kern, w, rb, k, 0, RB, a, gp, 0);
304                double md = 0, mx = 0;
305                for (int i = 0; i < 3; ++i)
306                    for (int r = 0; r < RB; ++r) {
307                        md = std::max(md, (double) std::fabs(got[i][r] - ref[i][r]));
308                        mx = std::max(mx, (double) std::fabs(ref[i][r]));
309                    }
310                std::printf("  %-6s %-10s vs scalar: max |diff| %.3g (max |y| %.3g, rel %.2g)%s\n", down ? "down" : "gate",
311                            kern == kFloat ? "float" : gg::mx_tier_name(kern), md, mx, md / std::max(mx, 1e-30),
312                            kern != kFloat && std::memcmp(got, ref, sizeof got) == 0 ? "  bit-identical" : "");
313            }
314        }
315        // the quant's two forms: the same bytes
316        std::vector<uint8_t> q1(gg::mx_act_bytes(E)), q2(gg::mx_act_bytes(E));
317        gg::mx_quant_blocks(a.xf.data(), 0, E / 32, q1.data(), E);
318        gg::mx_quant_blocks_scalar(a.xf.data(), 0, E / 32, q2.data(), E);
319        std::printf("  quant: vector vs scalar bytes %s\n", q1 == q2 ? "identical" : "DIFFER");
320    }
321
322    // ---- the quant and madvise costs
323    {
324        std::vector<float> x(E), r(E);
325        std::mt19937 rng(3);
326        std::normal_distribution<float> nd;
327        for (auto& v : x) v = nd(rng);
328        std::vector<uint8_t> q(gg::mx_act_bytes(E));
329        const int N = 20000;
330        double t0 = now_s();
331        for (int i = 0; i < N; ++i) gg::mx_quant(x.data(), E, q.data());
332        const double tq = (now_s() - t0) / N;
333        t0 = now_s();
334        for (int i = 0; i < N / 10; ++i) gg::q8_round(x.data(), E, r.data());
335        const double tr = (now_s() - t0) / (N / 10);
336        std::printf("activation of %d: mx_quant %.2f us, q8_round (old, scalar) %.2f us\n", E, tq * 1e6, tr * 1e6);
337        if (!file.empty()) {
338            t0 = now_s();
339            int n = 0;
340            for (int e = 0; e < B.n_exp; ++e)
341                for (int m = 0; m < 3; ++m, ++n)
342                    os::prefetch({{B.mem + (size_t) e * kExpert + (size_t) m * kMat, kMat}});
343            std::printf("madvise(WILLNEED) of a cached expert matrix (%.1f MB): %.1f us\n", kMat / 1e6,
344                        (now_s() - t0) / n * 1e6);
345            t0 = now_s();
346            int nres = 0;
347            for (int rep = 0; rep < 10; ++rep)
348                for (int e = 0; e < B.n_exp; ++e)
349                    for (int m = 0; m < 3; ++m)
350                        nres += os::resident_sampled(B.mem + (size_t) e * kExpert + (size_t) m * kMat, kMat);
351            std::printf("os::resident_sampled (8 pages) of an expert matrix: %.2f us (%d of %d resident)\n",
352                        (now_s() - t0) / (10 * n) * 1e6, nres / 10, n);
353        }
354    }
355
356    // ---- the table
357    const std::vector<int> order = cpu_order();
358    std::printf("\n%-11s %3s %4s %5s %9s %10s\n", "kernel", "T", "thr", "pf", "GB/s", "GB/s/thr");
359    for (int nt : threads) {
360        nt = std::max(1, std::min(nt, (int) order.size()));
361        Pool pool(nt - 1, std::vector<int>(order.begin() + 1, order.begin() + nt), 20000);
362        os::pin_self(order[0]);
363        for (const std::string& ks : kerns) {
364            const int kern = kern_id(ks);
365            if (kern < 0 || (kern < gg::kMxTiers && !gg::mx_tier_ok(kern))) continue;
366#if !defined(STRATA_NATIVE_EXPERTS)
367            if (kern == kGgml) continue;
368#endif
369            for (int T : Ts) {
370                if (T < 1 || T > 16) continue;
371                Acts a;
372                a.make(T, 11 + (uint64_t) T);
373                for (int pf : pfs) {
374                    if (pf != 0 && (kern == kFloat || kern == kGgml || kern == gg::kMxScalar)) continue;
375                    const double g = B.run(pool, kern, a, pf);
376                    std::printf("%-11s %3d %4d %5d %9.2f %10.2f\n", ks.c_str(), T, nt, pf, g, g / nt);
377                    std::fflush(stdout);
378                }
379            }
380        }
381    }
382    return 0;
383}