okami.mom/strata

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

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

main
39.4 KiB610 linesraw
1// Strata. The i-quant routed experts of the DeepSeek-V4.1 path (ds4_iq.cu on the device, ds4_iq_cpu.cpp on the CPU lane)
2// against ggml's own decode of the same bytes plus a double reference: the token path (gate/up, down), the window path
3// (grouped entries), the prompt sets (gate/up and down), and the CPU lane on the same experts.  Random legal blocks: any
4// bit pattern with a sane F16 scale is one.  This is the H2 gate for a new type (IQ2_XS first): the kernel's integer sums
5// must equal ggml's weights times the same activations.
6//   iq_expert_test [--type 16,17,18,21,22,23,29] [--bench] [--iq256 0|1]
7#include "../../src/dsv41/ds4_gguf_cpu.hpp"
8#include "../../src/dsv41/ds4_iq.cuh"
9
10#include "strata/dsv41/hip_or_cuda.h"   // HIP names on a HIP build, the CUDA runtime otherwise
11
12#include "ggml.h"   // ggml_get_type_traits(type)->to_float: ggml's decode of the same blocks
13
14#include <algorithm>
15#include <cmath>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19#include <random>
20#include <string>
21#include <vector>
22
23namespace iq = strata::ds4::gguf::iq;
24namespace gg = strata::ds4::gguf;
25#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0)
26
27template <typename T> static T* up(const std::vector<T>& v) {
28    T* d; CK(hipMalloc(&d, std::max<size_t>(1, v.size() * sizeof(T)))); CK(hipMemcpy(d, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); return d;
29}
30template <typename T> static std::vector<T> down_(const T* d, size_t n) {
31    std::vector<T> v(n); CK(hipMemcpy(v.data(), d, n * sizeof(T), hipMemcpyDeviceToHost)); return v;
32}
33static float h2f(uint16_t h) {
34    const int s = h >> 15, e = (h >> 10) & 31, m = h & 1023;
35    float f = e == 0 ? std::ldexp((float) m, -24) : std::ldexp(1.0f + m / 1024.0f, e - 15);
36    return s ? -f : f;
37}
38static uint16_t f2h(float f) {   // round to nearest even, normal range
39    uint32_t u; std::memcpy(&u, &f, 4);
40    const uint32_t s = (u >> 16) & 0x8000u; int e = (int) ((u >> 23) & 0xff) - 127 + 15; uint32_t m = u & 0x7fffffu;
41    uint32_t hm = m >> 13; const uint32_t rem = m & 0x1fffu;
42    uint32_t v = ((uint32_t) e << 10) | hm;
43    if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
44    return (uint16_t) (s | v);
45}
46
47struct Q8 { std::vector<int8_t> q; std::vector<float> d; std::vector<float> xhat; };
48// the engine's q8_quant: sc = max|x| / 127 per 32, q = round-half-even(x / sc)
49static Q8 quant(const float* x, int k) {
50    Q8 r; r.q.resize(k); r.d.resize(k / 32); r.xhat.resize(k);
51    for (int b = 0; b < k / 32; ++b) {
52        float am = 0; for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(x[b * 32 + j]));
53        const float sc = am / 127.0f; r.d[b] = sc;
54        for (int j = 0; j < 32; ++j) { const int q = am > 0 ? (int) std::nearbyint(x[b * 32 + j] / sc) : 0; r.q[b * 32 + j] = (int8_t) q; r.xhat[b * 32 + j] = (float) q * sc; }
55    }
56    return r;
57}
58static double swiglu(double g, double u, double lim) {
59    if (lim > 0) { g = std::min(g, lim); u = std::min(std::max(u, -lim), lim); }
60    return g / (1.0 + std::exp(-g)) * u;
61}
62static double dotd(const float* w, const float* x, int k, double* sabs = nullptr) {
63    double s = 0, sa = 0; for (int i = 0; i < k; ++i) { const double t = (double) w[i] * x[i]; s += t; sa += std::fabs(t); } if (sabs) *sabs = sa; return s;
64}
65// an activation buffer of a ggml type (Q8_K for the i-quant rows) decoded by ggml itself
66static std::vector<float> act_values(int type, const void* act, int k) {
67    std::vector<float> v((size_t) k);
68    if (type == 15) {   // Q8_K: float d, int8 qs[256], int16 bsums[16] - no to_float (an intermediate type)
69        const int nb = k / 256;
70        const size_t bs = ggml_row_size((ggml_type) type, k) / (size_t) nb;
71        for (int b = 0; b < nb; ++b) {
72            const uint8_t* p = (const uint8_t*) act + (size_t) b * bs;
73            float d; std::memcpy(&d, p, 4);
74            const int8_t* qs = (const int8_t*) (p + 4);
75            for (int j = 0; j < 256; ++j) v[(size_t) b * 256 + j] = d * (float) qs[j];
76        }
77        return v;
78    }
79    const ggml_type_traits* t = ggml_get_type_traits((ggml_type) type);
80    if (t == nullptr || t->to_float == nullptr) { std::printf("no to_float for activation type %d\n", type); std::exit(2); }
81    t->to_float(act, v.data(), k);
82    return v;
83}
84
85struct Mat { std::vector<uint8_t> bytes; std::vector<float> w; int rows = 0, k = 0; };
86// random legal blocks of `type` for a rows x k matrix, decoded by ggml itself
87static Mat make_mat(std::mt19937_64& rng, int type, int rows, int k) {
88    Mat m; m.rows = rows; m.k = k;
89    const int bv = iq::block_values(type), bb = iq::block_bytes(type);
90    const size_t nblk = (size_t) rows * (k / bv);
91    m.bytes.resize(nblk * (size_t) bb);
92    for (auto& b : m.bytes) b = (uint8_t) rng();
93    for (size_t b = 0; b < nblk; ++b) {   // a sane F16 scale: at offset 0 (every type here but IQ1_M has d there)
94        const uint16_t d = f2h(0.02f + 0.0002f * (float) (rng() % 600));
95        uint8_t* p = &m.bytes[b * (size_t) bb];
96        if (type == 29) {   // block_iq1_m has no d field: its F16 scale is the top nibbles of its four u16 scales
97            p[49] = (uint8_t) ((p[49] & 0x0f) | ((d & 0x000f) << 4));
98            p[51] = (uint8_t) ((p[51] & 0x0f) | (d & 0x00f0));
99            p[53] = (uint8_t) ((p[53] & 0x0f) | ((d & 0x0f00) >> 4));
100            p[55] = (uint8_t) ((p[55] & 0x0f) | ((d & 0xf000) >> 8));
101        } else {
102            std::memcpy(p, &d, 2);
103        }
104    }
105    m.w.resize((size_t) rows * k);
106    const ggml_type_traits* tr = ggml_get_type_traits((ggml_type) type);
107    if (tr == nullptr || tr->to_float == nullptr) { std::printf("ggml has no to_float for type %d\n", type); std::exit(2); }
108    const size_t rb = (size_t) (k / bv) * (size_t) bb;
109    for (int r = 0; r < rows; ++r) tr->to_float(&m.bytes[(size_t) r * rb], &m.w[(size_t) r * k], k);
110    return m;
111}
112
113// one decode token of the DeepSeek shape (n_embd 5120, n_ff 2304, top-6 experts): gate/up + down launches, per-layer time
114static void bench(int type) {
115    const int E = 5120, FF = 2304, NE = 6;
116    const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
117    auto al = [](size_t n) { return (n + 255) / 256 * 256; };
118    const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
119    std::mt19937_64 rng(5);
120    std::vector<uint8_t> one(blob);
121    for (auto& b : one) b = (uint8_t) rng();
122    std::vector<unsigned long long> plan(NE);
123    for (int e = 0; e < NE; ++e) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); plan[e] = (unsigned long long) d; }
124    std::vector<int8_t> xq(E, 3), hq((size_t) NE * FF, 3); std::vector<float> xd(E / 32, 0.01f), hd((size_t) NE * FF / 32, 0.01f);
125    iq::Args a{};
126    a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
127    for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
128    float *dh, *dp; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMalloc(&dp, (size_t) NE * E * 4)); a.h = dh; a.part = dp;
129    hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
130    for (int rep = 0; rep < 5; ++rep) { iq::gate_up(a, NE, 1, 0); iq::down(a, NE, 1, 0); }
131    CK(hipDeviceSynchronize());
132    float ms_gu = 0, ms_dn = 0;
133    for (int part = 0; part < 2; ++part) {
134        hipEventRecord(e0);
135        for (int rep = 0; rep < 100; ++rep) { if (part == 0) iq::gate_up(a, NE, 1, 0); else iq::down(a, NE, 1, 0); }
136        hipEventRecord(e1); hipEventSynchronize(e1);
137        float ms; hipEventElapsedTime(&ms, e0, e1);
138        (part == 0 ? ms_gu : ms_dn) = ms / 100;
139    }
140    const double bytes = (double) NE * blob;
141    std::printf("bench %-7s 6 experts x 40 layers: gate/up %.0f us, down %.0f us, layer %.0f us -> %.0f GB/s, %.2f Tw/s, 40 layers %.1f ms/token\n",
142                iq::name(type), ms_gu * 1e3, ms_dn * 1e3, (ms_gu + ms_dn) * 1e3,
143                bytes / ((ms_gu + ms_dn) * 1e-3) / 1e9,
144                (double) NE * 3 * FF * E / ((ms_gu + ms_dn) * 1e-3) / 1e12, 40.0 * (ms_gu + ms_dn));
145}
146
147
148// --dump F / --cmp F: every device output of a run as raw bits, to a file / against one (a kernel change that keeps the sums
149// exact and the float order must leave all of them identical)
150static FILE* g_dump = nullptr; static FILE* g_cmp = nullptr; static long g_cmp_bad = 0, g_cmp_n = 0;
151static void bits(const char* what, int type, const void* p, size_t bytes) {
152    if (!g_dump && !g_cmp) return;
153    if (g_dump) { std::fwrite(p, 1, bytes, g_dump); return; }
154    std::vector<uint8_t> ref(bytes);
155    if (std::fread(ref.data(), 1, bytes, g_cmp) != bytes) { std::printf("cmp: golden file too short at %s %s\n", iq::name(type), what); ++g_cmp_bad; return; }
156    ++g_cmp_n;
157    if (std::memcmp(ref.data(), p, bytes) != 0) {
158        size_t bad = 0, first = 0; for (size_t i = 0; i < bytes; ++i) if (ref[i] != ((const uint8_t*) p)[i]) { if (!bad) first = i; ++bad; }
159        std::printf("%-7s %-22s BITS DIFFER: %zu of %zu bytes (first at %zu)\n", iq::name(type), what, bad, bytes, first);
160        ++g_cmp_bad;
161    }
162}
163// the real shapes (n_embd 5120, n_ff 2304): the plan path (6 groups of one entry) and the grouped path (windows of 3 and 2)
164static void real_shape_bits(int type) {
165    std::mt19937_64 rng(1000 + type);   // (its own stream: the main loop's random experts are the same with or without this)
166    const int E = 5120, FF = 2304, NG = 2, NEnt = 12;
167    const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
168    auto al = [](size_t n) { return (n + 255) / 256 * 256; };
169    const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
170    std::vector<uint8_t> hb((size_t) NG * blob);
171    for (auto& b : hb) b = (uint8_t) rng();
172    for (size_t b = 0; b < hb.size() / (size_t) iq::block_bytes(type); ++b) {   // sane F16 scales (the same placement as make_mat)
173        const uint16_t d = f2h(0.02f + 0.0002f * (float) (rng() % 600));
174        uint8_t* p = &hb[b * (size_t) iq::block_bytes(type)];
175        if (type == 29) { p[49] = (uint8_t) ((p[49] & 0x0f) | ((d & 0x000f) << 4)); p[51] = (uint8_t) ((p[51] & 0x0f) | (d & 0x00f0)); p[53] = (uint8_t) ((p[53] & 0x0f) | ((d & 0x0f00) >> 4)); p[55] = (uint8_t) ((p[55] & 0x0f) | ((d & 0xf000) >> 8)); }
176        else std::memcpy(p, &d, 2);
177    }
178    uint8_t* dblob = up(hb);
179    std::vector<int8_t> xq(2 * E), hq((size_t) NEnt * FF); std::vector<float> xd(2 * E / 32), hd((size_t) NEnt * FF / 32);
180    for (auto& v : xq) v = (int8_t) ((int) (rng() % 255) - 127);
181    for (auto& v : hq) v = (int8_t) ((int) (rng() % 255) - 127);
182    for (auto& v : xd) v = 0.002f + 0.0001f * (float) (rng() % 100);
183    for (auto& v : hd) v = 0.002f + 0.0001f * (float) (rng() % 100);
184    iq::Args a{};
185    a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
186    for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
187    float *dh, *dp; CK(hipMalloc(&dh, (size_t) NEnt * FF * 4)); CK(hipMalloc(&dp, (size_t) NEnt * E * 4)); a.h = dh; a.part = dp;
188    std::vector<unsigned long long> plan = {(unsigned long long) dblob, (unsigned long long) (dblob + blob), 0ull, (unsigned long long) dblob};
189    a.plan_ptr = up(plan);
190    CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
191    if (!iq::gate_up(a, 4, 1, 0) || !iq::down(a, 4, 1, 0)) { std::printf("real shape: refused\n"); return; }
192    CK(hipDeviceSynchronize());
193    { auto h = down_(dh, (size_t) NEnt * FF); bits("real plan h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real plan part", type, p.data(), p.size() * 4); }
194    std::vector<unsigned long long> gp = {(unsigned long long) dblob, (unsigned long long) (dblob + blob)};
195    std::vector<int> gs = {0, 3, 5}, ge = {0, 1, 2, 3, 4}, ng = {NG};
196    a.plan_ptr = nullptr; a.grp_ptr = up(gp); a.grp_start = up(gs); a.grp_ent = up(ge); a.n_groups = up(ng);
197    CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
198    if (!iq::gate_up(a, NG, 3, 0) || !iq::down(a, NG, 3, 0)) { std::printf("real shape grouped: refused\n"); return; }
199    CK(hipDeviceSynchronize());
200    { auto h = down_(dh, (size_t) NEnt * FF); bits("real grp h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real grp part", type, p.data(), p.size() * 4); }
201    // more windows: a bound of 7 groups with 3 live (dynamic count), 5/1/3 entries (ne_max 5: the 8-entry kernels), then 9 groups of
202    // one entry with 4 live; entries index the h/hq rows, their input row is entry >> 3
203    {
204        std::vector<unsigned long long> gp2 = {(unsigned long long) dblob, (unsigned long long) (dblob + blob), (unsigned long long) dblob, 0ull, 0ull, 0ull, 0ull, 0ull, 0ull};
205        std::vector<int> gs2 = {0, 5, 6, 9, 9, 9, 9, 9, 9, 9}, ge2 = {3, 1, 4, 0, 2, 7, 5, 6, 8, 11, 10, 9}, ng2 = {3};
206        a.grp_ptr = up(gp2); a.grp_start = up(gs2); a.grp_ent = up(ge2); a.n_groups = up(ng2);
207        CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
208        if (!iq::gate_up(a, 7, 5, 0) || !iq::down(a, 7, 5, 0)) { std::printf("real shape window 2: refused\n"); return; }
209        CK(hipDeviceSynchronize());
210        { auto h = down_(dh, (size_t) NEnt * FF); bits("real win2 h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real win2 part", type, p.data(), p.size() * 4); }
211        std::vector<int> gs3 = {0, 1, 2, 3, 4, 4, 4, 4, 4, 4}, ng3 = {4};
212        std::vector<unsigned long long> gp3 = {(unsigned long long) (dblob + blob), (unsigned long long) dblob, (unsigned long long) (dblob + blob), (unsigned long long) dblob, 0ull, 0ull, 0ull, 0ull, 0ull};
213        a.grp_ptr = up(gp3); a.grp_start = up(gs3); a.n_groups = up(ng3);
214        CK(hipMemset(dh, 0, (size_t) NEnt * FF * 4)); CK(hipMemset(dp, 0, (size_t) NEnt * E * 4));
215        if (!iq::gate_up(a, 9, 1, 0) || !iq::down(a, 9, 1, 0)) { std::printf("real shape window 3: refused\n"); return; }
216        CK(hipDeviceSynchronize());
217        { auto h = down_(dh, (size_t) NEnt * FF); bits("real win3 h", type, h.data(), h.size() * 4); auto p = down_(dp, (size_t) NEnt * E); bits("real win3 part", type, p.data(), p.size() * 4); }
218    }
219    CK(hipFree(dblob));
220}
221
222// the same DeepSeek decode token over a working set far past L2 (>= 640 MiB of distinct expert blobs, rotated launch by launch),
223// so the rate is DRAM's, not L2's: gate/up and down timed apart; ne = entries a group (1: the decode token)
224static void bench_big(int type, int mib) {
225    const int E = 5120, FF = 2304, NE = 6;
226    const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
227    auto al = [](size_t n) { return (n + 255) / 256 * 256; };
228    const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
229    const int L = std::max(2, (int) (((size_t) mib << 20) / (NE * blob)) + 1);   // layers rotated
230    std::mt19937_64 rng(5);
231    std::vector<uint8_t> one(blob);
232    for (auto& b : one) b = (uint8_t) rng();
233    std::vector<unsigned long long> plan((size_t) L * NE);
234    for (auto& p : plan) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); p = (unsigned long long) d; }
235    const int NW = std::getenv("DS4_BENCH_WIN") ? std::max(1, std::min(16, std::atoi(std::getenv("DS4_BENCH_WIN")))) : 0;   // window path: NW entries a group
236    const int NEN = std::max(1, NW) * NE;   // entries
237    std::vector<int8_t> xq((size_t) 8 * E, 3), hq((size_t) NEN * FF, 3); std::vector<float> xd((size_t) 8 * E / 32, 0.01f), hd((size_t) NEN * FF / 32, 0.01f);
238    for (size_t i = 0; i < xq.size(); ++i) xq[i] = (int8_t) ((int) (rng() % 255) - 127);
239    for (size_t i = 0; i < hq.size(); ++i) hq[i] = (int8_t) ((int) (rng() % 255) - 127);
240    if (const char* e = std::getenv("DS4_BENCH_ACTIVE")) { const int na = std::atoi(e); for (int l = 0; l < L; ++l) for (int k = na; k < NE; ++k) plan[(size_t) l * NE + k] = 0; }   // (empty plan entries)
241    unsigned long long* dplan = up(plan);
242    iq::Args a{};
243    a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
244    for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
245    float *dh, *dp; CK(hipMalloc(&dh, (size_t) NEN * FF * 4)); CK(hipMalloc(&dp, (size_t) NEN * E * 4)); a.h = dh; a.part = dp;
246    std::vector<int> gstart(NE + 1), gent(NEN), ngrp(1, NE);
247    for (int g = 0; g <= NE; ++g) gstart[g] = g * std::max(1, NW);
248    for (int i = 0; i < NEN; ++i) gent[i] = i;
249    a.grp_start = up(gstart); a.grp_ent = up(gent); a.n_groups = up(ngrp);
250    hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
251    double us[2] = {0, 0};
252    for (int part = 0; part < 2; ++part) {
253        auto run = [&](int reps) {
254            hipEventRecord(e0);
255            for (int rep = 0; rep < reps; ++rep) {
256                if (NW) a.grp_ptr = dplan + (size_t) (rep % L) * NE; else a.plan_ptr = dplan + (size_t) (rep % L) * NE;
257                if (part == 0) iq::gate_up(a, NE, std::max(1, NW), 0); else iq::down(a, NE, std::max(1, NW), 0);
258            }
259            hipEventRecord(e1); hipEventSynchronize(e1);
260            float ms; hipEventElapsedTime(&ms, e0, e1);
261            return (double) ms;
262        };
263        double ms = 0; int reps = 2 * L;
264        while (ms < 300.0) { ms = run(reps); reps *= 2; }   // warm-up: clocks ramp, ~300 ms
265        const int n = std::max(L, (int) (reps / 2 * 40.0 / ms));   // ~40 ms a window
266        double best = 1e30;
267        for (int w = 0; w < 7; ++w) best = std::min(best, run(n) * 1e3 / n);   // the best of 7 windows (clocks/thermals wander)
268        us[part] = best;
269    }
270    const double bg = (double) NE * (off[2]) , bd = (double) NE * al((size_t) E * rb_d);   // bytes read a launch
271    std::printf("big %-7s ws %4.0f MiB: gate/up %6.1f us (%5.0f GB/s)  down %6.1f us (%5.0f GB/s)  layer %6.1f us -> %5.0f GB/s, %.2f Tw/s\n",
272                iq::name(type), (double) L * NE * blob / 1048576.0, us[0], bg / us[0] * 1e-3, us[1], bd / us[1] * 1e-3, us[0] + us[1],
273                (bg + bd) / (us[0] + us[1]) * 1e-3, (double) NE * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12);
274    for (auto p : plan) if (p) hipFree((void*) p);
275}
276
277// the light sets (experts of <= 16 rows: DSpark verify windows, short prompts): n_exp experts of `rows` rows each, gate/up and down
278static void bench_light(int type, int nexp, int rows, bool tiles = false) {
279    const int E = 5120, FF = 2304;
280    const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
281    auto al = [](size_t n) { return (n + 255) / 256 * 256; };
282    const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
283    std::mt19937_64 rng(7);
284    std::vector<uint8_t> one(blob);
285    for (auto& b : one) b = (uint8_t) rng();
286    uint8_t* w; CK(hipMalloc(&w, blob * nexp));
287    for (int e = 0; e < nexp; ++e) CK(hipMemcpy(w + (size_t) e * blob, one.data(), blob, hipMemcpyHostToDevice));
288    const int NR = nexp * rows, T = 8;
289    if (tiles && rows <= 16) { std::printf("tiles: rows > 16 only\n"); return; }
290    std::vector<int> bounds(nexp + 1), idx(NR);
291    for (int e = 0; e <= nexp; ++e) bounds[e] = e * rows;
292    for (int i = 0; i < NR; ++i) idx[i] = i % T;
293    std::vector<float> x((size_t) T * E);
294    std::normal_distribution<float> nd(0.f, 1.f);
295    for (auto& v : x) v = nd(rng);
296    std::vector<uint16_t> h((size_t) NR * FF, 0x3c00);
297    iq::SetArgs q{};
298    q.wbase = w; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
299    q.bounds = up(bounds); q.row0 = 0; q.max_rows = rows; q.skip_le = 0; q.n_exp = nexp; q.n_embd = E; q.n_ff = FF; q.limit = 7.0f;
300    q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
301    uint16_t* dh; CK(hipMalloc(&dh, (size_t) NR * FF * 2)); q.h = dh; q.ldo = FF;
302    q.xh = up(h);
303    float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4));
304    hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
305    double us[2] = {0, 0};
306    for (int part = 0; part < 2; ++part) {
307        auto run = [&](int reps) {
308            hipEventRecord(e0);
309            for (int rep = 0; rep < reps; ++rep) {
310                if (part == 0) { q.h = dh; q.ldo = FF; if (tiles) iq::set_gate_up(q, 0); else iq::light_gate_up(q, 0); }
311                else { q.y = dy; q.ldo = E; q.ldx = FF; if (tiles) iq::set_down(q, 0); else iq::light_down(q, 0); }
312            }
313            hipEventRecord(e1); hipEventSynchronize(e1);
314            float ms; hipEventElapsedTime(&ms, e0, e1);
315            return (double) ms;
316        };
317        double ms = 0; int reps = 4;
318        while (ms < 200.0) { ms = run(reps); reps *= 2; }
319        const int n = std::max(2, (int) (reps / 2 * 40.0 / ms));
320        double best = 1e30;
321        for (int wnd = 0; wnd < 5; ++wnd) best = std::min(best, run(n) * 1e3 / n);
322        us[part] = best;
323    }
324    const double bytes = (double) nexp * (off[2] + al((size_t) E * rb_d));
325    std::printf("%s %-7s %3d experts x %2d rows: gate/up %7.1f us  down %7.1f us  -> %6.0f GB/s of weights, %.2f Tw/s, %.1f TMAC/s\n", tiles ? "tiles" : "light", iq::name(type), nexp, rows,
326                us[0], us[1], bytes / ((us[0] + us[1]) * 1e-6) / 1e9, (double) nexp * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12, (double) NR * 3 * FF * E / ((us[0] + us[1]) * 1e-6) / 1e12);
327    hipFree(w);
328}
329
330int main(int argc, char** argv) {
331    std::vector<int> types = {16, 17, 22, 18, 21, 23, 29};
332    std::vector<int> devs;
333    for (int i = 1; i < argc; ++i) {
334        if (std::string(argv[i]) == "--bench-tiles") {   // [types] [n_exp] [rows list]: the prompt sets' tensor-core tiles
335            std::vector<int> bt, rl = {32, 128};
336            int nexp = 48;
337            if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
338            else bt = types;
339            if (i + 1 < argc && argv[i + 1][0] != '-') nexp = std::atoi(argv[++i]);
340            if (i + 1 < argc && argv[i + 1][0] != '-') { rl.clear(); for (const char* p = argv[++i]; *p;) { rl.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
341            for (int t : bt) for (int r : rl) bench_light(t, nexp, r, true);
342            return 0;
343        } else if (std::string(argv[i]) == "--bench-light") {   // [types] [n_exp] [rows list]
344            std::vector<int> bt, rl = {1, 2, 4};
345            int nexp = 24;
346            if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
347            else bt = types;
348            if (i + 1 < argc && argv[i + 1][0] != '-') nexp = std::atoi(argv[++i]);
349            if (i + 1 < argc && argv[i + 1][0] != '-') { rl.clear(); for (const char* p = argv[++i]; *p;) { rl.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
350            for (int t : bt) for (int r : rl) bench_light(t, nexp, r);
351            return 0;
352        } else if (std::string(argv[i]) == "--bench-big") {   // [types] [MiB]
353            std::vector<int> bt; int mib = 640;
354            if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
355            else bt = types;
356            if (i + 1 < argc && argv[i + 1][0] != '-') mib = std::atoi(argv[++i]);
357            for (int t : bt) bench_big(t, mib);
358            return 0;
359        } else if (std::string(argv[i]) == "--bench") {
360            std::vector<int> bt;
361            if (i + 1 < argc && argv[i + 1][0] != '-') { for (const char* p = argv[++i]; *p;) { bt.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
362            else bt = types;
363            for (int t : bt) bench(t);
364            return 0;
365        } else if (std::string(argv[i]) == "--devices" && i + 1 < argc) {   // every check on each device in turn, in this process;
366            devs.clear(); for (const char* p = argv[++i]; *p;) { devs.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; }   // the later ones bit-compared to the first
367        } else if (std::string(argv[i]) == "--dump" && i + 1 < argc) {
368            g_dump = std::fopen(argv[++i], "wb"); if (!g_dump) { std::printf("cannot write %s\n", argv[i]); return 2; }
369        } else if (std::string(argv[i]) == "--cmp" && i + 1 < argc) {
370            g_cmp = std::fopen(argv[++i], "rb"); if (!g_cmp) { std::printf("cannot read %s\n", argv[i]); return 2; }
371        } else if (std::string(argv[i]) == "--type" && i + 1 < argc) {
372            types.clear(); for (const char* p = argv[++i]; *p;) { types.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; }
373        } else if (std::string(argv[i]) == "--iq256" && i + 1 < argc) {
374            gg::gg_cpu_set_iq256(std::atoi(argv[++i]));
375        }
376    }
377    int fails = 0;
378    if (devs.size() > 1) {   // the first device writes its outputs, the others compare to them
379        if (g_dump || g_cmp) { std::printf("--devices takes neither --dump nor --cmp\n"); return 2; }
380    }
381    for (size_t di = 0; di < std::max<size_t>(1, devs.size()); ++di) {
382    if (!devs.empty()) {
383        CK(hipSetDevice(devs[di]));
384        if (devs.size() > 1) {
385            if (g_dump) { std::fclose(g_dump); g_dump = nullptr; }
386            if (di == 0) g_dump = std::fopen("iq_devices.bin", "wb"); else { g_cmp = std::fopen("iq_devices.bin", "rb"); g_cmp_n = g_cmp_bad = 0; }
387        }
388        std::printf("---- device %d\n", devs[di]);
389    }
390    std::mt19937_64 rng(11);
391    std::normal_distribution<float> nd(0.f, 1.f);
392    auto report = [&](const char* what, int type, double worst, double tol) {
393        const bool ok = worst <= tol;
394        std::printf("%-7s %-22s worst %.2e (tol %.0e) %s\n", iq::name(type), what, worst, tol, ok ? "ok" : "FAIL");
395        fails += !ok;
396    };
397    for (int type : types) {
398        if (!iq::supported(type) && !iq::known(type)) { std::printf("%-7s not a type this engine knows\n", iq::name(type)); ++fails; continue; }
399        const bool dev = iq::supported(type);   // (IQ1_S / IQ1_M / IQ4_NL: a known layout, no device kernel - CPU lane only)
400        const int E = 512, FF = 256, NEXP = 3, T = 4;
401        const float lim = 7.0f;
402        const size_t rb_g = iq::row_bytes(type, E), rb_d = iq::row_bytes(type, FF);
403        auto al = [](size_t n) { return (n + 255) / 256 * 256; };
404        const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
405        std::vector<Mat> G(NEXP), U(NEXP), D(NEXP);
406        auto refh = [&](int e, int r, const float* xv, double& scale) {
407            double sg, su;
408            const double g = dotd(&G[e].w[(size_t) r * E], xv, E, &sg), u = dotd(&U[e].w[(size_t) r * E], xv, E, &su);
409            scale = sg + su + 1e-30;
410            return swiglu(g, u, lim);
411        };
412        std::vector<uint8_t> blobs((size_t) NEXP * blob, 0);
413        for (int e = 0; e < NEXP; ++e) {
414            G[e] = make_mat(rng, type, FF, E); U[e] = make_mat(rng, type, FF, E); D[e] = make_mat(rng, type, E, FF);
415            std::memcpy(&blobs[e * blob + off[0]], G[e].bytes.data(), G[e].bytes.size());
416            std::memcpy(&blobs[e * blob + off[1]], U[e].bytes.data(), U[e].bytes.size());
417            std::memcpy(&blobs[e * blob + off[2]], D[e].bytes.data(), D[e].bytes.size());
418        }
419        uint8_t* dblob = up(blobs);
420        std::vector<float> x((size_t) T * E);
421        for (auto& v : x) v = nd(rng) * (1.0f + 3.0f * (rng() % 7 == 0));
422        std::vector<Q8> qx(T);
423        std::vector<int8_t> xq((size_t) T * E); std::vector<float> xd((size_t) T * E / 32);
424        for (int t = 0; t < T; ++t) { qx[t] = quant(&x[(size_t) t * E], E); std::memcpy(&xq[(size_t) t * E], qx[t].q.data(), E); std::memcpy(&xd[(size_t) t * E / 32], qx[t].d.data(), E / 32 * 4); }
425        const int8_t* dxq = up(xq); const float* dxd = up(xd);
426
427        // ---- the reference h of every expert's rows for token 0 (the CPU lane and the device share it)
428        std::vector<float> href((size_t) NEXP * FF);
429        std::vector<Q8> qh(NEXP);
430        for (int e = 0; e < NEXP; ++e)
431            for (int r = 0; r < FF; ++r) {
432                double sc;
433                href[(size_t) e * FF + r] = (float) refh(e, r, qx[0].xhat.data(), sc);
434            }
435        for (int e = 0; e < NEXP; ++e) qh[e] = quant(&href[(size_t) e * FF], FF);
436
437        // ---- token path (device; skipped for a type with no device kernel)
438        if (dev) {
439            std::vector<unsigned long long> plan(NEXP);
440            for (int e = 0; e < NEXP; ++e) plan[e] = (unsigned long long) (dblob + e * blob);
441            iq::Args a{};
442            a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
443            for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
444            float* dh; CK(hipMalloc(&dh, (size_t) NEXP * FF * 4)); a.h = dh;
445            if (!iq::gate_up(a, NEXP, 1, 0)) { std::printf("gate_up refused\n"); return 1; }
446            CK(hipDeviceSynchronize());
447            const auto h = down_(dh, (size_t) NEXP * FF);
448            bits("token h", type, h.data(), h.size() * 4);
449            double worst = 0;
450            for (int e = 0; e < NEXP; ++e)
451                for (int r = 0; r < FF; ++r) {
452                    double sc;
453                    const double ref = refh(e, r, qx[0].xhat.data(), sc);
454                    worst = std::max(worst, std::fabs(h[(size_t) e * FF + r] - ref) / sc);
455                }
456            report("token gate_up", type, worst, 1e-5);
457            std::vector<int8_t> hq((size_t) NEXP * FF); std::vector<float> hd((size_t) NEXP * FF / 32);
458            for (int e = 0; e < NEXP; ++e) { std::memcpy(&hq[(size_t) e * FF], qh[e].q.data(), FF); std::memcpy(&hd[(size_t) e * FF / 32], qh[e].d.data(), FF / 32 * 4); }
459            a.hq = up(hq); a.hd = up(hd);
460            float* dp; CK(hipMalloc(&dp, (size_t) NEXP * E * 4)); a.part = dp;
461            if (!iq::down(a, NEXP, 1, 0)) { std::printf("down refused\n"); return 1; }
462            CK(hipDeviceSynchronize());
463            const auto part = down_(dp, (size_t) NEXP * E);
464            bits("token part", type, part.data(), part.size() * 4);
465            worst = 0;
466            for (int e = 0; e < NEXP; ++e)
467                for (int r = 0; r < E; ++r) {
468                    double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa);
469                    worst = std::max(worst, std::fabs(part[(size_t) e * E + r] - ref) / (sa + 1e-30));
470                }
471            report("token down", type, worst, 1e-6);
472
473            // ---- the prompt sets: expert 0 owns rows [0, 37), expert 2 [37, 42)
474            const int NR = 42;
475            std::vector<int> bounds = {0, 37, 37, 42}, idx(NR);
476            for (int i = 0; i < NR; ++i) idx[i] = i % T;
477            iq::SetArgs q{};
478            q.wbase = dblob; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
479            q.bounds = up(bounds); q.row0 = 0; q.max_rows = 37; q.n_exp = 3; q.n_embd = E; q.n_ff = FF; q.limit = lim;
480            q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
481            uint16_t* dh16; CK(hipMalloc(&dh16, (size_t) NR * FF * 2)); q.h = dh16; q.ldo = FF;
482            if (!iq::set_gate_up(q, 0)) { std::printf("set_gate_up refused\n"); return 1; }
483            CK(hipDeviceSynchronize());
484            const auto h16 = down_(dh16, (size_t) NR * FF);
485            bits("set h16", type, h16.data(), h16.size() * 2);
486            double w2 = 0;
487            for (int e = 0; e < 3; ++e)
488                for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr)
489                    for (int r = 0; r < FF; ++r) {
490                        double sc;
491                        const double ref = refh(e, r, &x[(size_t) idx[lr] * E], sc);
492                        w2 = std::max(w2, std::fabs((double) h2f(h16[(size_t) lr * FF + r]) - ref) / sc);
493                    }
494            // (the prompt sets quantise the activations, so this worst case is data dependent: IQ1_S measured 7.1e-3 .. 1.08e-2 over
495            // different random-data orders, the same on the older build, with every other check far inside; IQ1_S gets 1.5e-2)
496            report("set gate_up (f16)", type, w2, type == 19 ? 1.5e-2 : 1e-2);
497            q.xh = dh16; q.ldx = FF;
498            float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4)); q.y = dy; q.ldo = E;
499            if (!iq::set_down(q, 0)) { std::printf("set_down refused\n"); return 1; }
500            CK(hipDeviceSynchronize());
501            const auto y = down_(dy, (size_t) NR * E);
502            bits("set y", type, y.data(), y.size() * 4);
503            real_shape_bits(type);
504            w2 = 0;
505            for (int e = 0; e < 3; ++e)
506                for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr) {
507                    std::vector<float> hf(FF);
508                    for (int c = 0; c < FF; ++c) hf[c] = h2f(h16[(size_t) lr * FF + c]);
509                    for (int r = 0; r < E; ++r) {
510                        double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hf.data(), FF, &sa);
511                        w2 = std::max(w2, std::fabs(y[(size_t) lr * E + r] - ref) / (sa + 1e-30));
512                    }
513                }
514            // (the prompt sets' tiles take F16 operands for the i-quants: the tile's own rounding, not the token path's)
515            report("set down", type, w2, 3e-3);
516
517            // ---- the matrix-core tiles (HIP gfx11 / gfx12) forced on, against the scalar tiles forced on the same inputs: each within the
518            // tolerances above of the CPU reference, the two within the same tolerance of each other, and the forced-on run must really
519            // have launched them (STRATA_DS4_HIPK is not needed)
520            if (iq::hipk_force(1)) {
521                const long long n0 = iq::hipk_launches();
522                iq::SetArgs qm = q;
523                uint16_t* mh; CK(hipMalloc(&mh, (size_t) NR * FF * 2)); float* my; CK(hipMalloc(&my, (size_t) NR * E * 4));
524                qm.h = mh; qm.ldx = E; qm.ldo = FF; qm.xh = nullptr; qm.y = nullptr;
525                if (!iq::set_gate_up(qm, 0)) { std::printf("matrix-core set_gate_up refused\n"); return 1; }
526                qm.xh = mh; qm.ldx = FF; qm.y = my; qm.ldo = E;
527                if (!iq::set_down(qm, 0)) { std::printf("matrix-core set_down refused\n"); return 1; }
528                CK(hipDeviceSynchronize());
529                const long long taken = iq::hipk_launches() - n0;
530                iq::hipk_force(0);
531                const long long n1 = iq::hipk_launches();
532                uint16_t* sh; CK(hipMalloc(&sh, (size_t) NR * FF * 2)); float* sy; CK(hipMalloc(&sy, (size_t) NR * E * 4));
533                iq::SetArgs qs = q;
534                qs.h = sh; qs.ldx = E; qs.ldo = FF; qs.xh = nullptr; qs.y = nullptr;
535                if (!iq::set_gate_up(qs, 0)) { std::printf("scalar set_gate_up refused\n"); return 1; }
536                qs.xh = sh; qs.ldx = FF; qs.y = sy; qs.ldo = E;
537                if (!iq::set_down(qs, 0)) { std::printf("scalar set_down refused\n"); return 1; }
538                CK(hipDeviceSynchronize());
539                const long long scal = iq::hipk_launches() - n1;
540                iq::hipk_force(-1);
541                const auto hm = down_(mh, (size_t) NR * FF), hs = down_(sh, (size_t) NR * FF);
542                const auto ym = down_(my, (size_t) NR * E), ys = down_(sy, (size_t) NR * E);
543                double wg = 0, wd = 0, wx = 0, wy = 0;
544                for (int e = 0; e < 3; ++e)
545                    for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr) {
546                        std::vector<float> hf(FF);
547                        for (int c = 0; c < FF; ++c) hf[c] = h2f(hm[(size_t) lr * FF + c]);
548                        for (int r = 0; r < FF; ++r) {
549                            double sc;
550                            const double ref = refh(e, r, &x[(size_t) idx[lr] * E], sc);
551                            wg = std::max(wg, std::fabs((double) h2f(hm[(size_t) lr * FF + r]) - ref) / sc);
552                            wx = std::max(wx, std::fabs((double) h2f(hm[(size_t) lr * FF + r]) - (double) h2f(hs[(size_t) lr * FF + r])) / sc);
553                        }
554                        for (int r = 0; r < E; ++r) {
555                            double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hf.data(), FF, &sa);
556                            wd = std::max(wd, std::fabs(ym[(size_t) lr * E + r] - ref) / (sa + 1e-30));
557                            wy = std::max(wy, std::fabs((double) ym[(size_t) lr * E + r] - (double) ys[(size_t) lr * E + r]) / (sa + 1e-30));
558                        }
559                    }
560                std::printf("%-7s matrix-core tiles taken %lld (scalar run: %lld)\n", iq::name(type), taken, scal);
561                if (taken < 2 || scal != 0) { std::printf("%-7s FAIL: the matrix-core tiles did not run as forced\n", iq::name(type)); ++fails; }
562                report("wmma gate_up vs CPU", type, wg, type == 19 ? 1.5e-2 : 1e-2);
563                report("wmma down vs CPU", type, wd, 3e-3);
564                report("wmma vs scalar h", type, wx, type == 19 ? 1.5e-2 : 1e-2);
565                report("wmma vs scalar y", type, wy, 3e-3);
566            }
567        }
568
569        // ---- the CPU lane on the same experts and inputs (ggml-cpu's rows, or Strata's AVX2 ones with DS4_GG_IQ256=1)
570        {
571            gg::IqCpu fm; std::string err;
572            if (!gg::iq_cpu_fmt(type, type, E, FF, fm, err)) { std::printf("%-7s cpu lane: %s\n", iq::name(type), err.c_str()); ++fails; }
573            else {
574                std::vector<uint8_t> act(fm.act_bytes), hact(fm.h_bytes);
575                gg::iq_cpu_quant(fm.gu_act, x.data(), E, act.data());
576                // (the CPU lane rounds the activation to its own type - Q8_K, one F32 scale per 256 values - so the
577                //  reference is that quantized activation, not the device's per-32 one)
578                const std::vector<float> xhat = act_values(fm.gu_act, act.data(), E);
579                double wg = 0, wd = 0;
580                for (int e = 0; e < NEXP; ++e) {
581                    std::vector<float> hc(FF), yc(E);
582                    float* hp[1] = {hc.data()}; float* yp[1] = {yc.data()};
583                    const void* ap[1] = {act.data()};
584                    gg::iq_cpu_gate_up(fm, &blobs[e * blob + off[0]], &blobs[e * blob + off[1]], ap, 1, hp, 0, FF, lim);
585                    for (int r = 0; r < FF; ++r) {
586                        double sg, su;
587                        const double g = dotd(&G[e].w[(size_t) r * E], xhat.data(), E, &sg);
588                        const double u = dotd(&U[e].w[(size_t) r * E], xhat.data(), E, &su);
589                        wg = std::max(wg, std::fabs(hc[r] - swiglu(g, u, lim)) / (sg + su + 1e-30));
590                    }
591                    gg::iq_cpu_quant(fm.d_act, &href[(size_t) e * FF], FF, hact.data());
592                    const std::vector<float> hhat = act_values(fm.d_act, hact.data(), FF);
593                    const void* hpp[1] = {hact.data()};
594                    gg::iq_cpu_down(fm, &blobs[e * blob + off[2]], hpp, 1, yp, 0, E);
595                    for (int r = 0; r < E; ++r) { double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hhat.data(), FF, &sa); wd = std::max(wd, std::fabs(yc[r] - ref) / (sa + 1e-30)); }
596                }
597                report("cpu gate_up vs ref", type, wg, 1e-5);
598                report("cpu down vs ref", type, wd, 1e-5);
599                std::printf("%-7s cpu rows: %s\n", iq::name(type), gg::iq_cpu_own_rows(type) ? "Strata AVX2" : "ggml-cpu");
600            }
601        }
602        CK(hipFree(dblob));
603    }
604    if (g_cmp && devs.size() > 1) { std::fclose(g_cmp); g_cmp = nullptr; std::printf("device %d vs device %d: %ld buffers, %ld differ\n", devs[di], devs[0], g_cmp_n, g_cmp_bad); fails += g_cmp_bad != 0; }
605    }
606    if (g_cmp) { std::printf("bit-compare vs golden: %ld buffers, %ld differ -> %s\n", g_cmp_n, g_cmp_bad, g_cmp_bad ? "DIFFERENT" : "IDENTICAL"); fails += g_cmp_bad != 0; }
607    if (g_dump) std::fclose(g_dump);
608    std::printf("%s\n", fails ? "FAILED" : "ALL OK");
609    return fails;
610}