okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

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