okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
15.4 KiB319 linesraw
1// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise.
2//
3//     build/mmvq_multi_parity
4//
5// WHY IT EXISTS.  `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`:
6//
7//     "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call"
8//
9// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window
10// produces what greedy decode would, bit for bit.  Nothing tested that sentence: `iq_parity` calls `native_mmvq`
11// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one
12// column and T columns.
13//
14// WHAT IT COMPARES.  The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j
15// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32").  The quantization is shared, so the only
16// thing under test is how the columns are laid out.
17//
18// THE DATA.  The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has
19// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in
20// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal
21// whatever operations produced it and proves nothing.  With finite scales and finite normal activations (the
22// precondition the header puts on the input) every output is finite, and a non-finite one fails the test.
23//
24// THE NEGATIVE CONTROL.  The same comparison with `multi_exact` off must find differences, or the test has no power
25// and its pass means nothing.  Where it has power depends on T: in `native_mmvq.cu` the generic layout uses
26// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the
27// exact layout at T <= 4.  So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is
28// reported as that coincidence rather than skipped.  The control needs a row long enough for the two layouts to
29// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8
30// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096.
31#define DPCT_PROFILING_ENABLED
32#include <sycl/sycl.hpp>
33#include <dpct/dpct.hpp>
34#include "strata/kernels/iq_kernels.hpp"
35#include "strata/kernels/native_mmvq.hpp"
36
37#include <cmath>
38#include <cstdint>
39#include <cstdio>
40#include <cstdlib>
41#include <string>
42#include <cstring>
43#include <random>
44#include <vector>
45
46namespace {
47
48struct Case {
49    const char* name;
50    int type;          // stable GGML type id, from the list in native_mmvq.hpp
51    int n_in;
52    int n_out;
53    int block_elems;   // elements per weight block
54    int block_bytes;
55    int scale_at[2];   // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none
56};
57
58// the types a head or a projection can have in this model
59const Case CASES[] = {
60    {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}},          // Q40Block: half d
61    {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}},          // Q80Block: half d
62    {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}},        // Q4KBlock: half2 dm
63    {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}},        // Q5KBlock: half2 dm
64    {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}},     // Q6KBlock: half d after ql, qh, scales
65    {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}},     // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL
66    {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}},
67};
68
69// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign
70uint16_t sane_half(std::mt19937& rng) {
71    const uint32_t r = rng();
72    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
73}
74
75// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ
76const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8};
77constexpr int COINCIDE_MAX_T = 4;
78
79bool ck(dpct::err0 e, const char *what) {
80    if (e == 0) return true;
81    /*
82    DPCT1009: SYCL reports errors using exceptions and does not use error
83    codes. Please replace the "get_error_string_dummy(...)" with a real
84    error-handling function.
85    */
86    std::printf("CUDA: %s: %s\n", what, dpct::get_error_string_dummy(e));
87    return false;
88}
89
90// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on
91// outputs that are finite in both paths.
92long long compare(const Case &c, int T, dpct::queue_ptr s, long long &nonfinite,
93                  long long &diff_finite, bool &ran) try {
94    ran = false;
95    if (!strata::kernels::native_mmvq_supported(c.type)) return -1;
96
97    const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out);
98    const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1);   // Q8_1 bytes of ONE column
99    const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T);
100    if (qall != qcol * (std::size_t) T) {
101        std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test "
102                    "assumes contiguous columns and they are not\n", c.name, T, qall, qcol);
103        return -1;
104    }
105
106    std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T);
107    std::vector<uint8_t> w(wbytes);
108    for (auto& b : w) b = (uint8_t) (rng() & 0xff);
109    const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems);
110    if (n_blocks * (std::size_t) c.block_bytes != wbytes) {
111        std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name,
112                    T, n_blocks, c.block_bytes, wbytes);
113        return -1;
114    }
115    for (std::size_t k = 0; k < n_blocks; ++k)
116        for (int at : c.scale_at)
117            if (at >= 0) {
118                const uint16_t h = sane_half(rng);
119                std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2);
120            }
121    std::vector<float> x((std::size_t) T * c.n_in);
122    std::normal_distribution<float> nd(0.f, 1.f);
123    for (auto& v : x) v = nd(rng);
124
125    void* dw = nullptr;
126    void* xq = nullptr;
127    float* dx = nullptr;
128    float* dmulti = nullptr;
129    float* dsingle = nullptr;
130    const std::size_t ybytes = (std::size_t) T * c.n_out * 4;
131    if (!ck(DPCT_CHECK_ERROR(dw = (void *)sycl::malloc_device(
132                                 wbytes, dpct::get_in_order_queue())),
133            "malloc w") ||
134        !ck(DPCT_CHECK_ERROR(xq = (void *)sycl::malloc_device(
135                                 qall, dpct::get_in_order_queue())),
136            "malloc xq") ||
137        !ck(DPCT_CHECK_ERROR(dx = (float *)sycl::malloc_device(
138                                 x.size() * 4, dpct::get_in_order_queue())),
139            "malloc x") ||
140        !ck(DPCT_CHECK_ERROR(dmulti = (float *)sycl::malloc_device(
141                                 ybytes, dpct::get_in_order_queue())),
142            "malloc multi") ||
143        !ck(DPCT_CHECK_ERROR(dsingle = (float *)sycl::malloc_device(
144                                 ybytes, dpct::get_in_order_queue())),
145            "malloc single"))
146        return -1;
147    /*
148    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
149    in the original code the source host memory is pageable memory. If the
150    memory is not pageable, call wait() on event return by memcpy API to ensure
151    synchronization behavior.
152    */
153    if (!ck(DPCT_CHECK_ERROR(
154                (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dw, w.data(), wbytes).wait()),
155            "copy w") ||
156        /*
157        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
158        assuming in the original code the source host memory is pageable memory.
159        If the memory is not pageable, call wait() on event return by memcpy API
160        to ensure synchronization behavior.
161        */
162        !ck(DPCT_CHECK_ERROR(
163                (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
164            "copy x"))
165        return -1;
166
167    // ONE quantization, shared by both paths: the quantization is not under test
168    strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s);
169    if (!ck(DPCT_CHECK_ERROR(s->wait()), "quantize")) return -1;
170
171    try {
172        strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s);
173        for (int j = 0; j < T; ++j)
174            strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol,
175                                         dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s);
176    } catch (const std::exception& e) {
177        std::printf("%-12s T=%d: %s\n", c.name, T, e.what());
178        return -1;
179    }
180    if (!ck(DPCT_CHECK_ERROR(s->wait()), "mmvq")) return -1;
181
182    std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size());
183    if (!ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
184                                 .memcpy(a.data(), dmulti, ybytes)
185                                 .wait()),
186            "read multi") ||
187        !ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
188                                 .memcpy(b.data(), dsingle, ybytes)
189                                 .wait()),
190            "read single"))
191        return -1;
192
193    long long diff = 0;
194    nonfinite = 0;
195    diff_finite = 0;
196    for (std::size_t i = 0; i < a.size(); ++i) {
197        float fa, fb;
198        std::memcpy(&fa, &a[i], 4);
199        std::memcpy(&fb, &b[i], 4);
200        const bool both_finite = std::isfinite(fa) && std::isfinite(fb);
201        if (!both_finite) ++nonfinite;
202        if (a[i] != b[i]) {
203            ++diff;
204            if (both_finite) ++diff_finite;
205        }
206    }
207    sycl::free(dw, dpct::get_in_order_queue());
208        sycl::free(xq, dpct::get_in_order_queue());
209        sycl::free(dx, dpct::get_in_order_queue());
210        sycl::free(dmulti, dpct::get_in_order_queue());
211        sycl::free(dsingle, dpct::get_in_order_queue());
212    ran = true;
213    return diff;
214}
215catch (sycl::exception const &exc) {
216  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
217            << ", line:" << __LINE__ << std::endl;
218  std::exit(1);
219}
220
221struct Totals {
222    long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0;   // all widths
223    long long diff_finite_wide = 0;                                     // T > COINCIDE_MAX_T only
224    int powerless_cases = 0;   // cases where the control found no difference at any T > COINCIDE_MAX_T
225};
226
227int sweep(bool exact, dpct::queue_ptr s, Totals &t) {
228    strata::kernels::native_mmvq_set_multi_exact(exact);
229    if (strata::kernels::native_mmvq_multi_exact() != exact) {
230        std::printf("native_mmvq_multi_exact() does not reflect what was set\n");
231        return 1;
232    }
233    std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)");
234    std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite");
235    int bad = 0;
236    for (const Case& c : CASES) {
237        long long case_wide = 0;
238        for (int T : WIDTHS) {
239            long long nf = 0, dfin = 0;
240            bool ran = false;
241            const long long diff = compare(c, T, s, nf, dfin, ran);
242            if (!ran) { ++bad; continue; }
243            const long long n = (long long) T * c.n_out;
244            t.checked += n;
245            t.diff += diff;
246            t.diff_finite += dfin;
247            t.nonfinite += nf;
248            if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; }
249            const char* verdict;
250            if (exact) verdict = diff == 0 ? "ok" : "FAIL";
251            else if (dfin > 0) verdict = "control sees it";
252            else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T";
253            std::printf("%-12s %3d %10lld %10lld %14lld %10lld  %s\n", c.name, T, n, diff, dfin, nf, verdict);
254            if (exact && diff != 0) ++bad;
255        }
256        if (!exact && case_wide == 0) ++t.powerless_cases;
257    }
258    return bad;
259}
260
261}  // namespace
262
263int main() try {
264    dpct::queue_ptr s;
265    if (!ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),
266            "stream create")) return 1;
267
268    Totals on, off;
269    const int bad = sweep(true, s, on);
270    const int bad_off = sweep(false, s, off);
271    strata::kernels::native_mmvq_set_multi_exact(true);   // back to the default
272
273    std::printf("\nmulti_exact on:   %lld outputs compared, %lld differ bitwise, %lld non-finite\n",
274                on.checked, on.diff, on.nonfinite);
275    std::printf("multi_exact off:  %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n",
276                off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T);
277
278    if (on.nonfinite != 0 || off.nonfinite != 0) {
279        std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the "
280                    "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite);
281        return 1;
282    }
283    if (bad != 0 || bad_off != 0) {
284        std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls "
285                    "or did not run, %d case(s) did not run with it off. If they differ, the sentence in "
286                    "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n",
287                    bad, bad_off);
288        return 1;
289    }
290    // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one,
291    // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing.
292#if defined(STRATA_HIP_GFX906)
293    // gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact
294    // has nothing to switch and the control cannot see a difference.  The control with power is the CUDA layout:
295    // ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0.
296    if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) {
297        std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, "
298                    "so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n");
299        return 0;
300    }
301#endif
302    if (off.powerless_cases != 0) {
303        std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at "
304                    "any T > %d, where the generic layout is not the exact one: for those cases this comparison "
305                    "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases,
306                    COINCIDE_MAX_T);
307        return 1;
308    }
309    std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column "
310                "call; with it off the control finds differences at T > %d in every case, so the comparison has "
311                "power.\n",
312                COINCIDE_MAX_T);
313    return 0;
314}
315catch (sycl::exception const &exc) {
316  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
317            << ", line:" << __LINE__ << std::endl;
318  std::exit(1);
319}