okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
24.0 KiB488 linesraw
1// src/kernels/iq_multi_parity.cpp - the IQ kernels that decode each weight part once for every
2// column / entry, against the older kernels that decode it again per column.  Synthetic blocks, no model.
3//
4//     build/iq_multi_parity            the checks (a ctest; needs the GPU)
5//     build/iq_multi_parity --bench    the checks, then old/new timings of both paths
6//
7// (1) iq_mmvq, every format it takes, ncols 1..8 and 11 (the > 8 split): the new output must be BITWISE equal to
8//     the old one (iq_set_old_kernels), and within float rounding of a double reference built from the GPU's own
9//     dequantizer (validated against gguf-py by iq_parity) and the dequantized q8_1 activations - a gross-error
10//     guard, not the contract.
11// (2) native_expert_grouped, every gate/up format with the down formats: groups of 0..11 entries (more than a pass
12//     of GRP_NC), unused grid rows (cap_groups > groups), scattered destinations; bitwise, new vs old, the rows it
13//     must not write included.
14//
15// Random bytes are valid codes for every format here (all grid indices are in range); only the fp16 block scales
16// are set, small enough that the grouped path's SwiGLU output keeps a finite fp16 q8_1 scale.
17#include "strata/kernels/f16_bits.hpp"
18#include "strata/kernels/iq_kernels.hpp"
19#include "strata/kernels/native_mmvq.hpp"
20
21#include <cuda_runtime.h>
22
23#include <algorithm>
24#include <cmath>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <numeric>
29#include <random>
30#include <string>
31#include <vector>
32
33namespace k = strata::kernels;
34
35namespace {
36
37int g_fail = 0;
38
39void ck(cudaError_t e, const char* w) {
40    if (e != cudaSuccess) {
41        std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e));
42        std::exit(2);
43    }
44}
45
46template<typename T>
47T* dalloc(size_t n) {
48    T* p = nullptr;
49    ck(cudaMalloc(&p, n * sizeof(T) + 256), "malloc");
50    ck(cudaMemset(p, 0, n * sizeof(T) + 256), "memset");
51    return p;
52}
53
54const char* name_of(int t) {
55    switch (t) {
56        case 16: return "IQ2_XXS";
57        case 17: return "IQ2_XS";
58        case 18: return "IQ3_XXS";
59        case 20: return "IQ4_NL";
60        case 21: return "IQ3_S";
61        case 22: return "IQ2_S";
62        case 23: return "IQ4_XS";
63        case 29: return "IQ1_M";
64        case 42: return "Q2_0";
65        case 11: return "Q3_K";
66        case 12: return "Q4_K";
67        case 13: return "Q5_K";
68        case 7: return "Q5_1";
69        case 8: return "Q8_0";
70        default: return "?";
71    }
72}
73int block_values(int t) { return (t == 20 || t == 7 || t == 8) ? 32 : t == 42 ? 64 : 256; }
74
75// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
76std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
77    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
78    std::vector<uint8_t> w((size_t) rows * rb);
79    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 3);
80    for (auto& b : w) b = (uint8_t) byte(rng);
81    for (size_t o = 0; o < w.size(); o += bs) {
82        if (t == 29) {
83            // IQ1_M: the fp16 scale is the top nibbles of the four scale words (bytes 48..55); nibble 3 carries the
84            // sign and the exponent's top bits: 0x1 / 0x2 (or 0x9 / 0xA) keeps it in 2^-11 .. 2^-3
85            const uint8_t nib = (uint8_t) ((sgn(rng) == 0 ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
86            w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
87        } else {
88            const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));   // 2^-13 .. 2^-6
89            std::memcpy(&w[o], &h, 2);
90            if (t == 12 || t == 13 || t == 7) {   // Q4_K / Q5_K (d, dmin) and Q5_1 (d, m): the second half is finite too
91                const uint16_t h2 = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));
92                std::memcpy(&w[o + 2], &h2, 2);
93            }
94        }
95    }
96    return w;
97}
98
99std::vector<float> random_x(size_t n, std::mt19937& rng) {
100    std::normal_distribution<float> nd(0.f, 1.f);
101    std::vector<float> x(n);
102    for (auto& v : x) v = nd(rng);
103    return x;
104}
105
106// q8_1 blocks (fp16 scale, fp16 sum, 32 int8) back to floats
107std::vector<double> dequant_q8_1(const std::vector<uint8_t>& q, size_t n) {
108    std::vector<double> v(n);
109    for (size_t b = 0; b < n / 32; ++b) {
110        uint16_t dh;
111        std::memcpy(&dh, &q[b * 36], 2);
112        const double d = k::f32_from_f16(dh);
113        for (int i = 0; i < 32; ++i) v[b * 32 + i] = d * (int8_t) q[b * 36 + 4 + i];
114    }
115    return v;
116}
117
118// ------------------------------------------------------------------------------------------------ (1) iq_mmvq
119void check_mmvq(int t, int n_in, int n_out, cudaStream_t s, std::mt19937& rng) {
120    const auto w = random_rows(t, n_out, n_in, rng);
121    uint8_t* dw = dalloc<uint8_t>(w.size());
122    ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
123    // the double reference's weights: the GPU dequantizer (iq_parity checks it against gguf-py)
124    float* dwf = dalloc<float>((size_t) n_out * n_in);
125    k::iq_dequant_f32(t, dw, (int64_t) n_out * n_in, dwf, s);
126    std::vector<float> wf((size_t) n_out * n_in);
127    ck(cudaMemcpy(wf.data(), dwf, wf.size() * 4, cudaMemcpyDeviceToHost), "wf");
128    const int max_cols = 11;
129    const auto x = random_x((size_t) max_cols * n_in, rng);
130    float* dx = dalloc<float>(x.size());
131    ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
132    const size_t xq_bytes = (size_t) max_cols * (n_in / 32) * 36;
133    uint8_t* dxq = dalloc<uint8_t>(xq_bytes);
134    k::quantize_q8_1_rows(dx, max_cols, n_in, dxq, s);
135    std::vector<uint8_t> xq(xq_bytes);
136    ck(cudaMemcpy(xq.data(), dxq, xq_bytes, cudaMemcpyDeviceToHost), "xq");
137    const auto xd = dequant_q8_1(xq, (size_t) max_cols * n_in);
138    float* dy_old = dalloc<float>((size_t) max_cols * n_out);
139    float* dy_new = dalloc<float>((size_t) max_cols * n_out);
140    std::vector<float> y_old((size_t) max_cols * n_out), y_new(y_old.size());
141    const int cols[] = {1, 2, 3, 4, 5, 6, 7, 8, 11};
142    int bad = 0;
143    double worst = 0.0;
144    for (int nc : cols) {
145        ck(cudaMemset(dy_old, 0xFF, y_old.size() * 4), "memset");
146        ck(cudaMemset(dy_new, 0xFF, y_new.size() * 4), "memset");
147        k::iq_set_old_kernels(true);
148        k::iq_mmvq(t, dw, dxq, dy_old, n_in, n_out, nc, s);
149        k::iq_set_old_kernels(false);
150        k::iq_mmvq(t, dw, dxq, dy_new, n_in, n_out, nc, s);
151        ck(cudaStreamSynchronize(s), "sync");
152        ck(cudaMemcpy(y_old.data(), dy_old, y_old.size() * 4, cudaMemcpyDeviceToHost), "y_old");
153        ck(cudaMemcpy(y_new.data(), dy_new, y_new.size() * 4, cudaMemcpyDeviceToHost), "y_new");
154        size_t diff = 0;
155        for (size_t i = 0; i < y_old.size(); ++i) diff += std::memcmp(&y_old[i], &y_new[i], 4) != 0;
156        double num = 0, den = 0;
157        bool finite = true;
158        for (int c = 0; c < nc; ++c)
159            for (int r = 0; r < n_out; ++r) {
160                double acc = 0;
161                for (int i = 0; i < n_in; ++i) acc += (double) wf[(size_t) r * n_in + i] * xd[(size_t) c * n_in + i];
162                const float g = y_new[(size_t) c * n_out + r];
163                finite = finite && std::isfinite(g);
164                num += std::fabs(g - acc);
165                den += std::fabs(acc);
166            }
167        const double rel = num / (den + 1e-30);
168        worst = std::max(worst, rel);
169        if (diff != 0 || !finite || !(rel < 1e-2)) {
170            std::printf("  %-8s %5d x %5d  ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s  FAIL\n",
171                        name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite");
172            ++bad;
173        }
174    }
175    std::printf("%-8s type %2d  %5d x %5d  iq_mmvq ncols 1..8, 11: %s (ref rel <= %.2e)\n", name_of(t), t, n_out, n_in,
176                bad ? "FAIL" : "bitwise equal to the old kernel", worst);
177    g_fail += bad;
178    cudaFree(dw); cudaFree(dwf); cudaFree(dx); cudaFree(dxq); cudaFree(dy_old); cudaFree(dy_new);
179}
180
181// ---------------------------------------------------------------------------------- (2) native_expert_grouped
182struct Grouped {
183    k::NativeExpertLayout L;
184    int n_groups = 0, n_ent = 0, cap_groups = 0, cap_ent = 0, n_tok = 0;
185    std::vector<uint8_t*> blobs;
186    unsigned long long* dptr = nullptr;
187    int32_t *dstart = nullptr, *dn = nullptr, *ddst = nullptr, *dtok = nullptr;
188    float* dx = nullptr;
189    uint8_t *dxq = nullptr, *dscr = nullptr;
190    float* dout = nullptr;
191    size_t out_floats = 0;
192
193    Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector<int>& counts, int tokens, std::mt19937& rng) {
194        L = k::native_expert_layout(gu, dt, H, FF);
195        n_groups = (int) counts.size();
196        cap_groups = n_groups + 2;              // the extra grid rows must exit
197        n_tok = tokens;
198        std::vector<int32_t> start(1, 0), tok, dst;
199        for (int c : counts) start.push_back(start.back() + c);
200        n_ent = start.back();
201        cap_ent = n_ent + 3;
202        std::uniform_int_distribution<int> tk(0, tokens - 1);
203        for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng));
204        dst.resize(n_ent);
205        std::iota(dst.begin(), dst.end(), 0);
206        std::shuffle(dst.begin(), dst.end(), rng);
207        std::vector<unsigned long long> ptr;
208        for (int g = 0; g < n_groups; ++g) {
209            // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values)
210            auto b = random_rows(gu, 2 * FF, H, rng);
211            const auto d = random_rows(dt, H, FF, rng);
212            b.insert(b.end(), d.begin(), d.end());
213            if (b.size() != L.bytes) { std::fprintf(stderr, "blob size %zu != %zu\n", b.size(), L.bytes); std::exit(2); }
214            uint8_t* db = dalloc<uint8_t>(b.size());
215            ck(cudaMemcpy(db, b.data(), b.size(), cudaMemcpyHostToDevice), "blob");
216            blobs.push_back(db);
217            ptr.push_back((unsigned long long) db);
218        }
219        dptr = dalloc<unsigned long long>(cap_groups);
220        dstart = dalloc<int32_t>(cap_groups + 1);
221        dn = dalloc<int32_t>(1);
222        ddst = dalloc<int32_t>(cap_ent);
223        dtok = dalloc<int32_t>(cap_ent);
224        ck(cudaMemcpy(dptr, ptr.data(), ptr.size() * 8, cudaMemcpyHostToDevice), "ptr");
225        ck(cudaMemcpy(dstart, start.data(), start.size() * 4, cudaMemcpyHostToDevice), "start");
226        ck(cudaMemcpy(dn, &n_groups, 4, cudaMemcpyHostToDevice), "n");
227        if (n_ent) {
228            ck(cudaMemcpy(ddst, dst.data(), dst.size() * 4, cudaMemcpyHostToDevice), "dst");
229            ck(cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice), "tok");
230        }
231        const auto x = random_x((size_t) tokens * H, rng);
232        dx = dalloc<float>(x.size());
233        ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
234        dxq = dalloc<uint8_t>((size_t) tokens * (H / 32) * 36);
235        dscr = dalloc<uint8_t>(k::native_expert_scratch_bytes(cap_ent, FF));
236        out_floats = (size_t) cap_ent * H;
237        dout = dalloc<float>(out_floats);
238    }
239    ~Grouped() {
240        for (auto* b : blobs) cudaFree(b);
241        cudaFree(dptr); cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
242        cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout);
243    }
244    void run(bool old, cudaStream_t s) {
245        k::iq_set_old_kernels(old);
246        k::quantize_q8_1_rows(dx, n_tok, L.n_embd, dxq, s);
247        k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s);
248        k::iq_set_old_kernels(false);
249    }
250    std::vector<float> result(bool old, cudaStream_t s) {
251        ck(cudaMemset(dout, 0xFF, out_floats * 4), "memset");      // NaN rows: must stay NaN where nothing writes
252        ck(cudaMemset(dscr, 0, k::native_expert_scratch_bytes(cap_ent, L.n_ff)), "memset");
253        run(old, s);
254        ck(cudaStreamSynchronize(s), "sync");
255        std::vector<float> o(out_floats);
256        ck(cudaMemcpy(o.data(), dout, o.size() * 4, cudaMemcpyDeviceToHost), "out");
257        return o;
258    }
259};
260
261void check_grouped(int gu, int dt, int64_t H, int64_t FF, cudaStream_t s, std::mt19937& rng) {
262    // 0..11 entries per group: one pass, a partial pass, two passes and three passes of GRP_NC = 4
263    Grouped G(gu, dt, H, FF, {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8, rng);
264    const int saved_ed = k::native_expert_expdec();
265    const k::NativeExpertExpdecParams saved_p = k::native_expert_expdec_params();
266    const auto a = G.result(true, s);
267    k::native_expert_set_expdec(0);
268    const auto b = G.result(false, s);
269    k::NativeExpertExpdecParams ed_p = saved_p;
270    ed_p.down = 1;
271    ed_p.down_iq4_nl = 1;
272    k::native_expert_set_expdec(1);
273    k::native_expert_set_expdec_params(ed_p);
274    const auto c = G.result(false, s);
275    k::native_expert_set_expdec(saved_ed);
276    k::native_expert_set_expdec_params(saved_p);
277    size_t diff = 0, diff_ed = 0;
278    bool finite = true;
279    for (size_t i = 0; i < a.size(); ++i) {
280        diff += std::memcmp(&a[i], &b[i], 4) != 0;
281        diff_ed += std::memcmp(&a[i], &c[i], 4) != 0;
282        if (i < (size_t) G.n_ent * H) { finite = finite && std::isfinite(b[i]) && std::isfinite(c[i]); }
283    }
284    const bool ok = diff == 0 && diff_ed == 0 && finite;
285    std::printf("%-8s/%-7s %5lld x %4lld  native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu),
286                name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent,
287                ok ? "bitwise equal to the old kernels" : "FAIL");
288    if (!ok) {
289        std::printf("  %zu (multi) / %zu (expdec) of %zu floats differ%s\n", diff, diff_ed, a.size(),
290                    finite ? "" : ", non-finite outputs");
291        ++g_fail;
292    }
293}
294
295// ------------------------------------------------------------------------------------------------ --bench
296float time_ms(cudaStream_t s, int it, const auto& fn) {
297    cudaEvent_t e0, e1;
298    cudaEventCreate(&e0);
299    cudaEventCreate(&e1);
300    fn();
301    cudaEventRecord(e0, s);
302    for (int i = 0; i < it; ++i) fn();
303    cudaEventRecord(e1, s);
304    ck(cudaEventSynchronize(e1), "bench");
305    float ms = 0;
306    cudaEventElapsedTime(&ms, e0, e1);
307    cudaEventDestroy(e0);
308    cudaEventDestroy(e1);
309    return ms / it;
310}
311
312void bench(cudaStream_t s, std::mt19937& rng) {
313    std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n");
314    const int n_in = 2560, n_out = 8192, it = 200;
315    for (int t : {16, 17, 18, 21, 22, 29}) {
316        const auto w = random_rows(t, n_out, n_in, rng);
317        uint8_t* dw = dalloc<uint8_t>(w.size());
318        ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
319        const auto x = random_x((size_t) 8 * n_in, rng);
320        float* dx = dalloc<float>(x.size());
321        ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
322        uint8_t* dxq = dalloc<uint8_t>((size_t) 8 * (n_in / 32) * 36);
323        k::quantize_q8_1_rows(dx, 8, n_in, dxq, s);
324        float* dy = dalloc<float>((size_t) 8 * n_out);
325        std::printf("%-8s iq_mmvq %d x %d:", name_of(t), n_out, n_in);
326        for (int nc = 1; nc <= 8; ++nc) {
327            float us[2];
328            for (int old = 1; old >= 0; --old) {
329                k::iq_set_old_kernels(old != 0);
330                us[old] = 1e3f * time_ms(s, it, [&] { k::iq_mmvq(t, dw, dxq, dy, n_in, n_out, nc, s); });
331            }
332            std::printf("  %d: %.1f/%.1f", nc, us[1], us[0]);
333        }
334        std::printf("\n");
335        k::iq_set_old_kernels(false);
336        cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy);
337    }
338    // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each
339    for (int gu : {16, 17, 18, 21, 22, 29}) {
340        std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu));
341        for (int m : {1, 2, 3, 4, 8}) {
342            Grouped G(gu, 42, 2560, 640, std::vector<int>(16, m), 8, rng);
343            float us[2];
344            for (int old = 1; old >= 0; --old)
345                us[old] = 1e3f * time_ms(s, 50, [&] { G.run(old != 0, s); });
346            std::printf("  m=%d: %.1f/%.1f", m, us[1], us[0]);
347        }
348        std::printf("\n");
349    }
350}
351
352// #606: the q8_1 activation quantizers (quantize_q8_1_rows, native_quantize_q8_1 and the shared expert's fused
353// native_swiglu_quantize_q8_1) against a host transcription of the 0.1.38 formula: every finite block bit for bit; a
354// block whose sum (or scale) overflowed fp16 is now stored finite (the largest half, its sign), with its values in the
355// int8 range.  The fused one gets gate = 32 and up = x / 32: silu(32) is 32 in float, so its activations are x exactly.
356void check_q8_1_finite(cudaStream_t s, std::mt19937& rng) {
357    const int n = 2560, rows = 3, nb = n / 32;
358    std::vector<float> x = random_x((size_t) rows * n, rng);
359    for (int i = 0; i < 32; ++i) x[(size_t) 5 * 32 + i] = 3000.0f;                  // sum 96,000: overflowed
360    for (int i = 0; i < 32; ++i) x[(size_t) 9 * 32 + i] = i == 3 ? -70000.0f : 0.5f;   // sum -69,984.5
361    for (int i = 0; i < 32; ++i) x[(size_t) 13 * 32 + i] = 2000.0f + i;            // sum 64,496: finite, kept
362    x[(size_t) n + 40] = 2.0e7f;                                                    // amax / 127 overflowed too
363    float* dx = dalloc<float>(x.size());
364    ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
365    std::vector<float> gate(x.size(), 32.0f), up(x.size());
366    for (size_t i = 0; i < x.size(); ++i) up[i] = x[i] / 32.0f;
367    float* dg = dalloc<float>(x.size());
368    float* du = dalloc<float>(x.size());
369    ck(cudaMemcpy(dg, gate.data(), x.size() * 4, cudaMemcpyHostToDevice), "gate");
370    ck(cudaMemcpy(du, up.data(), x.size() * 4, cudaMemcpyHostToDevice), "up");
371    uint8_t* dq = dalloc<uint8_t>((size_t) rows * nb * 36);
372    for (int path = 0; path < 3; ++path) {
373        if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s);
374        else if (path == 1) k::native_quantize_q8_1(dx, dq, n, rows, s);
375        else k::native_swiglu_quantize_q8_1(dg, du, dq, n, rows, s);
376        ck(cudaStreamSynchronize(s), "quantize");
377        std::vector<uint8_t> got((size_t) rows * nb * 36);
378        ck(cudaMemcpy(got.data(), dq, got.size(), cudaMemcpyDeviceToHost), "q");
379        int same = 0, clamped = 0, bad = 0;
380        for (int b = 0; b < rows * nb; ++b) {
381            const float* v = x.data() + (size_t) b * 32;
382            float lane[32], amax = 0.0f;
383            for (int i = 0; i < 32; ++i) { lane[i] = v[i]; amax = std::max(amax, std::fabs(v[i])); }
384            for (int o = 16; o > 0; o >>= 1) {   // the warp's butterfly: every lane ends with the same sum
385                float nx[32];
386                for (int i = 0; i < 32; ++i) nx[i] = lane[i] + lane[i ^ o];
387                std::memcpy(lane, nx, sizeof lane);
388            }
389            const float d = amax / 127.0f, sum = lane[0];
390            const uint8_t* g = got.data() + (size_t) b * 36;
391            uint16_t gd, gs;
392            std::memcpy(&gd, g, 2);
393            std::memcpy(&gs, g + 2, 2);
394            const uint16_t od = k::f16_from_f32(d), os = k::f16_from_f32(sum);
395            const bool finite_before = (od & 0x7c00) != 0x7c00 && (os & 0x7c00) != 0x7c00;
396            if (finite_before) {
397                uint8_t want[36];
398                std::memcpy(want, &od, 2);
399                std::memcpy(want + 2, &os, 2);
400                for (int i = 0; i < 32; ++i)   // CUDA's roundf: half away from zero, as std::round
401                    want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d));
402                // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be
403                // the same bits, the scale within one fp16 step and each value within one step
404                bool near = path >= 1 && gs == os && std::abs((int) gd - (int) od) <= 1;
405                for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1;
406                if (std::memcmp(want, g, 36) == 0 || near) ++same;
407                else { ++bad; std::printf("  q8_1 path %d block %d: changed although it was finite\n", path, b); }
408            } else {
409                const float fd = k::f32_from_f16(gd), fs = k::f32_from_f16(gs);
410                bool ok = std::isfinite(fd) && std::isfinite(fs) && fd > 0.0f &&
411                          ((os & 0x7c00) != 0x7c00 ? gs == os : std::fabs(fs) == 65504.0f && (fs < 0) == (sum < 0));
412                for (int i = 0; i < 32; ++i) ok = ok && (int8_t) g[4 + i] >= -127 && (int8_t) g[4 + i] <= 127;
413                if (ok) ++clamped;
414                else { ++bad; std::printf("  q8_1 path %d block %d: d %g sum %g not finite and clamped\n", path, b, fd, fs); }
415            }
416        }
417        std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n",
418                    path == 0 ? "quantize_q8_1_rows" : path == 1 ? "native_quantize_q8_1" : "native_swiglu_quantize_q8_1",
419                    same, clamped, bad ? "  FAIL" : "");
420        g_fail += bad + (clamped != 3);
421    }
422    cudaFree(dx);
423    cudaFree(dg);
424    cudaFree(du);
425    cudaFree(dq);
426}
427
428void colscale_rows_test() {   // lat_colscale_rows: in-place x[r][c] *= inv[c], the Q3_K pack's source-side
429    // multiply.  Width 20: not a multiple of the kernel's 128-lane block (the c >= width guard); 1280: the v7l1280
430    // latent pack's ELL.  The host reference runs the same f32 multiply, so the match is bitwise.
431    for (int width : {20, 1280}) {
432        const int64_t rows = 6;
433        std::vector<float> x((size_t) rows * width), inv((size_t) width), ref;
434        std::mt19937 rng(123);
435        std::uniform_real_distribution<float> d(-1.5f, 1.5f);
436        for (float& v : x) v = d(rng);
437        for (float& v : inv) v = d(rng);
438        ref = x;
439        for (int64_t r = 0; r < rows; ++r)
440            for (int c = 0; c < width; ++c) ref[(size_t) r * width + (size_t) c] *= inv[(size_t) c];
441        float* xd = nullptr;
442        float* invd = nullptr;
443        ck(cudaMalloc(&xd, x.size() * 4), "colscale x");
444        ck(cudaMalloc(&invd, inv.size() * 4), "colscale inv");
445        ck(cudaMemcpy(xd, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "colscale h2d x");
446        ck(cudaMemcpy(invd, inv.data(), inv.size() * 4, cudaMemcpyHostToDevice), "colscale h2d inv");
447        k::lat_colscale_rows(xd, rows, width, invd, nullptr);
448        ck(cudaMemcpy(x.data(), xd, x.size() * 4, cudaMemcpyDeviceToHost), "colscale d2h x");
449        ck(cudaFree(xd), "colscale free x");
450        ck(cudaFree(invd), "colscale free inv");
451        int bad = 0;
452        for (size_t i = 0; i < x.size(); ++i) bad += std::memcmp(&x[i], &ref[i], 4) != 0;
453        std::printf("colscale_rows: width %d %s (%d bad of %lld)\n", width, bad ? "FAIL" : "ok",
454                    bad, (long long) x.size());
455        g_fail += bad > 0;
456    }
457}
458
459}  // namespace
460
461int main(int argc, char** argv) {
462    const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";
463    cudaStream_t s;
464    ck(cudaStreamCreate(&s), "stream");
465    colscale_rows_test();
466    std::mt19937 rng(18);
467    for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42, 12, 13, 7, 8}) {
468        check_mmvq(t, 2560, 67, s, rng);   // the model's n_embd; 67 rows: a partial block of 4 rows
469        check_mmvq(t, 1024, 5, s, rng);
470    }
471    for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) {
472        for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng);   // the model's shape
473        check_grouped(gu, 23, 1024, 512, s, rng);                           // IQ4_XS down needs n_ff % 256 == 0
474    }
475    // Q3_K gate/up (the v7l1280 latent A pack's format; 1280-wide variant below matches it exactly)
476    for (int dt : {20, 42}) { check_grouped(11, dt, 2560, 640, s, rng); check_grouped(11, dt, 1280, 640, s, rng); }
477    check_grouped(11, 23, 1024, 512, s, rng);
478    // UD-Q4_K_XL (run with STRATA_KQ_SPLIT=1 to compare the Split path with the old kernels; STRATA_EXPERT_V2K=0 / 1 picks
479    // the generic multi kernel or the V2K one on gfx12: both are bitwise the old kernels)
480    for (int gu : {12, 13})
481        for (int dt : {7, 8}) check_grouped(gu, dt, 2560, 640, s, rng);
482    for (int gu : {12, 13}) check_grouped(gu, 13, 2048, 512, s, rng);   // Qwen3.6-35B-A3B's geometry
483    check_q8_1_finite(s, rng);
484    if (do_bench) bench(s, rng);
485    std::printf("iq_multi_parity: %d failures\n", g_fail);
486    cudaStreamDestroy(s);
487    return g_fail ? 1 : 0;
488}