okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
17.9 KiB366 linesraw
1// src/kernels/cpu/nvfp4_avx512_parity.cpp - the AVX-512 and AVX2 NVFP4 rows against ggml-cpu's own dot product.
2//
3//     nvfp4_avx512_parity [pack/experts.bin]
4//
5// Parity: every row x every token of the multi-token kernel against ggml_vec_dot_nvfp4_q8_0 on the same Q8_0
6// activation. Both sum each 16-value sub-block exactly in integers; only the float additions are ordered differently,
7// so the check is a relative tolerance, not equality. Random blocks cover every code and a wide scale range; a real
8// expert (layer 0, expert 0 of a pack's experts.bin) covers the checkpoint's own distribution.
9// Also the down rows (n 640) and gate/up through silu with the blob tail's scales, 1..9 tokens (past one slice).
10// The AVX2 rows follow ggml's AVX2 path step for step, so for them every row must also be bit-equal (ggml-cpu built
11// with AVX2: STRATA_PORTABLE, or a native build). Each kernel is checked when this CPU runs it.
12// Speed: gate+up rows of one expert for 1..8 tokens, each way, as the CPU pool runs them.
13//
14//     nvfp4_avx512_parity --bw THREADS TOKENS [ggml|avx2]
15//     nvfp4_avx512_parity --expert pack/experts.bin [layer expert]
16//
17// --expert: one whole expert as decode runs it (Q8_0 input, gate/up + silu, Q8_0 of the hidden, down) against a
18// double-precision reference with the checkpoint's global scales, with s_down folded into up (the hidden becomes
19// ~1e-5 and its Q8_0 scale an FP16 subnormal) and with s_down applied to the output instead.
20//
21// DRAM rate: THREADS threads each run whole experts (gate/up through silu, then down) out of 4.2 GB of blobs -
22// 40x the L3 - for TOKENS tokens; GB/s of weights read. STRATA_NVFP4_PREFETCH sets the kernel's prefetch distance.
23#include "strata/kernels/cpu/expert_layout.hpp"
24#include "strata/kernels/cpu/nvfp4_avx2.hpp"
25#include "strata/kernels/cpu/nvfp4_avx512.hpp"
26
27#include "ggml.h"
28#include "ggml-cpu.h"
29
30#include <chrono>
31#include <cmath>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35#include <fstream>
36#include <random>
37#include <thread>
38#include <string>
39#include <vector>
40
41namespace {
42
43struct Kern {
44    const char* name;
45    void (*gu)(const uint8_t*, size_t, size_t, int, const void* const*, int, float* const*, int, int, float, float);
46    void (*rows)(const uint8_t*, size_t, int, const void* const*, int, float* const*, int, int, float);
47    bool exact;   // bit-equal to ggml's AVX2 dot
48};
49const Kern k512{"avx512", strata::kernels::cpu::nvfp4_512_gu_rows, strata::kernels::cpu::nvfp4_512_rows, false};
50const Kern k256{"avx2", strata::kernels::cpu::nvfp4_256_gu_rows, strata::kernels::cpu::nvfp4_256_rows, true};
51
52constexpr int N = 2560, ROWS = 1280, BLK = 36;   // an expert's gate+up: 1280 rows of 2560 values
53constexpr int FF = 640;                          // its down: 2560 rows of 640
54constexpr size_t ROW_BYTES = (size_t) N / 64 * BLK, D_ROW = (size_t) FF / 64 * BLK;
55constexpr size_t BLOB = (size_t) ROWS * ROW_BYTES + (size_t) N * D_ROW + 16;
56
57double now_ms() {
58    return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
59}
60
61struct Acts {
62    std::vector<std::vector<uint8_t>> q;
63    std::vector<const void*> p;
64    Acts(int n, int nt, std::mt19937& rng) : q(nt), p(nt) {
65        const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
66        std::normal_distribution<float> nd(0.f, 1.f);
67        std::vector<float> x(n);
68        for (int t = 0; t < nt; ++t) {
69            for (float& v : x) v = nd(rng) * (t + 1);                 // several magnitudes
70            q[t].resize(ggml_row_size(GGML_TYPE_Q8_0, n));
71            ta->from_float(x.data(), q[t].data(), n);
72            p[t] = q[t].data();
73        }
74    }
75};
76
77float ref_dot(const uint8_t* row, int n, const void* a) {
78    float s = 0.f;
79    ggml_get_type_traits_cpu(GGML_TYPE_NVFP4)->vec_dot(n, &s, 0, row, 0, a, 0, 1);
80    return s;
81}
82
83int report(const std::vector<std::vector<float>>& mine, const std::vector<std::vector<float>>& ref,
84           int nt, int rows, double& worst, int& differ) {
85    int bad = 0;
86    for (int t = 0; t < nt; ++t) {
87        double scale = 0;
88        for (int r = 0; r < rows; ++r) scale = std::fmax(scale, std::fabs(ref[t][r]));
89        for (int r = 0; r < rows; ++r) {
90            const double e = std::fabs((double) mine[t][r] - ref[t][r]) / (scale > 0 ? scale : 1);
91            worst = std::fmax(worst, e);
92            if (!(e <= 1e-5)) ++bad;
93            differ += std::memcmp(&mine[t][r], &ref[t][r], sizeof(float)) != 0;
94        }
95    }
96    return bad;
97}
98
99// a kernel that claims bit equality fails on any differing row
100int verdict(const Kern& k, const char* what, double worst, int rows, int nt, int bad, int differ) {
101    std::printf("%-7s %-36s worst |mine - ggml| / max|ggml| = %.2e over %d rows x 1..%d tokens, %d beyond 1e-5, "
102                "%d not bit-equal\n", k.name, what, worst, rows, nt, bad, differ);
103#if defined(STRATA_TEST_GGML_WITHOUT_AVX2)
104    // an older-CPU build (STRATA_ISA_FLOOR): ggml-cpu has no AVX2/FMA there, so its dot is not the AVX2 one these rows
105    // follow; only the 1e-5 check counts
106    if (k.exact)
107        std::printf("%-7s %-36s bit-equality not required (STRATA_ISA_FLOOR build: ggml-cpu without AVX2/FMA)\n",
108                    k.name, what);
109    return bad;
110#else
111    return bad + (k.exact ? differ : 0);
112#endif
113}
114
115// plain rows: `rows` rows of `n` values, `row_bytes` apart
116int check_rows(const Kern& k, const uint8_t* w, int n, size_t row_bytes, int rows, const char* what,
117               std::mt19937& rng) {
118    constexpr int NT = 9;                                              // past one slice: 9 = 5 + 4
119    Acts a(n, NT, rng);
120    std::vector<std::vector<float>> mine(NT, std::vector<float>(rows)), ref(NT, std::vector<float>(rows));
121    std::vector<float*> op(NT);
122    for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
123    int bad = 0, differ = 0;
124    double worst = 0;
125    for (int nt = 1; nt <= NT; ++nt) {
126        k.rows(w, row_bytes, n, a.p.data(), nt, op.data(), 0, rows, 1.f);
127        for (int t = 0; t < nt; ++t)
128            for (int r = 0; r < rows; ++r) ref[t][r] = ref_dot(w + (size_t) r * row_bytes, n, a.p[t]);
129        bad += report(mine, ref, nt, rows, worst, differ);
130    }
131    return verdict(k, what, worst, rows, NT, bad, differ);
132}
133
134// gate/up with the blob tail's scales: silu(s_gate g) * (s_up u), as native_gu_rows' ggml path computes it
135int check_gu(const Kern& k, const uint8_t* blob, std::mt19937& rng) {
136    constexpr int NT = 9, F = ROWS / 2;
137    float tail[4];
138    std::memcpy(tail, blob + BLOB - 16, sizeof tail);
139    const float sg = tail[0], su = tail[1];
140    const size_t up_off = (size_t) F * ROW_BYTES;
141    Acts a(N, NT, rng);
142    std::vector<std::vector<float>> mine(NT, std::vector<float>(F)), ref(NT, std::vector<float>(F));
143    std::vector<float*> op(NT);
144    for (int t = 0; t < NT; ++t) op[t] = mine[t].data();
145    int bad = 0, differ = 0;
146    double worst = 0;
147    for (int nt = 1; nt <= NT; ++nt) {
148        k.gu(blob, ROW_BYTES, up_off, N, a.p.data(), nt, op.data(), 0, F, sg, su);
149        for (int t = 0; t < nt; ++t)
150            for (int r = 0; r < F; ++r) {
151                const float g = ref_dot(blob + (size_t) r * ROW_BYTES, N, a.p[t]) * sg;
152                const float u = ref_dot(blob + up_off + (size_t) r * ROW_BYTES, N, a.p[t]) * su;
153                ref[t][r] = (g / (1.f + std::exp(-g))) * u;
154            }
155        bad += report(mine, ref, nt, F, worst, differ);
156    }
157    char what[96];
158    std::snprintf(what, sizeof what, "expert 0: silu(gate) * up (s %.2g/%.2g)", sg, su);
159    return verdict(k, what, worst, F, NT, bad, differ);
160}
161
162void speed(const std::vector<uint8_t>& w, std::mt19937& rng, bool has512, bool has256) {
163    const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
164    const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(tw->vec_dot_type);
165    const size_t act_bytes = ggml_row_size(tw->vec_dot_type, N);
166    std::normal_distribution<float> nd(0.f, 1.f);
167    std::vector<std::vector<uint8_t>> act(8, std::vector<uint8_t>(act_bytes));
168    std::vector<float> x(N), sink(8 * ROWS);
169    const void* ap[8];
170    float* op[8];
171    for (int t = 0; t < 8; ++t) {
172        for (float& v : x) v = nd(rng);
173        ta->from_float(x.data(), act[t].data(), N);
174        ap[t] = act[t].data();
175        op[t] = sink.data() + (size_t) t * ROWS;
176    }
177    std::printf("\n%-6s %10s %10s %8s %10s %8s   (one expert's gate+up, %d rows; best of 20)\n", "tokens",
178                "ggml ms", "avx512 ms", "speedup", "avx2 ms", "speedup", ROWS);
179    for (int nt = 1; nt <= 8; ++nt) {
180        double tg = 1e30, tm = 1e30, t2 = 1e30;
181        for (int rep = 0; rep < 20; ++rep) {
182            double t0 = now_ms();
183            for (int t = 0; t < nt; ++t)
184                for (int r = 0; r < ROWS; ++r) tw->vec_dot(N, &op[t][r], 0, w.data() + (size_t) r * ROW_BYTES, 0, ap[t], 0, 1);
185            tg = std::fmin(tg, now_ms() - t0);
186            if (has512) {
187                t0 = now_ms();
188                k512.rows(w.data(), ROW_BYTES, N, ap, nt, op, 0, ROWS, 1.f);
189                tm = std::fmin(tm, now_ms() - t0);
190            }
191            if (has256) {
192                t0 = now_ms();
193                k256.rows(w.data(), ROW_BYTES, N, ap, nt, op, 0, ROWS, 1.f);
194                t2 = std::fmin(t2, now_ms() - t0);
195            }
196        }
197        std::printf("%-6d %10.3f %10.3f %7.2fx %10.3f %7.2fx\n", nt, tg, has512 ? tm : 0.0, has512 ? tg / tm : 0.0,
198                    has256 ? t2 : 0.0, has256 ? tg / t2 : 0.0);
199    }
200}
201
202int bandwidth(int threads, int nt, bool use_ggml, const Kern& k) {
203    constexpr int E = 1536;
204    std::vector<uint8_t> blobs((size_t) E * BLOB);
205    {
206        std::vector<std::thread> fill;
207        for (int t = 0; t < 16; ++t)
208            fill.emplace_back([&, t] {
209                uint64_t x = 0x9E3779B97F4A7C15ull * (t + 1);
210                const size_t n8 = blobs.size() / 8, a = n8 * t / 16, b = n8 * (t + 1) / 16;
211                for (size_t i = a; i < b; ++i) {
212                    x ^= x << 13; x ^= x >> 7; x ^= x << 17;
213                    uint64_t v = x & 0x3F3F3F3F3F3F3F3Full;       // scale bytes stay finite; codes are any nibble
214                    std::memcpy(blobs.data() + 8 * i, &v, 8);
215                }
216            });
217        for (auto& f : fill) f.join();
218    }
219    std::mt19937 rng(7);
220    Acts ax(N, nt, rng), ah(FF, nt, rng);
221    const ggml_type_traits_cpu* tw = ggml_get_type_traits_cpu(GGML_TYPE_NVFP4);
222    double best = 1e30;
223    for (int pass = 0; pass < 3; ++pass) {
224        const double t0 = now_ms();
225        std::vector<std::thread> pool;
226        for (int w = 0; w < threads; ++w)
227            pool.emplace_back([&, w] {
228                std::vector<float> ff((size_t) nt * (ROWS / 2)), out((size_t) nt * N);
229                std::vector<float*> fp(nt), op(nt);
230                for (int t = 0; t < nt; ++t) { fp[t] = ff.data() + (size_t) t * (ROWS / 2); op[t] = out.data() + (size_t) t * N; }
231                for (int e = w; e < E; e += threads) {
232                    const uint8_t* b = blobs.data() + (size_t) e * BLOB;
233                    const size_t up_off = (size_t) (ROWS / 2) * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
234                    if (!use_ggml) {
235                        k.gu(b, ROW_BYTES, up_off, N, ax.p.data(), nt, fp.data(), 0, ROWS / 2, 1.f, 1.f);
236                        k.rows(b + d_off, D_ROW, FF, ah.p.data(), nt, op.data(), 0, N, 1.f);
237                    } else {
238                        for (int r = 0; r < ROWS / 2; ++r)
239                            for (int t = 0; t < nt; ++t) {
240                                float g = 0.f, u = 0.f;
241                                tw->vec_dot(N, &g, 0, b + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
242                                tw->vec_dot(N, &u, 0, b + up_off + (size_t) r * ROW_BYTES, 0, ax.p[t], 0, 1);
243                                fp[t][r] = (g / (1.f + std::exp(-g))) * u;
244                            }
245                        for (int r = 0; r < N; ++r)
246                            for (int t = 0; t < nt; ++t) tw->vec_dot(FF, &op[t][r], 0, b + d_off + (size_t) r * D_ROW, 0, ah.p[t], 0, 1);
247                    }
248                }
249            });
250        for (auto& p : pool) p.join();
251        best = std::fmin(best, now_ms() - t0);
252    }
253    const char* pf = std::getenv("STRATA_NVFP4_PREFETCH");
254    std::printf("%s  threads %d  tokens %d  prefetch %s: %.1f ms for %d experts -> %.1f GB/s, %.1f us/expert/thread\n",
255                use_ggml ? "ggml  " : k.name, threads, nt, use_ggml ? "-" : (pf ? pf : "2048"), best, E,
256                (double) E * BLOB / best / 1e6, best * 1000.0 * threads / E);
257    return 0;
258}
259
260int expert_e2e(const char* path, int layer, int e) {
261    constexpr size_t STRIDE = 2764816, LAYER = 512 * STRIDE;
262    std::vector<uint8_t> b(BLOB);
263    std::ifstream f(path, std::ios::binary);
264    f.seekg((std::streamoff) (layer * LAYER + (size_t) e * STRIDE));
265    if (!f.read((char*) b.data(), (std::streamsize) b.size())) { std::fprintf(stderr, "cannot read %s\n", path); return 2; }
266    float tail[4];
267    std::memcpy(tail, b.data() + BLOB - 16, sizeof tail);
268    const float sg = tail[0], s_up = tail[1], s_down = tail[2];
269    const int F = ROWS / 2;
270    const size_t up_off = (size_t) F * ROW_BYTES, d_off = (size_t) ROWS * ROW_BYTES;
271    const ggml_type_traits* tt = ggml_get_type_traits(GGML_TYPE_NVFP4);
272    std::vector<float> wg((size_t) F * N), wu((size_t) F * N), wd((size_t) N * FF);
273    tt->to_float(b.data(), wg.data(), (int64_t) F * N);
274    tt->to_float(b.data() + up_off, wu.data(), (int64_t) F * N);
275    tt->to_float(b.data() + d_off, wd.data(), (int64_t) N * FF);
276    const ggml_type_traits_cpu* q8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_0);
277    std::mt19937 rng(9);
278    std::normal_distribution<float> nd(0.f, 1.f);
279    double e_fold = 0, e_out = 0, den = 0, hmax_fold = 0;
280    for (int trial = 0; trial < 8; ++trial) {
281        std::vector<float> x(N);
282        for (float& v : x) v = nd(rng);
283        std::vector<double> h(F), y(N, 0.0);
284        for (int r = 0; r < F; ++r) {
285            double g = 0, u = 0;
286            for (int k = 0; k < N; ++k) { g += (double) wg[(size_t) r * N + k] * x[k]; u += (double) wu[(size_t) r * N + k] * x[k]; }
287            g *= sg; u *= s_up;
288            h[r] = g / (1 + std::exp(-g)) * u;
289        }
290        for (int r = 0; r < N; ++r) {
291            double s = 0;
292            for (int k = 0; k < F; ++k) s += (double) wd[(size_t) r * FF + k] * h[k];
293            y[r] = s * s_down;
294        }
295        std::vector<uint8_t> xq(ggml_row_size(GGML_TYPE_Q8_0, N)), hq(ggml_row_size(GGML_TYPE_Q8_0, FF));
296        q8->from_float(x.data(), xq.data(), N);
297        const void* ap[1] = {xq.data()};
298        std::vector<float> ff(F), out(N);
299        float* fp[1] = {ff.data()};
300        float* op[1] = {out.data()};
301        for (int mode = 0; mode < 2; ++mode) {             // 0: s_down folded into up; 1: s_down on the output
302            const Kern& k = strata::kernels::cpu::cpu_avx512_ok() ? k512 : k256;
303            k.gu(b.data(), ROW_BYTES, up_off, N, ap, 1, fp, 0, F, sg, mode == 0 ? s_up * s_down : s_up);
304            if (mode == 0) for (float v : ff) hmax_fold = std::fmax(hmax_fold, std::fabs(v));
305            q8->from_float(ff.data(), hq.data(), FF);
306            const void* hp[1] = {hq.data()};
307            k.rows(b.data() + d_off, D_ROW, FF, hp, 1, op, 0, N, 1.f);
308            double err = 0;
309            for (int r = 0; r < N; ++r) {
310                const double got = mode == 0 ? out[r] : (double) out[r] * s_down;
311                err += (got - y[r]) * (got - y[r]);
312            }
313            (mode == 0 ? e_fold : e_out) += err;
314        }
315        for (int r = 0; r < N; ++r) den += y[r] * y[r];
316    }
317    std::printf("layer %d expert %d: s_gate %.3g s_up %.3g s_down %.3g; folded hidden max |h| %.3g (Q8_0 d %.3g, FP16 "
318                "normal from 6.1e-05)\n", layer, e, sg, s_up, s_down, hmax_fold, hmax_fold / 127);
319    std::printf("  s_down folded into up : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_fold / den));
320    std::printf("  s_down on the output  : expert output rel. error %.3f%%\n", 100 * std::sqrt(e_out / den));
321    return 0;
322}
323
324}  // namespace
325
326int main(int argc, char** argv) {
327    ggml_cpu_init();
328    if (argc >= 3 && std::string(argv[1]) == "--expert")
329        return expert_e2e(argv[2], argc >= 4 ? std::atoi(argv[3]) : 0, argc >= 5 ? std::atoi(argv[4]) : 0);
330    const bool has512 = strata::kernels::cpu::cpu_avx512_ok(), has256 = strata::kernels::cpu::cpu_avx2_ok();
331    if (argc >= 4 && std::string(argv[1]) == "--bw") {
332        const std::string how = argc >= 5 ? argv[4] : "";
333        return bandwidth(std::atoi(argv[2]), std::atoi(argv[3]), how == "ggml", how == "avx2" || !has512 ? k256 : k512);
334    }
335    std::vector<const Kern*> ks;
336    if (has512) ks.push_back(&k512);
337    if (has256) ks.push_back(&k256);
338    std::mt19937 rng(20260929);
339    std::vector<uint8_t> w(BLOB);
340    // random blocks: every code, scales 0x20..0x5f (sign bit clear, never 0x7F), as ModelOpt writes them
341    std::uniform_int_distribution<int> byte(0, 255), sc(0x20, 0x5f);
342    for (size_t b = 0; b + BLK <= BLOB - 16; b += BLK) {
343        for (int s = 0; s < 4; ++s) w[b + s] = (uint8_t) sc(rng);
344        for (int q = 4; q < BLK; ++q) w[b + q] = (uint8_t) byte(rng);
345    }
346    int bad = 0;
347    for (const Kern* k : ks) {
348        bad += check_rows(*k, w.data(), N, ROW_BYTES, ROWS, "random blocks, n 2560", rng);
349        bad += check_rows(*k, w.data(), FF, D_ROW, N, "random blocks, n 640", rng);
350    }
351    if (argc >= 2) {                                                   // layer 0, expert 0 of the pack
352        std::ifstream f(argv[1], std::ios::binary);
353        if (!f.read((char*) w.data(), (std::streamsize) w.size())) {
354            std::fprintf(stderr, "cannot read %zu bytes of %s\n", w.size(), argv[1]);
355            return 2;
356        }
357        for (const Kern* k : ks) {
358            bad += check_rows(*k, w.data(), N, ROW_BYTES, ROWS, "expert 0: gate+up rows", rng);
359            bad += check_rows(*k, w.data() + (size_t) ROWS * ROW_BYTES, FF, D_ROW, N, "expert 0: down rows", rng);
360            bad += check_gu(*k, w.data(), rng);
361        }
362    }
363    speed(w, rng, has512, has256);
364    std::printf("\nRESULT: %s\n", bad ? "MISMATCH" : "parity OK");
365    return bad ? 1 : 0;
366}