okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
8.0 KiB153 linesraw
1// src/kernels/iq_parity.cpp - plan v0.3 P6: the i-quant kernels against gguf-py on generated rows.
2//
3//     python tools/iq_fixture.py --out <dir> && build/iq_parity <dir>
4//
5// The fixtures are GENERATED (deterministic; TODO 24) - tools/iq_fixture.py writes each type's raw block
6// bytes and the gguf-py dequantized reference (Q2_0, this repository's type 42, is dequantized by
7// tools/gguf_writer.py's codec instead - gguf-py has no such type).  Dependencies: python3 with numpy and
8// the vendored gguf-py that setup downloads (the pinned llama.cpp zip; third_party/ is gitignored).
9//
10// What is compared, and how: the dequant parity is a MEASURED relative error (sum|got-ref| / sum|ref|) -
11// bitwise equality is not claimed and not required; on the generated fixtures it measures 0.00e+00.  The
12// MMVQ dot (q8_1 activations) must match the float matrix-vector product over that reference within the
13// activation rounding (a few 1e-3 relative), for 1 to 8 columns, every column of a multi-column call bitwise
14// equal to a one-column call on it.
15#define DPCT_PROFILING_ENABLED
16#include <sycl/sycl.hpp>
17#include <dpct/dpct.hpp>
18#include "strata/kernels/iq_kernels.hpp"
19#include "strata/kernels/native_mmvq.hpp"
20
21#include <cmath>
22#include <cstdio>
23#include <cstring>
24#include <random>
25#include <string>
26#include <vector>
27
28int main(int argc, char** argv) {
29    const std::string dir = argc > 1 ? argv[1] : "logs/iq_fixture";
30    const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"};
31    int failures = 0, missing = 0;
32    dpct::queue_ptr s;
33    s = dpct::get_current_device().create_queue(true);
34    for (const char* nm : names) {
35        std::FILE* f = std::fopen((dir + "/" + nm + ".bin").c_str(), "rb");
36        std::FILE* g = std::fopen((dir + "/" + nm + ".f32").c_str(), "rb");
37        if (!f || !g) {
38            std::printf("%-8s missing fixture: %s/%s.bin or %s/%s.f32 - generate the fixtures first with "
39                        "python tools/iq_fixture.py --out %s (deterministic; see the tool's --help)\n",
40                        nm, dir.c_str(), nm, dir.c_str(), nm, dir.c_str());
41            if (f) std::fclose(f);
42            if (g) std::fclose(g);
43            ++failures;
44            ++missing;
45            continue;
46        }
47        int hdr[3];
48        std::fread(hdr, 4, 3, f);
49        const int type = hdr[0], rows = hdr[1], cols = hdr[2];
50        std::vector<uint8_t> raw;
51        { uint8_t buf[1 << 16]; size_t n; while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) raw.insert(raw.end(), buf, buf + n); }
52        std::vector<float> ref((size_t) rows * cols);
53        std::fread(ref.data(), 4, ref.size(), g);
54        std::fclose(f);
55        std::fclose(g);
56        void* dw = nullptr;
57        float* dq = nullptr;
58        dw =
59            (void *)sycl::malloc_device(raw.size(), dpct::get_in_order_queue());
60        dq = (float *)sycl::malloc_device(ref.size() * 4,
61                                          dpct::get_in_order_queue());
62        /*
63        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
64        assuming in the original code the source host memory is pageable memory.
65        If the memory is not pageable, call wait() on event return by memcpy API
66        to ensure synchronization behavior.
67        */
68        (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dw, raw.data(), raw.size()).wait();
69        double dq_err = 0.0;
70        if (strata::kernels::iq_supported(type) && ((size_t) rows * cols) % 256 == 0) {
71            strata::kernels::iq_dequant_f32(type, dw, (int64_t) rows * cols, dq, s);
72            std::vector<float> got(ref.size());
73            (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
74                .memcpy(got.data(), dq, got.size() * 4)
75                .wait();
76            double num = 0, den = 0;
77            for (size_t i = 0; i < ref.size(); ++i) { num += std::fabs(got[i] - ref[i]); den += std::fabs(ref[i]); }
78            dq_err = num / (den + 1e-30);
79        }
80        // the dot, ncols 1..8: each column of an ncols call bitwise equal to a one-column call on it (the
81        // exact multi-column layout, the default), all of them within the activation rounding of the float product
82        const int MC = 8;
83        std::mt19937 rng(7);
84        std::normal_distribution<float> nd(0.f, 1.f);
85        std::vector<float> x((size_t) MC * cols);
86        for (auto& v : x) v = nd(rng);
87        float* dx = nullptr;
88        void* xq = nullptr;
89        float* dy = nullptr;
90        dx = (float *)sycl::malloc_device(x.size() * 4,
91                                          dpct::get_in_order_queue());
92        xq = (void *)sycl::malloc_device((size_t)MC * cols / 32 * 36,
93                                         dpct::get_in_order_queue());
94        dy = (float *)sycl::malloc_device((size_t)MC * rows * 4,
95                                          dpct::get_in_order_queue());
96        /*
97        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
98        assuming in the original code the source host memory is pageable memory.
99        If the memory is not pageable, call wait() on event return by memcpy API
100        to ensure synchronization behavior.
101        */
102        (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait();
103        strata::kernels::quantize_q8_1_rows(dx, MC, cols, xq, s);
104        std::vector<float> y((size_t) MC * rows), yn(y.size());
105        int multi_bad = 0;
106        try {
107            for (int c = 0; c < MC; ++c)
108                strata::kernels::native_mmvq(type, dw, (const uint8_t*) xq + (size_t) c * cols / 32 * 36,
109                                             dy + (size_t) c * rows, cols, rows, 1, s);
110            s->wait();
111            (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
112                .memcpy(y.data(), dy, y.size() * 4)
113                .wait();
114            for (int nc = 2; nc <= MC; ++nc) {
115                strata::kernels::native_mmvq(type, dw, xq, dy, cols, rows, nc, s);
116                s->wait();
117                (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
118                    .memcpy(yn.data(), dy, yn.size() * 4)
119                    .wait();
120                if (strata::kernels::native_mmvq_multi_exact() &&
121                    std::memcmp(yn.data(), y.data(), (size_t) nc * rows * 4) != 0) {
122                    std::printf("%-8s mmvq ncols %d: not bitwise equal to the one-column calls\n", nm, nc);
123                    ++multi_bad;
124                }
125            }
126        } catch (const std::exception& e) { std::printf("%-8s mmvq: %s\n", nm, e.what()); ++failures; continue; }
127        double num = 0, den = 0;
128        for (int c = 0; c < MC; ++c)
129            for (int r = 0; r < rows; ++r) {
130                double acc = 0;
131                for (int k = 0; k < cols; ++k) acc += (double) ref[(size_t) r * cols + k] * x[(size_t) c * cols + k];
132                num += std::fabs(y[(size_t) c * rows + r] - acc);
133                den += std::fabs(acc);
134            }
135        const double mm_err = num / (den + 1e-30);
136        const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;
137        std::printf("%-8s type %2d %4d x %5d  dequant rel %.2e  mmvq rel %.2e (ncols 1..%d)  %s\n", nm, type, rows, cols,
138                    dq_err, mm_err, MC, ok ? "ok" : "FAIL");
139        if (!ok) ++failures;
140        sycl::free(dw, dpct::get_in_order_queue());
141            sycl::free(dq, dpct::get_in_order_queue());
142            sycl::free(dx, dpct::get_in_order_queue());
143            sycl::free(xq, dpct::get_in_order_queue());
144            sycl::free(dy, dpct::get_in_order_queue());
145    }
146    std::printf("iq_parity: %d failures\n", failures);
147    // no fixture at all: the generator was skipped (no numpy / vendored gguf-py) - a skip (3), not a failure
148    if (missing == (int) (sizeof names / sizeof names[0])) {
149        std::printf("iq_parity: no fixtures in %s - skipped\n", dir.c_str());
150        return 3;
151    }
152    return failures ? 1 : 0;
153}