okami.mom/strata

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

Niko1221Merge f-own-2a-oracle 07df43732 (quant_parity golden reference leg, quant_golden_regen) into f-own-int67148809b

main
40.4 KiB790 linesraw
1// tests/quant/quant_parity.cpp - the layer against its ORACLE: ggml-cpu's own dot products and activation quantizers, bit for bit.
2//
3// ggml-cpu is linked into this program only.  The flavour of the linked ggml-cpu decides which contract is checked (isa.hpp):
4//   a default / STRATA_PORTABLE build  -> Arith::Avx2      (ggml's __AVX2__ branches)
5//   -DSTRATA_ISA_FLOOR=avx             -> Arith::Avx       (its __AVX__ branches)
6//   -DSTRATA_ISA_FLOOR=none            -> Arith::Generic   (its _generic C code)
7// Every kernel of that contract the CPU can run is compared with ggml's, on rows made by ggml's own quantizers from random floats
8// (so scales, mins and sign patterns are those of real models), at 1..8 blocks, and the activation quantizers on random rows and on rows
9// built to be exact ties (where half-to-even and half-away-from-zero differ).
10//
11// TWO LEGS (OWN-2A-ORACLE, 11-10).  ggml-cpu is C that the compiler may contract into FMAs (-ffp-contract=fast, GCC's default for gnu11), and newer
12// GCCs fuse where GCC 13 did not: ggml's own results move with the compiler that builds this test (measured on one Broadwell box: GCC 14.3 moves 55
13// IQ4_NL rows, GCC 15.2 those and 183 Q2_0 rows, by 1-4 ulp), while the layer's results stay the same bytes under GCC 13.3, 14.3 and 15.2.  So:
14//   leg 1, the gate: every group (flavour, section, type, n) of our results against tests/quant/golden_x86.txt, the digests of the reference that
15//          GCC 13.3's ggml-cpu computes for the same inputs (its header says how it was made).  Any difference fails, whatever the compiler.
16//   leg 2, information: our results row by row against the ggml-cpu linked here, as before.  Its summary names the compiler and the groups where
17//          that ggml differs from the golden reference.  QUANT_PARITY_LIVE_STRICT=1 in the environment makes its differences fail too (the old
18//          meaning of this test: right only where the local compiler builds ggml as GCC 13 does).
19// Where no golden exists (arm64: the Neon contract; a run with --rows other than 24) leg 2 is the gate, as before.
20//
21// A failing group, debugged without a GCC 13 box at hand: the FAIL line names its key, e.g. "avx2 dot iq4_nl 96".  Run
22//   quant_parity --dump-group "avx2 dot iq4_nl 96" > here.txt
23// on the failing build and the same on a GCC 13 build of the same tree (or ask for its file): every row of the group, ours per kernel and ggml's, as
24// output bits (hex bytes), with the row's input digest.  `diff` of the two files shows which rows moved and on which side.
25//
26// usage: quant_parity [--rows N] [--type NAME] [--verbose] [--golden FILE] [--dump-group KEY] [--write-golden FILE] [--regen-check]
27//   --write-golden FILE  write this flavour's golden lines (the reference digests of the linked ggml) to FILE; tests/quant/make_golden.sh uses it
28//   --regen-check        GCC 13.x on x86 only (exit 77 = skipped elsewhere): the linked ggml regenerates this flavour's stored lines byte for byte
29// exit 0 = every comparison of the gate leg bit-identical
30#include <cmath>
31#include <cstdint>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35#include <fstream>
36#include <map>
37#include <sstream>
38#include <string>
39#include <vector>
40
41#include "ggml-cpu.h"
42#include "ggml.h"
43#include "strata/quant/act.hpp"
44#include "strata/quant/dequant.hpp"
45#include "strata/quant/dot.hpp"
46#include "strata/quant/isa.hpp"
47#include "strata/quant/types.hpp"
48#include "internal.hpp"   // src/quant: the fp16 helpers (test only)
49
50#ifndef STRATA_QUANT_GOLDEN_FILE
51#define STRATA_QUANT_GOLDEN_FILE ""
52#endif
53
54namespace sq = strata::quant;
55
56namespace {
57
58struct Rng {
59    uint64_t s;
60    explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ull + 99) {}
61    uint32_t next() {
62        s ^= s >> 12;
63        s ^= s << 25;
64        s ^= s >> 27;
65        return (uint32_t) ((s * 0x2545F4914F6CDD1Dull) >> 32);
66    }
67    float uni() { return (float) next() / 4294967296.0f * 2.f - 1.f; }
68    // every draw in its own statement: the operands of one expression have no evaluation order in C++, and GCC and MSVC pick different ones
69    float gauss() {
70        const float a = uni();
71        const float b = uni();
72        const float c = uni();
73        const float d = uni();
74        return (a + b + c + d) * 0.5f;
75    }
76};
77
78// The golden digest: FNV-1a with 64-bit state (offset basis 0xcbf29ce484222325, prime 0x100000001b3), over the bytes in memory order, continued
79// across the rows of a group.  Fixed here on purpose (never std::hash or a library's hash): the golden file is only meaningful while this stays.
80constexpr uint64_t kFnvBasis = 0xcbf29ce484222325ull;
81uint64_t golden_fnv1a64(const void* p, size_t n, uint64_t h = kFnvBasis) {
82    const unsigned char* b = (const unsigned char*) p;
83    for (size_t i = 0; i < n; ++i) {
84        h ^= b[i];
85        h *= 0x100000001b3ull;
86    }
87    return h;
88}
89// the published FNV-1a 64 test vectors
90bool digest_selftest() {
91    return golden_fnv1a64("", 0) == 0xcbf29ce484222325ull && golden_fnv1a64("a", 1) == 0xaf63dc4c8601ec8cull &&
92           golden_fnv1a64("foobar", 6) == 0x85944171f73967e8ull;
93}
94
95std::string compiler_name() {
96#if defined(__clang__)
97    return std::string("clang ") + __clang_version__;
98#elif defined(__GNUC__)
99    return std::string("GCC ") + __VERSION__;
100#elif defined(_MSC_FULL_VER)
101    return "MSVC " + std::to_string(_MSC_FULL_VER);
102#else
103    return "unknown compiler";
104#endif
105}
106
107// Toolchain families of the golden file.  "gcc" lines are made by GCC 13.x on x86 and hold for every toolchain; "msvc" lines, made by MSVC 19.4x, stand
108// beside them only for the groups where MSVC's arithmetic differs (MSVC does not contract the intrinsics' add-of-mul into FMA where GCC does).
109// The family a build reads its own lines from, and whether --regen-check can regenerate them here:
110#if defined(_MSC_VER) && !defined(__clang__)
111const char* const kFamily = "msvc";
112#if _MSC_VER >= 1940 && _MSC_VER < 1950 && (defined(_M_X64) || defined(_M_IX86))
113constexpr bool kRegenHere = true;
114#else
115constexpr bool kRegenHere = false;
116#endif
117#else
118const char* const kFamily = "gcc";
119#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 13 && (defined(__x86_64__) || defined(__i386__))
120constexpr bool kRegenHere = true;
121#else
122constexpr bool kRegenHere = false;
123#endif
124#endif
125constexpr int kGoldenRows = 24;   // the golden file holds the default --rows
126
127sq::Arith oracle_arith() {
128#if defined(__aarch64__)
129    return sq::Arith::Neon;
130#else
131    if (ggml_cpu_has_avx2() && ggml_cpu_has_fma()) return sq::Arith::Avx2;
132    if (ggml_cpu_has_avx()) return sq::Arith::Avx;
133    return sq::Arith::Generic;
134#endif
135}
136
137int g_fail = 0, g_checked = 0, g_live_diff = 0, g_group_checks = 0;   // rows compared (x kernels), live rows that differ, golden group checks
138bool g_info_only = false;   // the oracle is a flavour the layer does not claim (arm64 with SVE): count the differences, do not fail
139bool g_verbose = false;
140bool g_golden_leg = false;   // leg 1 runs (a golden section for this flavour, default --rows)
141bool g_live_strict = false;  // leg 2's differences fail (no golden here, or QUANT_PARITY_LIVE_STRICT=1)
142std::string g_flavour;       // arith_name of the contract checked
143std::string g_dump_key;      // --dump-group
144
145void fail(const char* what, const std::string& detail) {
146    ++g_fail;
147    if (g_fail <= 40) std::printf("FAIL %s: %s\n", what, detail.c_str());
148}
149
150// leg 2: a row where the linked ggml and ours differ
151void live_diff(const char* what, const std::string& detail) {
152    ++g_live_diff;
153    if (g_live_strict) fail(what, detail);
154    else if (g_live_diff <= 10) std::printf("live: %s: %s\n", what, detail.c_str());
155}
156
157std::string hex_bytes(const void* p, size_t n) {
158    static const char* d = "0123456789abcdef";
159    std::string s;
160    const unsigned char* b = (const unsigned char*) p;
161    for (size_t i = 0; i < n; ++i) {
162        s += d[b[i] >> 4];
163        s += d[b[i] & 15];
164    }
165    return s;
166}
167
168std::string hex64(uint64_t v) {
169    char b[20];
170    std::snprintf(b, sizeof b, "%016llx", (unsigned long long) v);
171    return b;
172}
173
174// ---- golden file (tests/quant/golden_x86.txt): lines "<family> <flavour> <section> <name> <n> <rows> <input digest> <reference digest>";
175// "%note <family> <flavour> <section> <name> <why>" lines say why a family has its own lines; '#' lines are comments (the header)
176struct GoldenLine {
177    int rows;
178    uint64_t in, out;
179    std::string text;   // the line without its family, as --write-golden writes it
180};
181std::map<std::string, GoldenLine> g_golden;       // this flavour's gcc lines, by key "<flavour> <section> <name> <n>"
182std::map<std::string, GoldenLine> g_golden_own;   // this flavour's lines of this build's family when it is not gcc (the per-toolchain lines)
183std::vector<std::string> g_golden_gcc_order;      // the gcc keys in stored order (--regen-check under GCC 13)
184std::vector<std::string> g_notes;                 // "%note" lines of this family and flavour
185
186bool load_golden(const std::string& path, const std::string& flavour) {
187    std::ifstream f(path);
188    if (!f) return false;
189    std::string line;
190    while (std::getline(f, line)) {
191        if (!line.empty() && line.back() == '\r') line.pop_back();
192        if (line.empty() || line[0] == '#') continue;
193        std::istringstream ss(line);
194        std::string fam, fl, sec, name, n, in, out;
195        if (line[0] == '%') {
196            std::string tag;
197            ss >> tag >> fam >> fl;
198            if (fam == kFamily && fl == flavour) g_notes.push_back(line.substr(6));
199            continue;
200        }
201        int rows = 0;
202        if (!(ss >> fam >> fl >> sec >> name >> n >> rows >> in >> out)) {
203            std::printf("quant_parity: malformed golden line: %s\n", line.c_str());
204            std::exit(2);
205        }
206        if (fl != flavour) continue;
207        const std::string key = fl + " " + sec + " " + name + " " + n;
208        GoldenLine gl = {rows, std::strtoull(in.c_str(), nullptr, 16), std::strtoull(out.c_str(), nullptr, 16), line.substr(fam.size() + 1)};
209        if (fam == "gcc") {
210            g_golden[key] = gl;
211            g_golden_gcc_order.push_back(key);
212        } else if (fam == kFamily) {
213            g_golden_own[key] = gl;
214        }
215    }
216    return true;
217}
218
219// the line this build is held to: its family's own line where one exists, else the gcc line
220const GoldenLine* golden_for(const std::string& key) {
221    auto own = g_golden_own.find(key);
222    if (own != g_golden_own.end()) return &own->second;
223    auto it = g_golden.find(key);
224    return it == g_golden.end() ? nullptr : &it->second;
225}
226
227// one group of comparisons: the inputs and the reference (the linked ggml) are digested once, each kernel's results against them
228struct Group {
229    std::string key, name;
230    int rows = 0;
231    uint64_t in = kFnvBasis, ref = kFnvBasis;
232};
233std::vector<Group> g_groups;                    // visiting order = the order of the golden lines
234std::map<std::string, int> g_groups_by_key;
235std::vector<std::string> g_ref_moved;           // leg 2: groups where the linked ggml differs from golden
236
237Group& open_group(const char* section, const char* name, int n) {
238    const std::string key = g_flavour + " " + section + " " + name + " " + std::to_string(n);
239    g_groups.push_back(Group());
240    Group& g = g_groups.back();
241    g.key = key;
242    g.name = name;
243    g_groups_by_key[key] = (int) g_groups.size() - 1;
244    return g;
245}
246
247// close a group: the reference against golden (leg 2's summary), and every kernel's digest against golden (leg 1)
248void close_group(Group& g, const std::vector<std::pair<const char*, uint64_t>>& ours) {
249    if (!g_golden_leg) return;
250    const GoldenLine* gp = golden_for(g.key);
251    if (gp == nullptr) {
252        fail(g.name.c_str(), "group \"" + g.key + "\" has no golden line (a new case: regenerate tests/quant/golden_x86.txt, tests/quant/make_golden.sh)");
253        return;
254    }
255    const GoldenLine& gl = *gp;
256    if (gl.in != g.in || gl.rows != g.rows) {
257        fail(g.name.c_str(), "group \"" + g.key + "\": the INPUTS differ from the golden file's (" + std::to_string(g.rows) + " rows, digest " + hex64(g.in) +
258                                 "; golden " + std::to_string(gl.rows) + " rows, " + hex64(gl.in) + "): ggml's quantizers that make the test rows moved here");
259        return;
260    }
261    if (gl.out != g.ref) g_ref_moved.push_back(g.key);
262    for (const auto& k : ours) {
263        ++g_group_checks;
264        if (k.second != gl.out)
265            fail(g.name.c_str(), std::string("kernel ") + k.first + ": group \"" + g.key + "\" differs from the golden reference (ours " + hex64(k.second) +
266                                     ", golden " + hex64(gl.out) + "); rows: --dump-group \"" + g.key + "\"");
267    }
268}
269
270void dump_row(const Group& g, const char* who, int idx, uint64_t in, const void* out, size_t n) {
271    if (g.key == g_dump_key) std::printf("ROW %s %s %d %s %s\n", g.key.c_str(), who, idx, hex64(in).c_str(), hex_bytes(out, n).c_str());
272}
273
274// weights of `type`, `nrows` rows of n elements, quantized by ggml from gaussian floats of scale `amp`
275std::vector<uint8_t> make_rows(ggml_type type, int n, int nrows, Rng& r, float amp) {
276    ggml_quantize_init(type);
277    std::vector<float> f((size_t) n * nrows), im((size_t) n, 1.0f);
278    for (float& v : f) v = r.gauss() * amp;
279    std::vector<uint8_t> out(ggml_row_size(type, n) * nrows);
280    const size_t got = ggml_quantize_chunk(type, f.data(), out.data(), 0, nrows, n, ggml_quantize_requires_imatrix(type) ? im.data() : nullptr);
281    if (got != out.size()) {
282        std::printf("quantize_chunk(%s) returned %zu, expected %zu\n", ggml_type_name(type), got, out.size());
283        std::exit(2);
284    }
285    return out;
286}
287
288bool bits_equal(float a, float b) { return std::memcmp(&a, &b, 4) == 0; }
289
290uint32_t float_bits(float f) {
291    uint32_t u;
292    std::memcpy(&u, &f, 4);
293    return u;
294}
295
296void test_dot(sq::Type st, int rows) {
297    const ggml_type gt = (ggml_type) (int) st;
298    const sq::TypeInfo* ti = sq::type_info(st);
299    const ggml_type_traits_cpu* tr = ggml_get_type_traits_cpu(gt);
300    if (ti == nullptr || tr == nullptr || tr->vec_dot == nullptr) return;
301    const sq::Arith ar = oracle_arith();
302    // ggml's SSE4.2-only flavour (STRATA_ISA_FLOOR=none) has an SSSE3 branch for Q4_0 that is neither the generic C code nor AVX: not a contract of the layer
303    if (ar == sq::Arith::Generic && st == sq::Type::Q4_0) {
304        std::printf("  dot q4_0      skipped: ggml's SSSE3 branch is not the Generic contract\n");
305        return;
306    }
307    const sq::DotKernel* ks[16];
308    const int nk = sq::dot_kernels(st, ar, ks, 16);
309    const ggml_type_traits_cpu* ta = ggml_get_type_traits_cpu(tr->vec_dot_type);
310    if ((int) tr->vec_dot_type != (int) ti->act) {
311        fail(ti->name, "vec_dot_type differs from the layer's type table");
312        return;
313    }
314    if ((int) ggml_blck_size(gt) != ti->blck || ggml_type_size(gt) != ti->bytes) fail(ti->name, "block geometry differs from ggml's");
315    std::vector<const sq::DotKernel*> run;
316    for (int ki = 0; ki < nk; ++ki)
317        if (sq::isa_ok(ks[ki]->isa)) run.push_back(ks[ki]);
318    const int unit = ti->blck > (int) ggml_blck_size(tr->vec_dot_type) ? ti->blck : (int) ggml_blck_size(tr->vec_dot_type);
319    Rng r(1234 + (uint64_t) st);
320    std::vector<int> live_bad(run.size(), 0);
321    for (int nbk = 1; nbk <= 8; ++nbk) {
322        const int n = unit * nbk;
323        const float amp = nbk % 3 == 0 ? 0.02f : (nbk % 3 == 1 ? 1.0f : 40.0f);
324        const std::vector<uint8_t> w = make_rows(gt, n, rows, r, amp);
325        const size_t wrow = ggml_row_size(gt, n), arow = ggml_row_size(tr->vec_dot_type, n);
326        std::vector<float> xf((size_t) n);
327        std::vector<uint8_t> act(arow * 3);
328        for (int rep = 0; rep < 3; ++rep) {
329            for (float& v : xf) v = r.gauss() * (rep == 0 ? 1.f : (rep == 1 ? 0.05f : 7.f));
330            ta->from_float(xf.data(), act.data() + arow * rep, n);
331        }
332        Group& g = open_group("dot", ti->name, n);
333        std::vector<float> want((size_t) 3 * rows);
334        for (int rep = 0; rep < 3; ++rep)
335            for (int row = 0; row < rows; ++row) {
336                const uint8_t* wr = w.data() + (size_t) row * wrow;
337                const uint8_t* ar_ = act.data() + arow * rep;
338                float& o = want[(size_t) rep * rows + row];
339                tr->vec_dot(n, &o, 0, wr, 0, ar_, 0, 1);
340                const uint64_t rin = golden_fnv1a64(ar_, arow, golden_fnv1a64(wr, wrow));
341                g.in = golden_fnv1a64(ar_, arow, golden_fnv1a64(wr, wrow, g.in));
342                g.ref = golden_fnv1a64(&o, 4, g.ref);
343                ++g.rows;
344                dump_row(g, "ggml", rep * 1000 + row, rin, &o, 4);
345            }
346        std::vector<std::pair<const char*, uint64_t>> ours;
347        for (size_t ki = 0; ki < run.size(); ++ki) {
348            const sq::DotKernel* k = run[ki];
349            uint64_t h = kFnvBasis;
350            for (int rep = 0; rep < 3; ++rep)
351                for (int row = 0; row < rows; ++row) {
352                    const uint8_t* wr = w.data() + (size_t) row * wrow;
353                    const uint8_t* ar_ = act.data() + arow * rep;
354                    float got = 0.f;
355                    k->fn(n, &got, wr, ar_);
356                    h = golden_fnv1a64(&got, 4, h);
357                    if (!g_dump_key.empty()) dump_row(g, k->name, rep * 1000 + row, golden_fnv1a64(ar_, arow, golden_fnv1a64(wr, wrow)), &got, 4);
358                    const float wv = want[(size_t) rep * rows + row];
359                    ++g_checked;
360                    if (!bits_equal(wv, got) && live_bad[ki]++ < 1) {
361                        char b[220];
362                        std::snprintf(b, sizeof b, "kernel %s n=%d row %d: ggml %.9g (%08x) ours %.9g (%08x)", k->name, n, rep * 1000 + row, wv,
363                                      float_bits(wv), got, float_bits(got));
364                        live_diff(ti->name, b);
365                    } else if (!bits_equal(wv, got)) {
366                        live_diff(ti->name, std::string("kernel ") + k->name + " n=" + std::to_string(n) + " row " + std::to_string(rep * 1000 + row));
367                    }
368                }
369            ours.emplace_back(k->name, h);
370        }
371        close_group(g, ours);
372    }
373    if (g_verbose)
374        for (const sq::DotKernel* k : run) std::printf("  dot %-10s %-18s (%s/%s) done\n", ti->name, k->name, sq::arith_name(k->arith), sq::isa_name(k->isa));
375    if (run.empty() && g_verbose) std::printf("  dot %-10s no kernel of contract %s runs here\n", ti->name, sq::arith_name(ar));
376    if (run.empty() && nk == 0) fail(ti->name, std::string("the layer has no kernel of contract ") + sq::arith_name(ar));
377}
378
379void test_act(sq::Type act, int rows) {
380    const ggml_type gt = (ggml_type) (int) act;
381    const ggml_type_traits_cpu* tr = ggml_get_type_traits_cpu(gt);
382    const sq::TypeInfo* ti = sq::type_info(act);
383    if (tr == nullptr || tr->from_float == nullptr || ti == nullptr) return;
384    const sq::Arith ar = oracle_arith();
385    const sq::ActKernel* k = sq::act_kernel(act, ar);
386    if (k == nullptr || k->arith != ar) {
387        fail(ti->name, std::string("no activation quantizer of contract ") + sq::arith_name(ar));
388        return;
389    }
390    Rng r(777 + (uint64_t) act);
391    for (int nbk = 1; nbk <= 6; ++nbk) {
392        const int n = ti->blck * nbk;
393        Group& g = open_group("act", ti->name, n);
394        uint64_t h = kFnvBasis;
395        bool reported = false;
396        std::vector<float> x((size_t) n);
397        std::vector<uint8_t> a(ti->bytes * nbk), b(ti->bytes * nbk);
398        for (int it = 0; it < rows * 4; ++it) {
399            for (float& v : x) v = r.gauss() * (it % 3 == 0 ? 1.f : (it % 3 == 1 ? 1e-3f : 300.f));
400            if (it % 7 == 0) std::memset(x.data(), 0, x.size() * 4);   // an all-zero block
401            if (it % 11 == 0) x[(size_t) (r.next() % n)] = 0.f;
402            // ties: a block whose absolute maximum is 127 (id = 1) with half-integers elsewhere, and its negation
403            if (it % 5 == 0) {
404                // one draw per statement (see Rng::gauss): two r.next() in one expression gave MSVC other inputs than GCC
405                for (int j = 0; j < n; ++j) {
406                    const int q = (int) (r.next() % 255) - 127;
407                    const float half = r.next() & 1 ? 0.f : 0.5f;
408                    x[(size_t) j] = q * 0.5f + half;
409                }
410                for (int bI = 0; bI < nbk; ++bI) {
411                    const uint32_t at = r.next() % ti->blck;
412                    x[(size_t) bI * ti->blck + at] = r.next() & 1 ? 127.f : -127.f;
413                }
414                if (act == sq::Type::Q8_K) for (int bI = 0; bI < nbk; ++bI) x[(size_t) bI * ti->blck + r.next() % ti->blck] = 127.f;
415            }
416            // pre-filled: Q8_K leaves an all-zero block's 16 block sums unwritten (ggml and the layer alike); without this they carry an earlier row's bytes
417            std::memset(a.data(), 0, a.size());
418            std::memset(b.data(), 0, b.size());
419            tr->from_float(x.data(), a.data(), n);
420            k->fn(x.data(), b.data(), n);
421            const uint64_t rin = golden_fnv1a64(x.data(), x.size() * 4);
422            g.in = golden_fnv1a64(x.data(), x.size() * 4, g.in);
423            g.ref = golden_fnv1a64(a.data(), a.size(), g.ref);
424            h = golden_fnv1a64(b.data(), b.size(), h);
425            ++g.rows;
426            dump_row(g, "ggml", it, rin, a.data(), a.size());
427            dump_row(g, k->name, it, rin, b.data(), b.size());
428            ++g_checked;
429            if (std::memcmp(a.data(), b.data(), a.size()) != 0 && !reported) {
430                reported = true;
431                size_t at = 0;
432                while (a[at] == b[at]) ++at;
433                char buf[160];
434                std::snprintf(buf, sizeof buf, "kernel %s n=%d iteration %d: first differing byte %zu (ggml %02x ours %02x)", k->name, n, it, at, a[at], b[at]);
435                live_diff(ti->name, buf);
436            }
437        }
438        close_group(g, {{k->name, h}});
439    }
440    if (g_verbose) std::printf("  act %-10s %-18s done\n", ti->name, k->name);
441}
442
443// to_float of every type the layer dequantizes, and the Q4_0 requantizer (--mtp-q4's output), bit for bit against ggml-base
444void test_dequant(int rows) {
445    static const sq::Type kTypes[] = {sq::Type::Q2_0, sq::Type::Q4_0, sq::Type::Q4_1, sq::Type::Q5_0, sq::Type::Q5_1, sq::Type::Q8_0, sq::Type::MXFP4,
446                                      sq::Type::NVFP4, sq::Type::Q2_K, sq::Type::Q3_K, sq::Type::Q4_K, sq::Type::Q5_K, sq::Type::Q6_K, sq::Type::IQ2_XXS,
447                                      sq::Type::IQ2_XS, sq::Type::IQ2_S, sq::Type::IQ3_XXS, sq::Type::IQ3_S, sq::Type::IQ1_S, sq::Type::IQ1_M,
448                                      sq::Type::IQ4_NL, sq::Type::IQ4_XS};
449    for (sq::Type st : kTypes) {
450        const ggml_type gt = (ggml_type) (int) st;
451        const ggml_type_traits* tr = ggml_get_type_traits(gt);
452        const sq::TypeInfo* ti = sq::type_info(st);
453        if (tr == nullptr || tr->to_float == nullptr) continue;
454        if (!sq::can_dequant(st)) {
455            fail(ti->name, "the layer cannot dequantize it");
456            continue;
457        }
458        Rng r(321 + (uint64_t) st);
459        for (int nbk = 1; nbk <= 4; ++nbk) {
460            const int n = ti->blck * nbk;
461            const std::vector<uint8_t> w = make_rows(gt, n, rows, r, nbk % 2 ? 1.0f : 30.0f);
462            Group& g = open_group("deq", ti->name, n);
463            uint64_t h = kFnvBasis;
464            bool reported = false;
465            std::vector<float> a((size_t) n), b((size_t) n);
466            for (int row = 0; row < rows; ++row) {
467                const uint8_t* wr = w.data() + (size_t) row * ggml_row_size(gt, n);
468                tr->to_float(wr, a.data(), n);
469                std::memset(b.data(), 0, b.size() * 4);
470                const bool ok = sq::dequant_row(st, wr, b.data(), n);
471                const uint64_t rin = golden_fnv1a64(wr, ggml_row_size(gt, n));
472                g.in = golden_fnv1a64(wr, ggml_row_size(gt, n), g.in);
473                g.ref = golden_fnv1a64(a.data(), a.size() * 4, g.ref);
474                h = golden_fnv1a64(b.data(), b.size() * 4, h);
475                ++g.rows;
476                ++g_checked;
477                dump_row(g, "ggml", row, rin, a.data(), a.size() * 4);
478                dump_row(g, "dequant_row", row, rin, b.data(), b.size() * 4);
479                if (!ok) {
480                    fail(ti->name, "dequant_row refused n=" + std::to_string(n));
481                    break;
482                }
483                if (std::memcmp(a.data(), b.data(), a.size() * 4) != 0 && !reported) {
484                    reported = true;
485                    live_diff(ti->name, "dequant_row differs from ggml's to_float, n=" + std::to_string(n) + " row " + std::to_string(row));
486                }
487            }
488            close_group(g, {{"dequant_row", h}});
489        }
490    }
491    // Q4_0 from floats: ggml_quantize_chunk(Q4_0, no imatrix) is quantize_row_q4_0_ref
492    Rng r(99);
493    for (int nbk = 1; nbk <= 6; ++nbk) {
494        const int n = 32 * nbk;
495        Group& g = open_group("rq4", "q4_0", n);
496        uint64_t h = kFnvBasis;
497        bool reported = false;
498        std::vector<float> f((size_t) n);
499        std::vector<uint8_t> a(18 * nbk), b(18 * nbk);
500        for (int it = 0; it < rows * 4; ++it) {
501            for (float& v : f) v = r.gauss() * (it % 3 == 0 ? 1.f : (it % 3 == 1 ? 1e-3f : 200.f));
502            if (it % 9 == 0) std::memset(f.data(), 0, f.size() * 4);
503            ggml_quantize_chunk(GGML_TYPE_Q4_0, f.data(), a.data(), 0, 1, n, nullptr);
504            sq::quantize_q4_0_ref(f.data(), b.data(), n);
505            const uint64_t rin = golden_fnv1a64(f.data(), f.size() * 4);
506            g.in = golden_fnv1a64(f.data(), f.size() * 4, g.in);
507            g.ref = golden_fnv1a64(a.data(), a.size(), g.ref);
508            h = golden_fnv1a64(b.data(), b.size(), h);
509            ++g.rows;
510            dump_row(g, "ggml", it, rin, a.data(), a.size());
511            dump_row(g, "quantize_q4_0_ref", it, rin, b.data(), b.size());
512            ++g_checked;
513            if (a != b && !reported) {
514                reported = true;
515                live_diff("q4_0", "quantize_q4_0_ref differs from ggml_quantize_chunk, n=" + std::to_string(n) + " iteration " + std::to_string(it));
516            }
517        }
518        close_group(g, {{"quantize_q4_0_ref", h}});
519    }
520}
521
522// Values within a few ulps of the rounding boundaries of the Q8_K quantizer (nearest_int adds the 2^23 + 2^22 magic number to iscale * x) and of the Q4_0
523// requantizer (x * id + 8.5, truncated).  A compiler that contracts the multiply and the add into one FMA gives another result on exactly these inputs, and
524// ggml-base does so on arm64 under GCC (not on x86), so random data finds the mismatch only after millions of values: this finds it in a few thousand.
525void test_boundary(int rows) {
526    Rng r(4242);
527    const sq::Arith ar = oracle_arith();
528    const sq::ActKernel* k8 = sq::act_kernel(sq::Type::Q8_K, ar);
529    const ggml_type_traits_cpu* t8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K);
530    auto jitter = [&r](float v) {
531        for (uint32_t t = r.next() % 4; t > 0; --t) v = std::nextafter(v, r.next() & 1 ? INFINITY : -INFINITY);
532        return v;
533    };
534    if (k8 != nullptr && t8 != nullptr) {
535        Group& g = open_group("bnd", "q8_K", 256);
536        uint64_t h = kFnvBasis;
537        bool reported = false;
538        std::vector<float> x(256);
539        std::vector<uint8_t> a(sq::kBlockQ8_K), b(sq::kBlockQ8_K);
540        for (int it = 0; it < rows * 300; ++it) {
541            const float m = 0.5f + 0.5f * std::fabs(r.uni());
542            const int e = (int) (r.next() % 14) - 7;
543            const float dd = std::ldexp(m, e);
544            const float x0 = (r.next() & 1 ? 127.f : -127.f) * dd;
545            const float step = -1.f / (-127.f / x0);
546            x[0] = x0;
547            for (int j = 1; j < 256; ++j) x[(size_t) j] = jitter(((int) (r.next() % 253) - 126 + 0.5f) * step);
548            std::memset(a.data(), 0, a.size());
549            std::memset(b.data(), 0, b.size());
550            t8->from_float(x.data(), a.data(), 256);
551            k8->fn(x.data(), b.data(), 256);
552            const uint64_t rin = golden_fnv1a64(x.data(), x.size() * 4);
553            g.in = golden_fnv1a64(x.data(), x.size() * 4, g.in);
554            g.ref = golden_fnv1a64(a.data(), a.size(), g.ref);
555            h = golden_fnv1a64(b.data(), b.size(), h);
556            ++g.rows;
557            dump_row(g, "ggml", it, rin, a.data(), a.size());
558            dump_row(g, k8->name, it, rin, b.data(), b.size());
559            ++g_checked;
560            if (a != b && !reported) {
561                reported = true;
562                live_diff("q8_K", "boundary values: the quantizer differs from ggml's (a fused multiply-add on one side), iteration " + std::to_string(it));
563            }
564        }
565        close_group(g, {{k8->name, h}});
566    }
567    Group& g = open_group("bnd", "q4_0", 32);
568    uint64_t h = kFnvBasis;
569    bool reported = false;
570    std::vector<float> x(32);
571    std::vector<uint8_t> a(18), b(18);
572    for (int it = 0; it < rows * 300; ++it) {
573        const float m = 0.5f + 0.5f * std::fabs(r.uni());
574        const int e = (int) (r.next() % 14) - 7;
575        const float dd = std::ldexp(m, e);
576        x[0] = -8.f * dd;
577        for (int j = 1; j < 32; ++j) x[(size_t) j] = jitter(((int) (r.next() % 15) + 1 - 8.5f) * dd);
578        ggml_quantize_chunk(GGML_TYPE_Q4_0, x.data(), a.data(), 0, 1, 32, nullptr);
579        sq::quantize_q4_0_ref(x.data(), b.data(), 32);
580        const uint64_t rin = golden_fnv1a64(x.data(), x.size() * 4);
581        g.in = golden_fnv1a64(x.data(), x.size() * 4, g.in);
582        g.ref = golden_fnv1a64(a.data(), a.size(), g.ref);
583        h = golden_fnv1a64(b.data(), b.size(), h);
584        ++g.rows;
585        dump_row(g, "ggml", it, rin, a.data(), a.size());
586        dump_row(g, "quantize_q4_0_ref", it, rin, b.data(), b.size());
587        ++g_checked;
588        if (a != b && !reported) {
589            reported = true;
590            live_diff("q4_0", "boundary values: quantize_q4_0_ref differs from ggml's (a fused multiply-add on one side), iteration " + std::to_string(it));
591        }
592    }
593    close_group(g, {{"quantize_q4_0_ref", h}});
594}
595
596void test_fp16() {
597    // our software fp16 conversions against ggml's, every fp16 value and a spread of floats (one group, two rows: the two directions)
598    Group& g = open_group("fp16", "fp16", 0);
599    int bad = 0;
600    uint64_t h = kFnvBasis;
601    for (uint32_t hv = 0; hv < 65536; ++hv) {
602        const uint16_t u = (uint16_t) hv;
603        const float a = ggml_fp16_to_fp32((ggml_fp16_t) u);
604        const float b = sq::fp16_to_fp32(u);
605        g.in = golden_fnv1a64(&u, 2, g.in);
606        g.ref = golden_fnv1a64(&a, 4, g.ref);
607        h = golden_fnv1a64(&b, 4, h);
608        if (std::isnan(a) ? !std::isnan(b) : !bits_equal(a, b)) ++bad;
609    }
610    ++g.rows;
611    Rng r(5);
612    for (int i = 0; i < 4000000; ++i) {
613        uint32_t w = r.next();
614        float f;
615        std::memcpy(&f, &w, 4);
616        if (std::isnan(f)) continue;
617        const uint16_t a = ggml_fp32_to_fp16(f), b = sq::fp32_to_fp16(f);
618        g.in = golden_fnv1a64(&f, 4, g.in);
619        g.ref = golden_fnv1a64(&a, 2, g.ref);
620        h = golden_fnv1a64(&b, 2, h);
621        if (a != b) ++bad;
622    }
623    ++g.rows;
624    ++g_checked;
625    if (bad) live_diff("fp16", std::to_string(bad) + " conversions differ from ggml's");
626    close_group(g, {{"fp16", h}});
627}
628
629std::string golden_lines_of_this_run() {
630    std::string s;
631    for (const Group& g : g_groups) s += g.key + " " + std::to_string(g.rows) + " " + hex64(g.in) + " " + hex64(g.ref) + "\n";
632    return s;
633}
634
635}  // namespace
636
637int main(int argc, char** argv) {
638    int rows = kGoldenRows;
639    const char* only = nullptr;
640    std::string golden_path = STRATA_QUANT_GOLDEN_FILE, write_golden;
641    bool regen_check = false;
642    for (int i = 1; i < argc; ++i) {
643        if (!std::strcmp(argv[i], "--rows") && i + 1 < argc) rows = std::atoi(argv[++i]);
644        else if (!std::strcmp(argv[i], "--type") && i + 1 < argc) only = argv[++i];
645        else if (!std::strcmp(argv[i], "--verbose")) g_verbose = true;
646        else if (!std::strcmp(argv[i], "--golden") && i + 1 < argc) golden_path = argv[++i];
647        else if (!std::strcmp(argv[i], "--dump-group") && i + 1 < argc) g_dump_key = argv[++i];
648        else if (!std::strcmp(argv[i], "--write-golden") && i + 1 < argc) write_golden = argv[++i];
649        else if (!std::strcmp(argv[i], "--regen-check")) regen_check = true;
650        else {
651            std::printf("quant_parity: unknown argument %s\n", argv[i]);
652            return 2;
653        }
654    }
655    if (!digest_selftest()) {
656        std::printf("quant_parity: FAIL: the golden digest (FNV-1a 64) does not give its test vectors\n");
657        return 1;
658    }
659    if (regen_check && !kRegenHere) {
660        std::printf("quant_parity --regen-check: SKIPPED: the golden lines are made by GCC 13.x (family gcc) and MSVC 19.4x (family msvc) on x86; this is %s\n",
661                    compiler_name().c_str());
662        return 77;
663    }
664    ggml_cpu_init();
665    const sq::Arith ar = oracle_arith();
666    g_flavour = sq::arith_name(ar);
667    std::printf("quant_parity: oracle flavour %s (ggml avx=%d avx2=%d fma=%d f16c=%d avx512=%d), layer best isa %s, default contract %s, compiler %s\n",
668                sq::arith_name(ar), ggml_cpu_has_avx(), ggml_cpu_has_avx2(), ggml_cpu_has_fma(), ggml_cpu_has_f16c(), ggml_cpu_has_avx512(),
669                sq::isa_name(sq::best_isa()), sq::arith_name(sq::default_arith()), compiler_name().c_str());
670#if defined(__aarch64__)
671    // The Neon contract is ggml-cpu's arm64 flavour with the dot product extension (the shipped STRATA_PORTABLE build and the Mac's native build).  A ggml-cpu without it
672    // (GCC's -mcpu=native on the Spark's mixed X925 + A725 cores resolves to plain armv8-a) runs other code, and one with SVE other branches of the Q4_0 / Q8_0 /
673    // K-quant dots: those flavours are not the contract.  The first is skipped, the second is run for information and its differences do not fail the test.
674    if (!ggml_cpu_has_dotprod()) {
675        std::printf("quant_parity: SKIPPED, this ggml-cpu is built without the dot product extension (not the Neon contract)\n");
676        return 0;
677    }
678    if (ggml_cpu_has_sve()) {
679        g_info_only = true;
680        std::printf("quant_parity: this ggml-cpu is built with SVE (not the Neon contract): differences are reported, not failed\n");
681    }
682#endif
683    const bool have_golden = !golden_path.empty() && load_golden(golden_path, g_flavour) && !g_golden.empty();
684    g_golden_leg = have_golden && rows == kGoldenRows && write_golden.empty();
685    const char* strict_env = std::getenv("QUANT_PARITY_LIVE_STRICT");
686    g_live_strict = !g_golden_leg || (strict_env != nullptr && std::strcmp(strict_env, "0") != 0 && *strict_env != '\0');
687    if (regen_check && !have_golden) {
688        std::printf("quant_parity --regen-check: FAIL: no golden lines for flavour %s in %s\n", g_flavour.c_str(), golden_path.c_str());
689        return 1;
690    }
691    if (regen_check && rows != kGoldenRows) {
692        std::printf("quant_parity --regen-check: FAIL: the golden file holds --rows %d\n", kGoldenRows);
693        return 1;
694    }
695    if (g_golden_leg) {
696        std::printf("quant_parity: leg 1 (gate): ours against the golden reference, %zu groups of flavour %s (%s); leg 2 (%s): ours against the ggml-cpu linked here\n",
697                    g_golden.size(), g_flavour.c_str(), golden_path.c_str(), g_live_strict ? "FATAL, QUANT_PARITY_LIVE_STRICT" : "information");
698        if (!g_golden_own.empty()) {
699            std::printf("quant_parity: toolchain family %s has its own golden lines for %zu groups of flavour %s:", kFamily, g_golden_own.size(), g_flavour.c_str());
700            for (const auto& kv : g_golden_own) std::printf(" %s;", kv.first.c_str());
701            std::printf("\n");
702            for (const std::string& n : g_notes) std::printf("quant_parity:   why: %s\n", n.c_str());
703        }
704    }
705    else
706        std::printf("quant_parity: no golden reference for flavour %s%s: the gate is ours against the ggml-cpu linked here\n", g_flavour.c_str(),
707                    have_golden ? " at this --rows" : (golden_path.empty() ? "" : (" in " + golden_path).c_str()));
708    test_fp16();
709    test_dequant(rows);
710    test_boundary(rows);
711    for (sq::Type a : {sq::Type::Q8_0, sq::Type::Q8_1, sq::Type::Q8_K})
712        if (only == nullptr || !std::strcmp(only, sq::type_info(a)->name)) test_act(a, rows);
713    static const sq::Type kTypes[] = {sq::Type::Q2_0, sq::Type::Q4_0, sq::Type::Q4_1, sq::Type::Q5_0, sq::Type::Q5_1, sq::Type::Q8_0, sq::Type::IQ4_NL,
714                                      sq::Type::MXFP4, sq::Type::NVFP4, sq::Type::Q2_K, sq::Type::Q3_K, sq::Type::Q4_K, sq::Type::Q5_K, sq::Type::Q6_K,
715                                      sq::Type::IQ1_S, sq::Type::IQ1_M, sq::Type::IQ2_XXS, sq::Type::IQ2_XS, sq::Type::IQ2_S, sq::Type::IQ3_XXS,
716                                      sq::Type::IQ3_S, sq::Type::IQ4_XS};
717    for (sq::Type t : kTypes)
718        if (only == nullptr || !std::strcmp(only, sq::type_info(t)->name)) test_dot(t, rows);
719
720    const std::string mine = golden_lines_of_this_run();
721    if (!write_golden.empty()) {
722        if (only != nullptr || rows != kGoldenRows) {
723            std::printf("quant_parity --write-golden: refused with --type or --rows (the golden file holds every group at --rows %d)\n", kGoldenRows);
724            return 2;
725        }
726        FILE* f = std::fopen(write_golden.c_str(), "wb");
727        const std::string head = "# made by " + compiler_name() + ", flavour " + g_flavour + ", " + std::to_string(g_groups.size()) + " groups\n";
728        if (f == nullptr || std::fwrite(head.data(), 1, head.size(), f) != head.size() || std::fwrite(mine.data(), 1, mine.size(), f) != mine.size() ||
729            std::fclose(f) != 0) {
730            std::printf("quant_parity --write-golden: cannot write %s\n", write_golden.c_str());
731            return 2;
732        }
733        std::printf("quant_parity --write-golden: %zu groups of flavour %s written to %s (%s)\n", g_groups.size(), g_flavour.c_str(), write_golden.c_str(),
734                    compiler_name().c_str());
735        return 0;
736    }
737    if (regen_check) {
738        if (only != nullptr) {
739            std::printf("quant_parity --regen-check: refused with --type\n");
740            return 2;
741        }
742        std::string stored;
743        if (std::strcmp(kFamily, "gcc") == 0) {
744            for (const std::string& k : g_golden_gcc_order) stored += g_golden[k].text + "\n";
745        } else {
746            // this family's own lines must regenerate, and every group without one must equal its gcc line (else MSVC differs in a new group: it needs a line)
747            int own = 0;
748            for (const Group& g : g_groups) {
749                const GoldenLine* gl = golden_for(g.key);
750                own += g_golden_own.count(g.key) ? 1 : 0;
751                stored += (gl ? gl->text : std::string("(no golden line for ") + g.key + ")") + "\n";
752            }
753            if (own != (int) g_golden_own.size()) {
754                std::printf("quant_parity --regen-check: FAIL: %zu %s lines of flavour %s stored, %d met\n", g_golden_own.size(), kFamily, g_flavour.c_str(), own);
755                return 1;
756            }
757        }
758        if (stored == mine) {
759            std::printf("quant_parity --regen-check: PASS: %s regenerates the stored lines of flavour %s byte for byte (family %s: %zu own lines; %zu groups)\n",
760                        compiler_name().c_str(), g_flavour.c_str(), kFamily, std::strcmp(kFamily, "gcc") == 0 ? g_golden.size() : g_golden_own.size(),
761                        g_groups.size());
762            return 0;
763        }
764        std::istringstream a(stored), b(mine);
765        std::string la, lb;
766        int ln = 0;
767        while (true) {
768            const bool ha = (bool) std::getline(a, la), hb = (bool) std::getline(b, lb);
769            ++ln;
770            if (!ha && !hb) break;
771            if (!ha || !hb || la != lb) {
772                std::printf("quant_parity --regen-check: FAIL at flavour line %d:\n  stored:      %s\n  regenerated: %s\n", ln, ha ? la.c_str() : "(end)",
773                            hb ? lb.c_str() : "(end)");
774                break;
775            }
776        }
777        return 1;
778    }
779    if (g_golden_leg && only == nullptr)
780        for (const auto& kv : g_golden)   // every stored group of this flavour was met: a case that vanished does not pass silently
781            if (g_groups_by_key.find(kv.first) == g_groups_by_key.end()) fail("golden", "group \"" + kv.first + "\" of the golden file was not run");
782    if (g_golden_leg) {
783        std::printf("quant_parity: leg 2 (%s): %d rows differ from the ggml-cpu linked here (%s); that ggml differs from the golden reference in %zu groups%s",
784                    g_live_strict ? "FATAL" : "information", g_live_diff, compiler_name().c_str(), g_ref_moved.size(), g_ref_moved.empty() ? "\n" : ":");
785        for (size_t i = 0; i < g_ref_moved.size(); ++i) std::printf("%s %s", i ? "," : "", g_ref_moved[i].c_str());
786        if (!g_ref_moved.empty()) std::printf("\n");
787    }
788    std::printf("quant_parity: %d comparisons, %d golden group checks, %d failures -> %s\n", g_checked, g_group_checks, g_fail, g_fail ? (g_info_only ? "DIFFERENCES (information only)" : "FAIL") : "PASS");
789    return (g_fail && !g_info_only) ? 1 : 0;
790}