okami.mom/strata

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

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

main
40.0 KiB754 linesraw
1// src/kernels/s_gemv_parity.cpp - P2.S2's parity test for the S-family GEMV.
2//
3// Four source types, chosen to cover every branch the kernel has:
4//
5//   S2  Q2_0   2-bit, bias  -1, group 64   affine
6//   S4  Q4_0   4-bit, bias  -8, group 32   affine
7//   S4  IQ4_NL 4-bit, bias   0, group 32   CODEBOOK  (non-linear, no bias can express it)
8//   S8  Q8_0   8-bit, bias -128, group 32  affine
9//
10// That is all three template instantiations, both codebooks, and four different biases.  The offset branch
11// (`has_offset`, only Q4_K and Q5_K) is NOT exercised here and the test prints that fact rather than leaving a
12// green result to imply otherwise - Q4_K's canonicalisation needs the packed 6-bit scale/min pairs, and the
13// honest move is to say so than to half-build it.
14//
15// THE REFERENCE IS THE CHAIN: for each type the CPU side reconstructs the RAW GGUF block from the canonical
16// planes and decodes it with that type's scalar dequantizer from include/strata/artifact/dequant.hpp - the
17// ones `bench/micro/dequant_xcheck` checks against **ggml's own** dequantizers.  Reconstructing raw from
18// canonical is the inverse of what the packer does, and it is written here independently of the packer so the
19// two are not the same code.
20#define DPCT_PROFILING_ENABLED
21#include <sycl/sycl.hpp>
22#include <dpct/dpct.hpp>
23#include "strata/artifact/dequant.hpp"
24#include "strata/kernels/s_gemv.hpp"
25
26#include <cmath>
27#include <cstdint>
28#include <cstdio>
29#include <cstring>
30#include <algorithm>
31#include <chrono>
32#include <random>
33#include <string>
34#include <vector>
35
36namespace {
37
38void check(dpct::err0 e, const char *what) {
39}
40
41// Finite, exactly representable fp16 patterns WITH full mantissas.  Not powers of two: with only powers of
42// two every product is exact and the comparison cannot round, which is how the first version of s2_gemv's test
43// managed a worst error of exactly zero without proving anything.
44const uint16_t kScales[] = {0x3E00, 0x3555, 0x3C01, 0x4248, 0x4123, 0x2AAA, 0x4A2B, 0x3800,
45                            0xBE00, 0xB555, 0xC248, 0x2AAB, 0x4A2C, 0x2AAB, 0xB800};
46
47struct Case {
48    const char* name;
49    strata::kernels::SForm form;
50    int raw_bytes;        // one block
51    // Reconstruct the raw GGUF block for one group from the canonical codes/scales, and return the number of
52    // elements the block decodes to (which may exceed group_elems: Q8_0's block IS one group, Q2_0's too).
53    int (*to_raw)(const uint8_t* codes, size_t code_off, const uint16_t* scale_bits, size_t scale_off, uint8_t* raw);
54    double (*dequant)(const uint8_t* raw, float* out);
55};
56
57// ---- Q2_0: raw = { fp16 d ; uint8 qs[16] }, 64 elements, code i at byte i/4 bits (i%4)*2 - identical to the
58// canonical plane, so this is a straight copy plus the scale.
59int q2_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) {
60    const uint16_t d = scale_bits[so];
61    raw[0] = (uint8_t) (d & 0xFF);
62    raw[1] = (uint8_t) (d >> 8);
63    // `codes` is one code PER ELEMENT (64 of them); a Q2_0 block stores them PACKED, 4 per byte, element i at
64    // byte i/4 bits (i%4)*2.  The two coincide as a byte layout only if you confuse them, which is exactly the
65    // mistake the first version of this function made by copying 16 bytes verbatim.
66    for (int b = 0; b < 16; ++b) {
67        raw[2 + b] = (uint8_t) ((codes[co + 4 * b + 0] & 3) | ((codes[co + 4 * b + 1] & 3) << 2) |
68                                ((codes[co + 4 * b + 2] & 3) << 4) | ((codes[co + 4 * b + 3] & 3) << 6));
69    }
70    return 64;
71}
72double q2_0_deq(const uint8_t* raw, float* out) {
73    strata::dequantize_q2_0(raw, out);
74    return 64;
75}
76
77// ---- Q4_0: raw = { fp16 d ; uint8 qs[16] }, 32 elements; element j is the LOW nibble of byte j and element
78// j+16 the HIGH nibble.  The canonical plane stores one code per element, so this re-packs them.
79int q4_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) {
80    const uint16_t d = scale_bits[so];
81    raw[0] = (uint8_t) (d & 0xFF);
82    raw[1] = (uint8_t) (d >> 8);
83    for (int j = 0; j < 16; ++j) raw[2 + j] = (uint8_t) ((codes[co + j] & 0x0F) | (codes[co + 16 + j] << 4));
84    return 32;
85}
86double q4_0_deq(const uint8_t* raw, float* out) {
87    strata::dequantize_q4_0(raw, out);
88    return 32;
89}
90
91// ---- IQ4_NL: identical packing to Q4_0, different decode (a table, not a bias).
92int iq4_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) {
93    return q4_0_to_raw(codes, co, scale_bits, so, raw);
94}
95double iq4_deq(const uint8_t* raw, float* out) {
96    strata::dequantize_iq4_nl(raw, out);
97    return 32;
98}
99
100// ---- Q8_0: raw = { fp16 d ; int8 qs[32] }, 32 elements.  The canonical code plane is UNSIGNED with bias
101// -128 (round 154's fix), so the raw int8 byte is exactly the canonical code reinterpreted - a straight copy,
102// which is why this type is the cheapest one to check and the one whose sign bug was found by the pack.
103int q8_0_to_raw(const uint8_t* codes, size_t co, const uint16_t* scale_bits, size_t so, uint8_t* raw) {
104    const uint16_t d = scale_bits[so];
105    raw[0] = (uint8_t) (d & 0xFF);
106    raw[1] = (uint8_t) (d >> 8);
107    // NOT a straight copy.  The canonical code plane is UNSIGNED with bias -128, so canonical code c means the
108    // value (c - 128); the raw block stores that as an `int8_t`, whose reinterpretation as an unsigned byte is
109    // `c ^ 0x80` - a SIGN-BIT FLIP, not the identity.  Assuming identity is the same family of mistake as the
110    // round-154 Q8_0 bug that the pack found, and it is why this reconstruction is written out rather than
111    // memcpy'd.
112    for (int j = 0; j < 32; ++j) raw[2 + j] = (uint8_t) (codes[co + j] ^ 0x80);
113    return 32;
114}
115double q8_0_deq(const uint8_t* raw, float* out) {
116    strata::dequantize_q8_0(raw, out);
117    return 32;
118}
119
120// ---- S4/Q4_K: the ONLY canonical form with an offset, and the only one whose scale is an FP32 PRODUCT
121// (`fl(d*sc)`) rather than a widened fp16.  Both facts make it the case worth having.
122//
123// There is no `to_raw` for it in the table above because its canonical planes are DERIVED from the raw
124// parameters, not the other way round: the packer computes `scale = d*sc` and `offset = -(dmin*m)`, so this
125// generates d, dmin and the eight (sc, m) pairs, derives the planes exactly as the packer does, and writes a
126// raw block from the SAME parameters.  Inverting those products instead would be ambiguous.
127void test_q4k(long long n_in, long long n_out, double tol, int* total_bad) {
128    using strata::kernels::Codebook;
129    using strata::kernels::SForm;
130    const SForm form{4, 0, 32, Codebook::Affine, true};
131
132    std::mt19937 rng(777);
133    const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0]));
134    const long long n_groups = n_in / 32;
135    const long long codes_per_row = n_in / 2;
136
137    std::vector<uint16_t> x((size_t) n_in);
138    for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales];
139
140    std::vector<uint8_t> codes_el((size_t) n_out * n_in);
141    for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & 0x0F);
142    std::vector<uint8_t> codes((size_t) n_out * codes_per_row, 0);
143    for (size_t i = 0; i < codes_el.size(); ++i) {
144        const size_t o = i / (size_t) n_in, k = i % (size_t) n_in;
145        codes[o * (size_t) codes_per_row + k / 2] |= (uint8_t) (codes_el[i] << ((k % 2) * 4));
146    }
147    std::vector<float> scales((size_t) n_out * n_groups), offsets((size_t) n_out * n_groups);
148
149    struct Row {
150        uint16_t d, dmin;
151        uint8_t sc[8], m[8];
152    };
153    std::vector<Row> rows((size_t) n_out);
154    for (long long o = 0; o < n_out; ++o) {
155        Row& r = rows[(size_t) o];
156        r.d = kScales[rng() % n_scales];
157        r.dmin = kScales[rng() % n_scales];
158        for (int g = 0; g < 8; ++g) {
159            r.sc[g] = (uint8_t) (rng() & 0x3F);
160            r.m[g] = (uint8_t) (rng() & 0x3F);
161            for (long long sb = 0; sb < n_in / 256; ++sb) {
162                scales[(size_t) (o * n_groups + sb * 8 + g)] = strata::fp16_to_fp32(r.d) * (float) r.sc[g];
163                offsets[(size_t) (o * n_groups + sb * 8 + g)] = -(strata::fp16_to_fp32(r.dmin) * (float) r.m[g]);
164            }
165        }
166    }
167
168    std::vector<float> ref((size_t) n_out, 0.0f);
169    std::vector<double> cond((size_t) n_out, 0.0);
170    double worst_plane_ref = 0.0;   // max |planes - raw block| over every element, on the CPU alone
171    std::vector<uint8_t> blk(144);
172    std::vector<float> dec(256);
173    // A Q4_K raw block covers 256 elements, so a 2560-element row is TEN superblocks, each with its own
174    // 144-byte block.  The first version of this loop ran `step < 4` - one superblock, 256 of the row's 2560
175    // elements - while the kernel accumulated all of them, and the resulting 29x relative error was the
176    // reference being short, not the kernel being wrong.
177    for (long long o = 0; o < n_out; ++o) {
178        const Row& r = rows[(size_t) o];
179        float acc = 0.0f;
180        double sum_abs = 0.0;      // the natural scale of this row's dot product (see the metric below)
181        double plane_ref_diff = 0.0;   // (a) vs (b): planes against the raw block, both on the CPU
182        for (long long sb = 0; sb < n_in / 256; ++sb) {
183            // ONE 144-byte block per 256-element SUPERBLOCK, with all four steps' qs bytes filled BEFORE the
184            // decode.  The previous version decoded a fresh block per STEP and then read all 256 elements
185            // from each, so three quarters of every decode came from zeroed qs - four decodes of a
186            // quarter-filled block per superblock, which is the whole of the 1.17e4 disagreement.
187            // `scripts/probe_q4k_groups.cpp` builds it this way and agrees exactly, group by group.
188            blk.assign(144, 0);
189            blk[0] = (uint8_t) (r.d & 0xFF);
190            blk[1] = (uint8_t) (r.d >> 8);
191            blk[2] = (uint8_t) (r.dmin & 0xFF);
192            blk[3] = (uint8_t) (r.dmin >> 8);
193            for (int j = 0; j < 4; ++j) {          // the exact inverse of get_scale_min_k4
194                blk[4 + j] = (uint8_t) ((r.sc[j] & 0x3F) | ((r.sc[j + 4] >> 4) << 6));
195                blk[8 + j] = (uint8_t) ((r.m[j] & 0x3F) | ((r.m[j + 4] >> 4) << 6));
196                blk[12 + j] = (uint8_t) ((r.sc[j + 4] & 0x0F) | ((r.m[j + 4] & 0x0F) << 4));
197            }
198            for (int step = 0; step < 4; ++step) {
199                for (int l = 0; l < 32; ++l) {     // elements 0..31 LOW nibbles, 32..63 HIGH
200                    const long long e0 = o * n_in + sb * 256 + step * 64 + l;
201                    const long long e1 = e0 + 32;
202                    blk[16 + step * 32 + l] =
203                        (uint8_t) ((codes_el[(size_t) e0] & 0x0F) | (codes_el[(size_t) e1] << 4));
204                }
205            }
206            strata::dequantize_q4_K(blk.data(), dec.data());
207            for (int j = 0; j < 256; ++j) {
208                const float term = dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (sb * 256 + j)]);
209                acc += term;
210                sum_abs += std::fabs((double) term);      // the CONDITION of this dot product
211
212                // THE THIRD DECODE.  (a) the raw block through the scalar dequantizer, (b) the canonical
213                // PLANES through `code*scale + offset`, (c) the GPU.  If (a) != (b) then this test built
214                // planes that disagree with its own raw block and the kernel is innocent; if (a) == (b) and
215                // (c) differs, the kernel is wrong.  Without (b) there is no way to tell which.
216                const long long elem = sb * 256 + j;
217                const long long g = elem / 32;
218                const int code = (int) codes_el[(size_t) (o * n_in + elem)];
219                const float b_dec = (float) code * scales[(size_t) (o * n_groups + g)] +
220                                    offsets[(size_t) (o * n_groups + g)];
221                if (std::fabs((double) (b_dec - dec[(size_t) j])) > plane_ref_diff) {
222                    plane_ref_diff = std::fabs((double) (b_dec - dec[(size_t) j]));
223                }
224            }
225        }
226        ref[(size_t) o] = acc;
227        cond[(size_t) o] = sum_abs;
228        if (!(plane_ref_diff <= worst_plane_ref)) worst_plane_ref = plane_ref_diff;
229    }
230
231    uint16_t* d_x = nullptr;
232    uint8_t* d_codes = nullptr;
233    float *d_scales = nullptr, *d_offsets = nullptr, *d_y = nullptr;
234    check(DPCT_CHECK_ERROR(d_x = sycl::malloc_device<uint16_t>(
235                               x.size(), dpct::get_in_order_queue())),
236          "cudaMalloc x");
237    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
238                               codes.size(), dpct::get_in_order_queue())),
239          "cudaMalloc codes");
240    check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
241                               scales.size(), dpct::get_in_order_queue())),
242          "cudaMalloc scales");
243    check(DPCT_CHECK_ERROR(d_offsets = sycl::malloc_device<float>(
244                               offsets.size(), dpct::get_in_order_queue())),
245          "cudaMalloc offsets");
246    check(DPCT_CHECK_ERROR(d_y = sycl::malloc_device<float>(
247                               (size_t)n_out, dpct::get_in_order_queue())),
248          "cudaMalloc y");
249    /*
250    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
251    in the original code the source host memory is pageable memory. If the
252    memory is not pageable, call wait() on event return by memcpy API to ensure
253    synchronization behavior.
254    */
255    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
256              d_x, x.data(), x.size() * sizeof(uint16_t)).wait()),
257          "copy x");
258    /*
259    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
260    in the original code the source host memory is pageable memory. If the
261    memory is not pageable, call wait() on event return by memcpy API to ensure
262    synchronization behavior.
263    */
264    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
265              d_codes, codes.data(), codes.size()).wait()),
266          "copy codes");
267    /*
268    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
269    in the original code the source host memory is pageable memory. If the
270    memory is not pageable, call wait() on event return by memcpy API to ensure
271    synchronization behavior.
272    */
273    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
274              d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
275          "copy scales");
276    /*
277    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
278    in the original code the source host memory is pageable memory. If the
279    memory is not pageable, call wait() on event return by memcpy API to ensure
280    synchronization behavior.
281    */
282    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
283              d_offsets, offsets.data(), offsets.size() * sizeof(float)).wait()),
284          "copy offsets");
285    strata::kernels::s_gemv(d_x, d_codes, d_scales, d_offsets, d_y, n_in, n_out, form);
286    std::vector<float> got((size_t) n_out);
287    check(DPCT_CHECK_ERROR(
288              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
289                  .memcpy(got.data(), d_y, got.size() * sizeof(float))
290                  .wait()),
291          "copy back");
292
293    // THE ERROR IS MEASURED AGAINST sum|term|, NOT AGAINST THE RESULT.  A dot product of 2560 signed terms
294    // cancels, so `|ref-got| / |ref|` is a statement about the condition number, not about the kernel: a row
295    // whose terms are ~1e7 and whose result is ~1e3 reports a relative error of 50 for an absolute error of
296    // 1e-6 of the terms.  `sum_abs` is the natural scale of the computation, and comparing to it is what
297    // makes a tolerance mean "agrees to within rounding" instead of "did not cancel".
298    long long bad = 0;
299    double worst = 0.0, worst_res = 0.0;
300    for (long long o = 0; o < n_out; ++o) {
301        const double a = ref[(size_t) o], b = got[(size_t) o];
302        const double scale = cond[(size_t) o] > 1e-30 ? cond[(size_t) o] : 1e-30;
303        const double rel = std::fabs(a - b) / scale;
304        const double rel_res = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
305        if (!(rel <= worst)) worst = rel;
306        if (!(rel_res <= worst_res)) worst_res = rel_res;
307        if (!(rel <= tol)) ++bad;
308    }
309    double lo = ref[0], hi = ref[0];
310    for (float v : ref) {
311        lo = std::fmin(lo, v);
312        hi = std::fmax(hi, v);
313    }
314    std::printf("  %-10s %lld rows, %lld over tol, worst rel-to-terms %.3e (rel-to-result %.3e)\n",
315                "S4/Q4_K", n_out, bad, worst, worst_res);
316    std::printf("             ref spread [%.4g, %.4g], condition (sum|term|) up to %.4g\n", lo, hi,
317                *std::max_element(cond.begin(), cond.end()));
318    std::printf("             CPU planes vs CPU raw block: max |diff| = %.3e -> %s\n", worst_plane_ref,
319                worst_plane_ref == 0.0
320                    ? "the test is SELF-CONSISTENT"
321                    : "*** THE TEST DISAGREES WITH ITSELF - fix the reference before believing any GPU result ***");
322    if (hi - lo <= 0.0) {
323        std::fprintf(stderr, "VACUOUS: S4/Q4_K reference is constant\n");
324        std::exit(1);
325    }
326    *total_bad += (int) bad;
327    sycl::free(d_x, dpct::get_in_order_queue());
328    sycl::free(d_codes, dpct::get_in_order_queue());
329    sycl::free(d_scales, dpct::get_in_order_queue());
330    sycl::free(d_offsets, dpct::get_in_order_queue());
331    sycl::free(d_y, dpct::get_in_order_queue());
332}
333
334}  // namespace
335
336
337// ------------------------------------------------------------------ benchmark
338//
339// P2.S10 wants a first measurement and a ledger entry, and the objective is stated in tokens per second, so
340// the useful output is not GiB/s but "milliseconds of expert matvec per token".  Warm-up runs are discarded
341// (the first launch pays module load and page faults) and the MINIMUM is reported alongside the mean, because
342// the minimum is the one not polluted by another process on the machine.
343void bench_s2_gemv(long long n_in, long long n_out, int iters, int* split_bad) {
344    using strata::kernels::Codebook;
345    using strata::kernels::SForm;
346    const SForm form{2, -1, 64, Codebook::Affine, false};
347    const long long n_groups = n_in / 64;
348    const long long codes_per_row = n_in / 4;
349
350    std::vector<uint8_t> codes((size_t) n_out * codes_per_row, 0xA5);
351    std::vector<float> scales((size_t) n_out * n_groups, 0.001f);
352    std::vector<uint16_t> x((size_t) n_in, 0x3C00);            // 1.0 in fp16
353
354    uint16_t* d_x = nullptr;
355    uint8_t* d_codes = nullptr;
356    float *d_scales = nullptr, *d_y = nullptr;
357    check(DPCT_CHECK_ERROR(d_x = sycl::malloc_device<uint16_t>(
358                               x.size(), dpct::get_in_order_queue())),
359          "bench x");
360    check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
361                               codes.size(), dpct::get_in_order_queue())),
362          "bench codes");
363    check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
364                               scales.size(), dpct::get_in_order_queue())),
365          "bench scales");
366    check(DPCT_CHECK_ERROR(d_y = sycl::malloc_device<float>(
367                               (size_t)n_out, dpct::get_in_order_queue())),
368          "bench y");
369    /*
370    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
371    in the original code the source host memory is pageable memory. If the
372    memory is not pageable, call wait() on event return by memcpy API to ensure
373    synchronization behavior.
374    */
375    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
376              d_x, x.data(), x.size() * sizeof(uint16_t)).wait()),
377          "bench copy x");
378    /*
379    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
380    in the original code the source host memory is pageable memory. If the
381    memory is not pageable, call wait() on event return by memcpy API to ensure
382    synchronization behavior.
383    */
384    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
385              d_codes, codes.data(), codes.size()).wait()),
386          "bench copy codes");
387    /*
388    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
389    in the original code the source host memory is pageable memory. If the
390    memory is not pageable, call wait() on event return by memcpy API to ensure
391    synchronization behavior.
392    */
393    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
394              d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
395          "bench copy scales");
396
397    for (int i = 0; i < 3; ++i) strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form);
398
399    std::vector<double> ms;
400    for (int i = 0; i < iters; ++i) {
401        const auto t0 = std::chrono::steady_clock::now();
402        strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form);
403        const auto t1 = std::chrono::steady_clock::now();
404        ms.push_back(std::chrono::duration<double, std::milli>(t1 - t0).count());
405    }
406    std::sort(ms.begin(), ms.end());
407    double mean = 0;
408    for (double v : ms) mean += v;
409    mean /= (double) ms.size();
410
411    const double weights = (double) n_in * (double) n_out;
412    const double bytes = (double) n_out * (double) codes_per_row + (double) n_out * n_groups * 4.0;
413    std::printf("s2_gemv bench  [%lld x %lld]  %d iters\n", n_in, n_out, iters);
414    std::printf("  ms per gemv: min %.4f  median %.4f  mean %.4f\n", ms.front(), ms[ms.size() / 2], mean);
415    std::printf("  min -> %.1f G weights/s, %.1f GiB/s of S2 streamed\n", weights / ms.front() / 1e6,
416                bytes / (1024.0 * 1024 * 1024) / (ms.front() / 1000.0));
417
418    // The projection the objective is stated against: 48 layers x 10 experts x 3 roles, all of one token's
419    // experts, at the measured per-role rate.  This is the VRAM-resident path only - the CPU expert path and
420    // the KV/attention work are separate and are NOT included.
421    const double roles_per_token = 48.0 * 10.0 * 3.0;
422    const double tok_ms = roles_per_token * ms.front();
423    std::printf("  per token: %.0f roles x %.4f ms = %.1f ms  ->  %.1f tok/s (expert matvec only)\n",
424                roles_per_token, ms.front(), tok_ms, tok_ms > 0 ? 1000.0 / tok_ms : 0.0);
425    std::printf("  NOTE: expert matvec ONLY. No attention, no KV, no norm, no router, no sampling, and it\n"
426                "        assumes every expert is already resident in VRAM at zero cost.\n");
427
428    // The NAIVE kernel's output is the reference for the split one.  `s_gemv` is checked against the scalar
429    // dequantizer by this file's parity cases, so its result here is a validated value, and the split kernel
430    // sums in a different order - so this is a relative comparison, not bit equality.
431    strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form);
432    std::vector<float> ref_naive((size_t) n_out);
433    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
434                               .memcpy(ref_naive.data(), d_y,
435                                       ref_naive.size() * sizeof(float))
436                               .wait()),
437          "copy naive reference");
438
439    // ---- the row-split variant, same planes, same process -------------------
440    // Swept rather than guessed: more threads per row buys parallelism and costs a deeper reduction.
441    for (int tpr : {32, 64, 128, 256}) {
442        if (tpr > n_in) continue;
443        for (int i = 0; i < 3; ++i) {
444            strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr);
445        }
446        std::vector<double> sms;
447        for (int i = 0; i < iters; ++i) {
448            const auto t0 = std::chrono::steady_clock::now();
449            strata::kernels::s_gemv_split(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, form, tpr);
450            sms.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
451                              .count());
452        }
453        std::sort(sms.begin(), sms.end());
454
455        // correctness of the thing being timed
456        std::vector<float> got((size_t) n_out);
457        check(DPCT_CHECK_ERROR(
458                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
459                      .memcpy(got.data(), d_y, got.size() * sizeof(float))
460                      .wait()),
461              "copy split result");
462        long long bad = 0;
463        double worst = 0.0;
464        for (long long o = 0; o < n_out; ++o) {
465            const double a = ref_naive[(size_t) o], b = got[(size_t) o];
466            const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
467            if (!(rel <= worst)) worst = rel;
468            if (!(rel <= 1e-4)) ++bad;
469        }
470        if (bad) {
471            std::printf("  split tpr=%-4d *** WRONG *** %lld of %lld rows differ, worst rel %.3e\n", tpr,
472                        bad, n_out, worst);
473            *split_bad += (int) bad;
474        }
475
476        // ---- the quad-amortised S2 kernel, timed AND checked against the naive reference ----
477        // Only meaningful for S2: it assumes four elements share one code byte, which is true of 2-bit codes.
478        if (form.code_bits == 2 && (n_in % 64) == 0) {
479            for (int t2 : {32, 64, 128}) {
480                for (int i = 0; i < 3; ++i) {
481                    strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2);
482                }
483                std::vector<double> qms;
484                for (int i = 0; i < iters; ++i) {
485                    const auto q0 = std::chrono::steady_clock::now();
486                    strata::kernels::s2_gemv_quads(d_x, d_codes, d_scales, d_y, n_in, n_out, t2);
487                    qms.push_back(std::chrono::duration<double, std::milli>(
488                                      std::chrono::steady_clock::now() - q0).count());
489                }
490                std::sort(qms.begin(), qms.end());
491                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
492                                           .memcpy(got.data(), d_y,
493                                                   got.size() * sizeof(float))
494                                           .wait()),
495                      "copy quads result");
496                long long qbad = 0;
497                double qworst = 0.0;
498                for (long long o = 0; o < n_out; ++o) {
499                    const double a = ref_naive[(size_t) o], b = got[(size_t) o];
500                    const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
501                    if (rel > qworst) qworst = rel;
502                    if (!(rel <= 1e-4)) ++qbad;
503                }
504                if (qbad) *split_bad += (int) qbad;
505                std::printf("  quads tpr=%-4d min %.4f ms  -> %6.1f G weights/s   vs naive %.2fx   %s\n", t2,
506                            qms.front(), weights / qms.front() / 1e6, ms.front() / qms.front(),
507                            qbad ? "*** WRONG ***" : "checked ok");
508            }
509        }
510
511        // ---- the two-lever kernel, both configurations, timed AND checked ----
512        if (form.code_bits == 2 && (n_in % 64) == 0) {
513            for (int staged = 0; staged < 2; ++staged) {
514                for (int t3 : {32, 64, 128}) {
515                    for (int i = 0; i < 3; ++i) {
516                        strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0);
517                    }
518                    std::vector<double> fms;
519                    for (int i = 0; i < iters; ++i) {
520                        const auto q0 = std::chrono::steady_clock::now();
521                        strata::kernels::s2_gemv_fast(d_x, d_codes, d_scales, d_y, n_in, n_out, t3, staged != 0);
522                        fms.push_back(std::chrono::duration<double, std::milli>(
523                                          std::chrono::steady_clock::now() - q0).count());
524                    }
525                    std::sort(fms.begin(), fms.end());
526                    check(
527                        DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
528                                             .memcpy(got.data(), d_y,
529                                                     got.size() * sizeof(float))
530                                             .wait()),
531                        "copy fast result");
532                    long long fbad = 0;
533                    for (long long o = 0; o < n_out; ++o) {
534                        const double a = ref_naive[(size_t) o], b = got[(size_t) o];
535                        const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
536                        if (!(rel <= 1e-4)) ++fbad;
537                    }
538                    if (fbad) *split_bad += (int) fbad;
539                    std::printf("  fast %s tpr=%-4d min %.4f ms  -> %6.1f G weights/s   vs naive %.2fx   %s\n",
540                                staged ? "staged" : "global", t3, fms.front(),
541                                weights / fms.front() / 1e6, ms.front() / fms.front(),
542                                fbad ? "*** WRONG ***" : "checked ok");
543                }
544            }
545        }
546
547        const double sp = ms.front() / sms.front();
548        std::printf("  split tpr=%-4d min %.4f ms  -> %6.1f G weights/s   speedup vs naive %.2fx\n", tpr,
549                    sms.front(), weights / sms.front() / 1e6, sp);
550    }
551
552    sycl::free(d_x, dpct::get_in_order_queue());
553    sycl::free(d_codes, dpct::get_in_order_queue());
554    sycl::free(d_scales, dpct::get_in_order_queue());
555    sycl::free(d_y, dpct::get_in_order_queue());
556}
557
558int main(int argc, char** argv) {
559    long long n_in = 2560;
560    long long n_out = 128;
561    // 1e-4, not 1e-5: the measured worst is ~1e-5 (FMA contraction of a 2560-term f32 accumulation), so a
562    // 1e-5 threshold would pass by 4% and fail on a different n_in.  The phase spec allows 1e-3 for FP16
563    // paths; this is 10x tighter than the spec and 10x looser than the measurement.
564    double tol = 1e-4;
565    bool selftest = false;
566    bool bench = false;
567    int iters = 200;
568    for (int i = 1; i < argc; ++i) {
569        const std::string a = argv[i];
570        if (a == "--selftest") selftest = true;
571        else if (a == "--bench") bench = true;
572        else if (a == "--iters" && i + 1 < argc) iters = std::atoi(argv[++i]);
573        else if (a == "--n-in" && i + 1 < argc) n_in = std::atoll(argv[++i]);
574        else if (a == "--n-out" && i + 1 < argc) n_out = std::atoll(argv[++i]);
575        else {
576            std::fprintf(stderr, "usage: s_gemv_parity [--selftest] [--n-in N] [--n-out N]\n");
577            return 2;
578        }
579    }
580
581    using strata::kernels::Codebook;
582    using strata::kernels::SForm;
583    std::vector<Case> cases;
584    cases.push_back({"S2/Q2_0", SForm{2, -1, 64, Codebook::Affine, false}, 18, q2_0_to_raw, q2_0_deq});
585    cases.push_back({"S4/Q4_0", SForm{4, -8, 32, Codebook::Affine, false}, 18, q4_0_to_raw, q4_0_deq});
586    cases.push_back({"S4/IQ4_NL", SForm{4, 0, 32, Codebook::Iq4Nl, false}, 18, iq4_to_raw, iq4_deq});
587    cases.push_back({"S8/Q8_0", SForm{8, -128, 32, Codebook::Affine, false}, 34, q8_0_to_raw, q8_0_deq});
588
589    std::mt19937 rng(4242);
590    const int n_scales = (int) (sizeof(kScales) / sizeof(kScales[0]));
591    int total_bad = 0;
592
593    for (const Case& tc : cases) {
594        const int bits = tc.form.code_bits;
595        const int per_byte = 8 / bits;
596        const int G = tc.form.group_elems;
597        const long long n_groups = n_in / G;
598        const long long codes_per_row = n_in / per_byte;
599
600        // activations
601        std::vector<uint16_t> x((size_t) n_in);
602        for (long long i = 0; i < n_in; ++i) x[(size_t) i] = kScales[rng() % n_scales];
603
604        // Codes are generated ONE PER ELEMENT and then packed into the plane the kernel reads.
605        //
606        // The first version of this test generated a random BYTE ARRAY and used it as both, which is the bug
607        // that made S2 pass and the other three fail by 50x-500x.  The two are not the same thing: the kernel
608        // reads element i from byte i/per_byte at bit (i%per_byte)*bits, while the reference needs one code per
609        // element to rebuild a raw GGUF block.  For S2 (per_byte = 4, which IS Q2_0's own raw layout) treating
610        // one random array as both happened to agree - and that coincidence is exactly what a test must not
611        // depend on.
612        std::vector<uint8_t> codes_el((size_t) n_out * n_in);
613        for (size_t i = 0; i < codes_el.size(); ++i) codes_el[i] = (uint8_t) (rng() & ((1u << bits) - 1));
614        std::vector<uint8_t> codes((size_t) n_out * codes_per_row, 0);
615        for (long long o = 0; o < n_out; ++o) {
616            for (long long i = 0; i < n_in; ++i) {
617                const long long byi = o * codes_per_row + i / per_byte;
618                codes[(size_t) byi] |= (uint8_t) (codes_el[(size_t) (o * n_in + i)]
619                                                  << ((i % per_byte) * bits));
620            }
621        }
622        std::vector<float> scales((size_t) n_out * n_groups);
623        std::vector<uint16_t> scale_bits((size_t) n_out * n_groups);
624        for (size_t i = 0; i < scales.size(); ++i) {
625            scale_bits[i] = kScales[rng() % n_scales];
626            scales[i] = strata::fp16_to_fp32(scale_bits[i]);
627        }
628
629        // CPU reference
630        std::vector<float> ref((size_t) n_out, 0.0f);
631        std::vector<uint8_t> raw((size_t) tc.raw_bytes);
632        std::vector<float> dec((size_t) G);
633        for (long long o = 0; o < n_out; ++o) {
634            float acc = 0.0f;
635            for (long long g = 0; g < n_groups; ++g) {
636                const size_t co = (size_t) o * n_in + (size_t) g * G;   // the UNPACKED code array
637                const size_t so = (size_t) o * n_groups + (size_t) g;
638                // The raw block carries the scale as fp16 and the canonical plane carries it widened, so the
639                // block is rebuilt from the PATTERN the plane came from.  No float-to-fp16 conversion is
640                // needed anywhere, and the decoder therefore sees bit-identically what the kernel reads.
641                const int n = tc.to_raw(codes_el.data(), co, scale_bits.data(), so, raw.data());
642                tc.dequant(raw.data(), dec.data());
643                for (long long j = 0; j < (long long) n; ++j) {
644                    acc += dec[(size_t) j] * strata::fp16_to_fp32(x[(size_t) (g * G + j)]);
645                }
646            }
647            ref[(size_t) o] = acc;
648        }
649
650        // GPU
651        uint16_t* d_x = nullptr;
652        uint8_t* d_codes = nullptr;
653        float *d_scales = nullptr, *d_y = nullptr;
654        check(DPCT_CHECK_ERROR(d_x = sycl::malloc_device<uint16_t>(
655                                   x.size(), dpct::get_in_order_queue())),
656              "cudaMalloc x");
657        check(DPCT_CHECK_ERROR(d_codes = (uint8_t *)sycl::malloc_device(
658                                   codes.size(), dpct::get_in_order_queue())),
659              "cudaMalloc codes");
660        check(DPCT_CHECK_ERROR(d_scales = sycl::malloc_device<float>(
661                                   scales.size(), dpct::get_in_order_queue())),
662              "cudaMalloc scales");
663        check(DPCT_CHECK_ERROR(d_y = sycl::malloc_device<float>(
664                                   (size_t)n_out, dpct::get_in_order_queue())),
665              "cudaMalloc y");
666        /*
667        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
668        assuming in the original code the source host memory is pageable memory.
669        If the memory is not pageable, call wait() on event return by memcpy API
670        to ensure synchronization behavior.
671        */
672        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
673                  d_x, x.data(), x.size() * sizeof(uint16_t)).wait()),
674              "copy x");
675        /*
676        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
677        assuming in the original code the source host memory is pageable memory.
678        If the memory is not pageable, call wait() on event return by memcpy API
679        to ensure synchronization behavior.
680        */
681        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
682                  d_codes, codes.data(), codes.size()).wait()),
683              "copy codes");
684        /*
685        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
686        assuming in the original code the source host memory is pageable memory.
687        If the memory is not pageable, call wait() on event return by memcpy API
688        to ensure synchronization behavior.
689        */
690        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
691                  d_scales, scales.data(), scales.size() * sizeof(float)).wait()),
692              "copy scales");
693        strata::kernels::s_gemv(d_x, d_codes, d_scales, nullptr, d_y, n_in, n_out, tc.form);
694        std::vector<float> got((size_t) n_out);
695        check(DPCT_CHECK_ERROR(
696                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
697                      .memcpy(got.data(), d_y, got.size() * sizeof(float))
698                      .wait()),
699              "copy back");
700
701        long long bad = 0;
702        double worst = 0.0;
703        for (long long o = 0; o < n_out; ++o) {
704            const double a = ref[(size_t) o], b = got[(size_t) o];
705            const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
706            if (!(rel <= worst)) worst = rel;
707            if (!(rel <= tol)) ++bad;
708        }
709        double lo = ref[0], hi = ref[0];
710        for (float v : ref) {
711            lo = std::fmin(lo, v);
712            hi = std::fmax(hi, v);
713        }
714        std::printf("  %-10s %lld rows, %lld over tol, worst rel %.3e   ref spread [%.4g, %.4g]\n", tc.name,
715                    n_out, bad, worst, lo, hi);
716        if (hi - lo <= 0.0) {
717            std::fprintf(stderr, "VACUOUS: %s reference is constant\n", tc.name);
718            return 1;
719        }
720        total_bad += (int) bad;
721
722        sycl::free(d_x, dpct::get_in_order_queue());
723        sycl::free(d_codes, dpct::get_in_order_queue());
724        sycl::free(d_scales, dpct::get_in_order_queue());
725        sycl::free(d_y, dpct::get_in_order_queue());
726    }
727
728    std::printf("s_gemv: %zu type cases, %d rows over tolerance (tol %.1e)\n", cases.size(), total_bad, tol);
729    // Q4_K IS NOT PART OF THE DEFAULT RUN.  It FAILS: 128 of 128 rows, worst error 0.586 of sum|term| - a
730    // real difference, not cancellation (the condition number is 2.8e7 and the error is 1.6e7).  Either the
731    // kernel's offset handling or this test's reconstruction of a Q4_K block is wrong and the two have not
732    // been separated yet.  Running it by default would turn ctest red and hide regressions in the four cases
733    // that ARE verified; leaving it out silently would be worse.  It is one flag away, and it is recorded as
734    // OPEN in the project state.
735    // Q4_K is IN the default run as of round 171.  Rounds 169-170 gated it because it FAILED, and the
736    // failure was this test's own reconstruction of a Q4_K block - four decodes of a quarter-filled block per
737    // superblock - not the kernel.  It now agrees to 2.8e-07 of sum|term|, so the gate goes rather than
738    // staying as a habit: a gate that outlives its reason is a check that quietly stopped running.
739    test_q4k(n_in, n_out, tol, &total_bad);
740    std::printf("s_gemv total: %d rows over tolerance\n", total_bad);
741    if (bench) {
742        // the real expert shapes: gate/up are [2560 x 640], down is [640 x 2560]
743        int split_bad = 0;
744        bench_s2_gemv(2560, 640, iters, &split_bad);
745        bench_s2_gemv(640, 2560, iters, &split_bad);
746        std::printf("split kernel rows disagreeing with the naive reference: %d\n", split_bad);
747        // accumulated HERE, inside the block that declares it, and it makes the binary FAIL: a kernel that is
748        // benchmarked but never compared is an unverified kernel being quoted for performance.
749        total_bad += split_bad;
750    }
751    if (total_bad) return 1;
752    if (selftest) std::printf("s_gemv_parity OK\n");
753    return 0;
754}