okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
39.3 KiB776 linesraw
1// src/kernels/native_grouped_parity.cpp - native_expert_grouped's group stride (grid_groups) and its fused SwiGLU +
2// q8_1 pass, against the launches before them (native_grouped_set_v1: a block row per possible group, SwiGLU and the
3// q8_1 quantization as two kernels over all cap_entries).  Synthetic blobs, no model.
4//
5//     build/native_grouped_parity           the checks (a ctest; needs the GPU)
6//     build/native_grouped_parity --bench   the checks, then v1/new timings of 48 calls in a graph (a window's layers)
7//
8// Every gate/up format with every down format; calls of 0..cap groups of 1..T entries each (an empty call is what the
9// verify window's PCIe call usually is), entries from 0 and from past 0 (the PCIe call's follow the VRAM call's),
10// scattered destinations, stale scratch, grid_groups 0 (= cap), 1, 2, 3, 4 and above cap: the output must be BITWISE
11// equal to v1's, the rows the call must not write included (both start from the same NaN pattern).
12//
13// Random bytes are valid codes for every format here (every grid index is in range); only the fp16 block scales are
14// set, small enough that the SwiGLU outputs keep a finite fp16 q8_1 scale.
15#define DPCT_PROFILING_ENABLED
16#include <sycl/sycl.hpp>
17#include <dpct/dpct.hpp>
18#include "strata/kernels/iq_kernels.hpp"
19#include "strata/core/geometry.hpp"
20
21#include <algorithm>
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <numeric>
27#include <random>
28#include <string>
29#include <vector>
30
31namespace strata::kernels {
32// SYCL port only (iq_kernels.dp.cpp): the K-quant / Q5_1 / Q8_0 lane kernels with (true, the default) or without the
33// multi-entry split; STRATA_KQ_SPLIT=0 at startup is false
34void native_expert_set_kq_split(bool on);
35}
36namespace k = strata::kernels;
37
38namespace {
39
40int g_fail = 0;
41
42void ck(dpct::err0 e, const char *what) {
43}
44
45template<typename T>
46T* dalloc(size_t n) {
47    T* p = nullptr;
48    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
49                            n * sizeof(T) + 256, dpct::get_in_order_queue())),
50       "malloc");
51    ck(DPCT_CHECK_ERROR(
52           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 256).wait()),
53       "memset");
54    return p;
55}
56
57const char* name_of(int t) {
58    switch (t) {
59        case 16: return "IQ2_XXS";
60        case 17: return "IQ2_XS";
61        case 18: return "IQ3_XXS";
62        case 20: return "IQ4_NL";
63        case 21: return "IQ3_S";
64        case 22: return "IQ2_S";
65        case 23: return "IQ4_XS";
66        case 29: return "IQ1_M";
67        case 42: return "Q2_0";
68        case 12: return "Q4_K";
69        case 13: return "Q5_K";
70        case 14: return "Q6_K";
71        case 7: return "Q5_1";
72        case 8: return "Q8_0";
73        default: return "?";
74    }
75}
76int block_values(int t) { return t == 20 || t == 7 || t == 8 ? 32 : t == 42 ? 64 : 256; }
77
78// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
79std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
80    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
81    std::vector<uint8_t> w((size_t) rows * rb);
82    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 1);
83    for (auto& b : w) b = (uint8_t) byte(rng);
84    for (size_t o = 0; o < w.size(); o += bs) {
85        if (t == 29) {
86            // IQ1_M: the fp16 scale is the top nibbles of its four scale words (bytes 48..55), the sign and the
87            // exponent's top bits in the last: 0x1 / 0x2 there (0x9 / 0xA negative) keeps it in 2^-11 .. 2^-3
88            const uint8_t nib = (uint8_t) ((sgn(rng) ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
89            w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
90        } else {   // the other formats start their block with the fp16 scale: 2^-13 .. 2^-6
91            // (Q4_K / Q5_K: 2^-14 .. 2^-11, their 6-bit sub-scales multiply it by up to 63)
92            const int e = (t == 12 || t == 13) ? 1 + ex(rng) % 4 : ex(rng);
93            const uint16_t h = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (e << 10) | man(rng));
94            std::memcpy(&w[o + (t == 14 ? 208 : 0)], &h, 2);   // Q6_K keeps its fp16 scale last (ql, qh, scales, d)
95            if (t == 12 || t == 13 || t == 7) {   // Q4_K / Q5_K: dmin, Q5_1: m - the second fp16, as small
96                const int em = (t == 7) ? ex(rng) : 1 + ex(rng) % 4;
97                const uint16_t m = (uint16_t) ((sgn(rng) ? 0x8000 : 0) | (em << 10) | man(rng));
98                std::memcpy(&w[o + 2], &m, 2);
99            }
100        }
101    }
102    return w;
103}
104
105// one window's worth of expert calls on one format pair: blobs, T tokens' q8_1 activations, cap = T * K entries
106struct Setup {
107    k::NativeExpertLayout L;
108    int T = 0, K = 0, cap = 0, n_blobs = 0;
109    size_t slot = 0;
110    uint8_t* blobs = nullptr;
111    uint8_t* xq = nullptr;
112    uint8_t* scr = nullptr;
113    size_t scr_bytes = 0;
114    float* out = nullptr;
115    size_t out_floats = 0;
116    unsigned long long* ptr = nullptr;
117    int32_t *start = nullptr, *n = nullptr, *dst = nullptr, *tok = nullptr;
118    std::vector<std::vector<uint8_t>> hb;          // host copies: the blobs, the q8_1 activations, the last plan
119    std::vector<uint8_t> h_xq;
120    std::vector<int> h_blob;
121    std::vector<int32_t> h_start, h_tok, h_dst;
122
123    Setup(int gu, int dt, int64_t H, int64_t FF, int tokens, int k_per_token,
124          int blobs_n, std::mt19937 &rng, dpct::queue_ptr s) {
125        L = k::native_expert_layout(gu, dt, H, FF);
126        T = tokens; K = k_per_token; cap = T * K; n_blobs = blobs_n;
127        slot = (L.bytes + 255) & ~(size_t) 255;
128        blobs = dalloc<uint8_t>(slot * (size_t) n_blobs);
129        for (int b = 0; b < n_blobs; ++b) {
130            // gate rows | up rows (format gu, H values each) | down rows (format dt, FF values each)
131            auto blob = random_rows(gu, 2 * FF, H, rng);
132            const auto down = random_rows(dt, H, FF, rng);
133            blob.insert(blob.end(), down.begin(), down.end());
134            hb.push_back(blob);
135            if (blob.size() != L.bytes) { std::fprintf(stderr, "blob %zu != %zu bytes\n", blob.size(), L.bytes); std::exit(2); }
136            /*
137            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
138            assuming in the original code the source host memory is pageable
139            memory. If the memory is not pageable, call wait() on event return
140            by memcpy API to ensure synchronization behavior.
141            */
142            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
143                   blobs + slot * (size_t)b, blob.data(), blob.size()).wait()),
144               "blob");
145        }
146        std::normal_distribution<float> nd(0.f, 1.f);
147        std::vector<float> x((size_t) T * H);
148        for (auto& v : x) v = nd(rng);
149        float* dx = dalloc<float>(x.size());
150        /*
151        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
152        assuming in the original code the source host memory is pageable memory.
153        If the memory is not pageable, call wait() on event return by memcpy API
154        to ensure synchronization behavior.
155        */
156        ck(DPCT_CHECK_ERROR(
157               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
158           "x");
159        xq = dalloc<uint8_t>((size_t) T * (H / 32) * 36);
160        k::quantize_q8_1_rows(dx, T, H, xq, s);
161        h_xq.resize((size_t) T * (H / 32) * 36);
162        s->memcpy(h_xq.data(), xq, h_xq.size()).wait();
163        ck(DPCT_CHECK_ERROR(s->wait()), "quantize");
164        sycl::free(dx, dpct::get_in_order_queue());
165        scr_bytes = k::native_expert_scratch_bytes(cap, FF);
166        scr = dalloc<uint8_t>(scr_bytes);
167        out_floats = (size_t) cap * H;
168        out = dalloc<float>(out_floats);
169        ptr = dalloc<unsigned long long>(cap);
170        start = dalloc<int32_t>(cap + 1);
171        n = dalloc<int32_t>(1);
172        dst = dalloc<int32_t>(cap);
173        tok = dalloc<int32_t>(cap);
174    }
175    ~Setup() {
176        sycl::free(blobs, dpct::get_in_order_queue());
177            sycl::free(xq, dpct::get_in_order_queue());
178            sycl::free(scr, dpct::get_in_order_queue());
179            sycl::free(out, dpct::get_in_order_queue());
180        sycl::free(ptr, dpct::get_in_order_queue());
181            sycl::free(start, dpct::get_in_order_queue());
182            sycl::free(n, dpct::get_in_order_queue());
183            sycl::free(dst, dpct::get_in_order_queue());
184            sycl::free(tok, dpct::get_in_order_queue());
185    }
186    // a plan: `groups` groups of 1..T entries from entry `base` on (as many as fit in cap)
187    int plan(int groups, int base, std::mt19937& rng) {
188        std::uniform_int_distribution<int> size(1, T);
189        std::vector<int> sizes;
190        int used = base;
191        for (int g = 0; g < groups; ++g) {
192            const int m = std::min(size(rng), cap - used);
193            if (m <= 0) break;
194            sizes.push_back(m);
195            used += m;
196        }
197        return plan_sizes(sizes, base, rng);
198    }
199    // groups of these sizes from entry `base` on, each its own blob (as long as there are enough: a window's groups
200    // are different experts); scattered destinations, random tokens
201    int plan_sizes(const std::vector<int>& sizes, int base, std::mt19937& rng) {
202        std::uniform_int_distribution<int> tk(0, T - 1);
203        std::vector<int> order(n_blobs);
204        std::iota(order.begin(), order.end(), 0);
205        std::shuffle(order.begin(), order.end(), rng);
206        std::vector<unsigned long long> p;
207        std::vector<int32_t> st(1, base), tk_v, ds(cap);
208        h_blob.clear();
209        for (const int m : sizes) {
210            h_blob.push_back(order[p.size() % order.size()]);
211            p.push_back((unsigned long long) (blobs + slot * (size_t) order[p.size() % order.size()]));
212            st.push_back(st.back() + m);
213        }
214        if (st.back() > cap) { std::fprintf(stderr, "plan: %d entries > cap %d\n", st.back(), cap); std::exit(2); }
215        const int ng = (int) p.size();
216        std::iota(ds.begin(), ds.end(), 0);
217        std::shuffle(ds.begin(), ds.end(), rng);                  // scattered rows of `out`
218        for (int e = 0; e < cap; ++e) tk_v.push_back(tk(rng));
219        h_start = st; h_tok = tk_v; h_dst = ds;   // host copies for the CPU reference
220        /*
221        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
222        assuming in the original code the source host memory is pageable memory.
223        If the memory is not pageable, call wait() on event return by memcpy API
224        to ensure synchronization behavior.
225        */
226        if (ng) ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
227                       ptr, p.data(), p.size() * 8).wait()),
228                   "ptr");
229        /*
230        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
231        assuming in the original code the source host memory is pageable memory.
232        If the memory is not pageable, call wait() on event return by memcpy API
233        to ensure synchronization behavior.
234        */
235        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(start, st.data(),
236                                                              st.size() * 4).wait()),
237           "start");
238        ck(DPCT_CHECK_ERROR(
239               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(n, &ng, 4).wait()),
240           "n");
241        /*
242        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
243        assuming in the original code the source host memory is pageable memory.
244        If the memory is not pageable, call wait() on event return by memcpy API
245        to ensure synchronization behavior.
246        */
247        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dst, ds.data(),
248                                                              ds.size() * 4).wait()),
249           "dst");
250        /*
251        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
252        assuming in the original code the source host memory is pageable memory.
253        If the memory is not pageable, call wait() on event return by memcpy API
254        to ensure synchronization behavior.
255        */
256        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(tok, tk_v.data(),
257                                                              tk_v.size() * 4).wait()),
258           "tok");
259        return ng;
260    }
261    void call(int64_t grid_groups, dpct::queue_ptr s) {
262        k::native_expert_grouped(L, ptr, start, n, dst, tok, cap, cap, xq, scr, out, s, grid_groups);
263    }
264    // `out` after one call from the NaN pattern, the scratch holding `junk` (what earlier calls left there)
265    std::vector<uint32_t> result(bool v1, int64_t grid_groups, int junk,
266                                 dpct::queue_ptr s) {
267        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
268                                .memset(out, 0xFF, out_floats * 4)
269                                .wait()),
270           "memset");
271        ck(DPCT_CHECK_ERROR(
272               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(scr, junk, scr_bytes).wait()),
273           "memset");
274        k::native_grouped_set_v1(v1);
275        call(grid_groups, s);
276        k::native_grouped_set_v1(false);
277        ck(DPCT_CHECK_ERROR(s->wait()), "sync");
278        std::vector<uint32_t> o(out_floats);
279        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
280                                .memcpy(o.data(), out, o.size() * 4)
281                                .wait()),
282           "out");
283        return o;
284    }
285};
286
287void check(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s,
288           std::mt19937 &rng) {
289    Setup S(gu, dt, H, FF, 6, 4, 9, rng, s);   // 6 tokens x 4 experts: cap 24 entries
290    int calls = 0, bad = 0;
291    size_t written = 0;
292    for (const int base : {0, 7}) {
293        for (const int groups : {0, 1, 2, 3, 5, 8, 24}) {
294            const int ng = S.plan(groups, base, rng);
295            const auto ref = S.result(true, 0, 0x00, s);
296            size_t w = 0;
297            for (const uint32_t v : ref) w += v != 0xFFFFFFFFu;
298            written += w;
299            for (const int64_t gy : {(int64_t) 0, (int64_t) 1, (int64_t) 2, (int64_t) 3, (int64_t) 4, (int64_t) S.cap + 3}) {
300                const auto got = S.result(false, gy, (calls & 1) ? 0x7F : 0x00, s);
301                ++calls;
302                size_t diff = 0;
303                for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i];
304                if (diff) {
305                    std::printf("  %-8s/%-7s base %d, %d groups, grid_groups %lld: %zu of %zu floats differ  FAIL\n",
306                                name_of(gu), name_of(dt), base, ng, (long long) gy, diff, ref.size());
307                    ++bad;
308                }
309            }
310        }
311    }
312    std::printf("%-8s/%-7s %5lld x %4lld  %d calls: %s (%zu output floats written in all)\n", name_of(gu), name_of(dt),
313                (long long) H, (long long) FF, calls, bad ? "FAIL" : "bitwise equal to v1", written);
314    if (written == 0) { std::printf("  nothing was written: the check checked nothing  FAIL\n"); ++bad; }
315    g_fail += bad;
316}
317
318// ------------------------------------------------------------------------------------------------ --kq
319// MODEL-UPDATE (Intel): the K-quant / Q5_1 / Q8_0 multi-entry split (native_expert_set_kq_split) against the per-entry
320// kernels, bitwise; and both against a CPU reference in float: ggml's dequantize_row_* of the weights, the q8_1
321// activations' own values (d x q), SwiGLU in float (the GPU re-quantizes h to q8_1 for the down product, the reference
322// does not: that rounding is the tolerance, 3e-2 of the output's largest magnitude).
323float h2f(const uint8_t* p) {
324    uint16_t h;
325    std::memcpy(&h, p, 2);
326    return (float) sycl::bit_cast<sycl::half>(h);
327}
328// ggml-quants.c dequantize_row_* (one block)
329void dq_block(int t, const uint8_t* b, float* y) {
330    switch (t) {
331        case 8: {   // Q8_0: d, qs[32]
332            const float d = h2f(b);
333            for (int i = 0; i < 32; ++i) y[i] = d * (float) (int8_t) b[2 + i];
334            break;
335        }
336        case 7: {   // Q5_1: d, m, qh[4], qs[16]
337            const float d = h2f(b), m = h2f(b + 2);
338            uint32_t qh;
339            std::memcpy(&qh, b + 4, 4);
340            const uint8_t* qs = b + 8;
341            for (int j = 0; j < 16; ++j) {
342                const uint8_t xh0 = ((qh >> j) << 4) & 0x10, xh1 = ((qh >> (j + 12))) & 0x10;
343                y[j] = (float) ((qs[j] & 0x0F) | xh0) * d + m;
344                y[j + 16] = (float) ((qs[j] >> 4) | xh1) * d + m;
345            }
346            break;
347        }
348        case 12: case 13: {   // Q4_K: d, dmin, scales[12], qs[128]; Q5_K: d, dmin, scales[12], qh[32], qs[128]
349            const float d = h2f(b), dmin = h2f(b + 2);
350            const uint8_t* sc = b + 4;
351            const uint8_t* qh = b + 16;
352            const uint8_t* ql = t == 12 ? b + 16 : b + 48;
353            auto smk = [&](int j, uint8_t& s, uint8_t& m) {
354                if (j < 4) { s = sc[j] & 63; m = sc[j + 4] & 63; }
355                else { s = (sc[j + 4] & 0xF) | ((sc[j - 4] >> 6) << 4); m = (sc[j + 4] >> 4) | ((sc[j] >> 6) << 4); }
356            };
357            int is = 0;
358            uint8_t u1 = 1, u2 = 2;
359            for (int j = 0; j < 256; j += 64) {
360                uint8_t s, m;
361                smk(is, s, m);
362                const float d1 = d * s, m1 = dmin * m;
363                smk(is + 1, s, m);
364                const float d2 = d * s, m2 = dmin * m;
365                for (int l = 0; l < 32; ++l)
366                    *y++ = d1 * (float) ((ql[l] & 0xF) + (t == 13 && (qh[l] & u1) ? 16 : 0)) - m1;
367                for (int l = 0; l < 32; ++l)
368                    *y++ = d2 * (float) ((ql[l] >> 4) + (t == 13 && (qh[l] & u2) ? 16 : 0)) - m2;
369                ql += 32; is += 2; u1 <<= 2; u2 <<= 2;
370            }
371            break;
372        }
373        case 14: {   // Q6_K: ql[128], qh[64], scales[16], d
374            const uint8_t* ql = b;
375            const uint8_t* qh = b + 128;
376            const int8_t* sc = (const int8_t*) (b + 192);
377            const float d = h2f(b + 208);
378            for (int n = 0; n < 256; n += 128) {
379                for (int l = 0; l < 32; ++l) {
380                    const int is = l / 16;
381                    const int q1 = (int8_t) ((ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32;
382                    const int q2 = (int8_t) ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32;
383                    const int q3 = (int8_t) ((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;
384                    const int q4 = (int8_t) ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;
385                    y[l] = d * sc[is] * q1;
386                    y[l + 32] = d * sc[is + 2] * q2;
387                    y[l + 64] = d * sc[is + 4] * q3;
388                    y[l + 96] = d * sc[is + 6] * q4;
389                }
390                y += 128; ql += 64; qh += 32; sc += 8;
391            }
392            break;
393        }
394        default: std::fprintf(stderr, "dq_block: type %d\n", t); std::exit(2);
395    }
396}
397std::vector<float> dq_rows(int t, const uint8_t* w, int64_t rows, int64_t n) {
398    const int bv = block_values(t);
399    const size_t bs = k::iq_row_bytes(t, bv);
400    std::vector<float> y((size_t) rows * n);
401    for (size_t b = 0; b < y.size() / bv; ++b) dq_block(t, w + b * bs, &y[b * bv]);
402    return y;
403}
404// the CPU reference of the last plan's call: out rows ent_dst[e] (n_embd floats each)
405std::vector<float> reference(const Setup& S) {
406    const int64_t H = S.L.n_embd, FF = S.L.n_ff;
407    std::vector<float> ref(S.out_floats, std::nanf(""));
408    std::vector<float> x(H);
409    for (size_t g = 0; g + 1 < S.h_start.size(); ++g) {
410        const auto& blob = S.hb[S.h_blob[g]];
411        const auto G = dq_rows(S.L.gu_type, blob.data(), FF, H);
412        const auto U = dq_rows(S.L.gu_type, blob.data() + S.L.up_off, FF, H);
413        const auto D = dq_rows(S.L.d_type, blob.data() + S.L.down_off, H, FF);
414        for (int e = S.h_start[g]; e < S.h_start[g + 1]; ++e) {
415            const uint8_t* xb = &S.h_xq[(size_t) S.h_tok[e] * (H / 32) * 36];
416            for (int64_t i = 0; i < H; ++i) x[i] = h2f(xb + (i / 32) * 36) * (float) (int8_t) xb[(i / 32) * 36 + 4 + i % 32];
417            std::vector<float> h(FF);
418            for (int64_t r = 0; r < FF; ++r) {
419                double gs = 0, us = 0;
420                for (int64_t i = 0; i < H; ++i) { gs += (double) G[r * H + i] * x[i]; us += (double) U[r * H + i] * x[i]; }
421                h[r] = (float) (gs / (1.0 + std::exp(-gs)) * us);
422            }
423            for (int64_t r = 0; r < H; ++r) {
424                double s = 0;
425                for (int64_t i = 0; i < FF; ++i) s += (double) D[r * FF + i] * h[i];
426                ref[(size_t) S.h_dst[e] * H + r] = (float) s;
427            }
428        }
429    }
430    return ref;
431}
432void check_kq(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s, std::mt19937& rng) {
433    Setup S(gu, dt, H, FF, 6, 4, 9, rng, s);   // groups of 1..6 entries: the split's chunks of 4 and 2 and the rest
434    int calls = 0, bad = 0;
435    double worst = 0;
436    for (const int groups : {1, 2, 3, 5, 8}) {
437        const int ng = S.plan(groups, 0, rng);
438        k::native_expert_set_kq_split(false);
439        const auto a = S.result(false, 0, 0x00, s);
440        k::native_expert_set_kq_split(true);
441        const auto b = S.result(false, 0, 0x7F, s);
442        ++calls;
443        size_t diff = 0;
444        for (size_t i = 0; i < a.size(); ++i) diff += a[i] != b[i];
445        if (diff) {
446            std::printf("  %-6s/%-6s %d groups: split vs per-entry: %zu of %zu floats differ  FAIL\n", name_of(gu), name_of(dt),
447                        ng, diff, a.size());
448            ++bad;
449        }
450        const auto ref = reference(S);
451        double amax = 0, emax = 0;
452        size_t n = 0;
453        for (size_t i = 0; i < ref.size(); ++i) {
454            if (std::isnan(ref[i])) continue;
455            float g;
456            std::memcpy(&g, &b[i], 4);
457            amax = std::max(amax, (double) std::fabs(ref[i]));
458            emax = std::max(emax, (double) std::fabs(g - ref[i]));
459            ++n;
460        }
461        const double rel = amax > 0 ? emax / amax : 1.0;
462        worst = std::max(worst, rel);
463        if (n == 0 || !(rel < 3e-2)) {
464            std::printf("  %-6s/%-6s %d groups: GPU vs CPU reference: max err %.3g of %.3g (%zu values)  FAIL\n", name_of(gu),
465                        name_of(dt), ng, emax, amax, n);
466            ++bad;
467        }
468    }
469    std::printf("%-6s/%-6s %5lld x %4lld  %d calls: split %s, CPU reference worst %.2e of the largest output\n", name_of(gu),
470                name_of(dt), (long long) H, (long long) FF, calls, bad ? "FAIL" : "bitwise equal to per-entry", worst);
471    g_fail += bad;
472}
473
474// ------------------------------------------------------------------------------------------------ --bench
475// A window's 48 calls, one per layer, each with ITS OWN experts as the layers have: copies of the Setup's blobs in one
476// arena, so the weights stream from DRAM as in the engine.  (48 calls re-reading the same 28 experts - 73 MB, about an
477// Ada L2 - would read part of them from L2; the engine's layers share none.)
478struct Layers {
479    uint8_t* arena = nullptr;
480    std::vector<unsigned long long*> ptr;           // per layer: its groups' blobs (device)
481    Layers(Setup& S, int ng) {
482        const int per = std::max(ng, 1);
483        arena = dalloc<uint8_t>(S.slot * (size_t) (48 * per));
484        for (int l = 0; l < 48; ++l) {
485            std::vector<unsigned long long> p;
486            for (int j = 0; j < per; ++j) {
487                uint8_t* d = arena + S.slot * (size_t) (l * per + j);
488                ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
489                       d,
490                       S.blobs + S.slot * (size_t)((l * per + j) % S.n_blobs),
491                       S.L.bytes).wait()),
492                   "blob copy");
493                p.push_back((unsigned long long) d);
494            }
495            unsigned long long* dp = dalloc<unsigned long long>(p.size());
496            /*
497            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
498            assuming in the original code the source host memory is pageable
499            memory. If the memory is not pageable, call wait() on event return
500            by memcpy API to ensure synchronization behavior.
501            */
502            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
503                   dp, p.data(), p.size() * 8).wait()),
504               "ptr");
505            ptr.push_back(dp);
506        }
507    }
508    Layers(const Layers&) = delete;
509    Layers& operator=(const Layers&) = delete;
510    ~Layers() {
511        for (auto *p : ptr)
512            DPCT_CHECK_ERROR(sycl::free(p, dpct::get_in_order_queue()));
513        sycl::free(arena, dpct::get_in_order_queue());
514    }
515};
516
517// the 48 calls of one variant captured in one graph
518dpct::experimental::command_graph_exec_ptr
519make_graph(dpct::queue_ptr s, Setup &S, const Layers &Ls, bool v1, int64_t gy) {
520    k::native_grouped_set_v1(v1);
521    dpct::experimental::command_graph_ptr g;
522    dpct::experimental::command_graph_exec_ptr ge;
523    ck(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(s)), "capture");
524    for (int l = 0; l < 48; ++l)
525        k::native_expert_grouped(S.L, Ls.ptr[l], S.start, S.n, S.dst, S.tok, S.cap, S.cap, S.xq, S.scr, S.out, s, gy);
526    ck(DPCT_CHECK_ERROR(dpct::experimental::end_recording(s, &g)), "capture");
527    ck(DPCT_CHECK_ERROR(
528           ge = new sycl::ext::oneapi::experimental::command_graph<
529               sycl::ext::oneapi::experimental::graph_state::executable>(
530               g->finalize())),
531       "instantiate");
532    ck(DPCT_CHECK_ERROR(delete (g)), "graph");
533    k::native_grouped_set_v1(false);
534    return ge;
535}
536
537// one launch of the graph: microseconds per call
538float launch_us(dpct::queue_ptr s,
539                dpct::experimental::command_graph_exec_ptr ge,
540                dpct::event_ptr e0, dpct::event_ptr e1) {
541    /*
542    DPCT1024: The original code returned the error code that was further
543    consumed by the program logic. This original code was replaced with 0. You
544    may need to rewrite the program logic consuming the error code.
545    */
546    ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e0, s)), "record");
547    ck(DPCT_CHECK_ERROR(s->ext_oneapi_graph(*ge)), "launch");
548    /*
549    DPCT1024: The original code returned the error code that was further
550    consumed by the program logic. This original code was replaced with 0. You
551    may need to rewrite the program logic consuming the error code.
552    */
553    ck(DPCT_CHECK_ERROR(dpct::sync_barrier(e1, s)), "record");
554    ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench");
555    float ms = 0;
556    ck(DPCT_CHECK_ERROR(
557           ms = (e1->get_profiling_info<
558                     sycl::info::event_profiling::command_end>() -
559                 e0->get_profiling_info<
560                     sycl::info::event_profiling::command_start>()) /
561                1000000.0f),
562       "elapsed");
563    return 1e3f * ms / 48.0f;
564}
565
566float median(std::vector<float> v) {
567    std::sort(v.begin(), v.end());
568    return v[v.size() / 2];
569}
570
571// The two variants' launches ALTERNATE (v1-new, new-v1, ...) after a warm-up, and each reports its median: a card
572// under sustained load steps its clock down after a fraction of a second (an RTX 4080 SUPER went from 80 to 89 us
573// per gate/up call within one run), and whichever variant ran before the step would look faster.
574constexpr int kWarmPairs = 20, kPairs = 40;
575
576void bench(dpct::queue_ptr s, std::mt19937 &rng) {
577    std::printf("\n--bench: microseconds per call, a window's 48 calls in a graph, each layer with its own experts (the\n"
578                "weights stream from DRAM as in the engine); v1 / new (grid_groups): medians of %d launches each,\n"
579                "alternating, after %d warm-up pairs - idle GPU assumed\n", kPairs, kWarmPairs);
580    // a verify window's shape: 4 tokens x 10 experts, 2560 x 768 IQ3_S / IQ4_XS experts
581    Setup S(21, 23, 2560, 768, 4, 10, 32, rng, s);
582    std::vector<int> vram(16, 1);
583    vram.insert(vram.end(), 12, 2);                                   // 28 groups, 40 entries
584    const struct { const char* what; std::vector<int> sizes; int64_t gy; } rows[] = {
585        {"no group (the PCIe call at pcie_frac 0)", {}, 4},
586        {"1 group of 2 entries (a PCIe call)", {2}, 4},
587        {"28 groups, 40 entries (a VRAM call)", vram, 0},
588    };
589    dpct::event_ptr e0, e1;
590    ck(DPCT_CHECK_ERROR(e0 = new sycl::event()), "event");
591    ck(DPCT_CHECK_ERROR(e1 = new sycl::event()), "event");
592    for (const auto& r : rows) {
593        const int ng = S.plan_sizes(r.sizes, 0, rng);
594        const Layers Ls(S, ng);                                       // 48 x 28 experts: 3.7 GB for the VRAM call
595        dpct::experimental::command_graph_exec_ptr ga = make_graph(s, S, Ls,
596                                                                   true, 0),
597                                                   gb = make_graph(s, S, Ls,
598                                                                   false, r.gy);
599        std::vector<float> ta, tb;
600        for (int i = 0; i < kWarmPairs + kPairs; ++i) {
601            const bool a_first = i % 2 == 0;
602            const float x = launch_us(s, a_first ? ga : gb, e0, e1), y = launch_us(s, a_first ? gb : ga, e0, e1);
603            if (i < kWarmPairs) continue;
604            ta.push_back(a_first ? x : y);
605            tb.push_back(a_first ? y : x);
606        }
607        ck(DPCT_CHECK_ERROR(delete (ga)), "graph");
608        ck(DPCT_CHECK_ERROR(delete (gb)), "graph");
609        std::printf("  %-42s %8.2f / %8.2f us (grid_groups %lld)\n", r.what, median(ta), median(tb), (long long) r.gy);
610    }
611    dpct::destroy_event(e0);
612    dpct::destroy_event(e1);
613}
614
615// ------------------------------------------------------------------------------------------------ --kqbench [NL [host]]
616// Unsloth's formats against the IQ packs' at the model's shapes (2560 x 640): microseconds per grouped call and the
617// expert bytes it reads per microsecond.  NL layers (default 16), each with its own experts, so the weights stream from
618// DRAM; a call reads each of its groups' whole blobs (gate + up + down) once.  Shapes: one token (10 groups of 1), a
619// window of 2 tokens (16 groups, 20 entries) and of 4 (28 groups, 40 entries; native_grouped_parity's --bench).
620// STRATA_GU_LANES / STRATA_DOWN_LANES pick the lane split as in the engine.
621void kq_bench(dpct::queue_ptr s, std::mt19937& rng, int nl, bool host) {
622    const int pairs[][2] = {{21, 20}, {23, 20}, {18, 42}, {12, 7}, {12, 8}, {13, 8},
623#ifdef STRATA_Q6K_EXPERTS
624                            {14, 8},
625#endif
626                            {8, 8}};
627    std::vector<int> w1(10, 1), w2(12, 1), w4(16, 1);
628    w2.insert(w2.end(), 4, 2);                                  // 16 groups, 20 entries
629    w4.insert(w4.end(), 12, 2);                                 // 28 groups, 40 entries
630    const struct { const char* what; int T; const std::vector<int>* sizes; } shapes[] = {
631        {"1 token, 10x1", 1, &w1}, {"2 tokens, 16 groups / 20", 2, &w2}, {"4 tokens, 28 groups / 40", 4, &w4}};
632    dpct::event_ptr e0 = new sycl::event(), e1 = new sycl::event();
633    std::printf("\n--kqbench: %d layers per graph, each its own experts (%s); us per call (median of 40), expert MB per call, GB/s\n",
634                nl, host ? "pinned host memory" : "device memory");
635    for (const auto& pr : pairs) {
636        for (const auto& sh : shapes) {
637            Setup S(pr[0], pr[1], 2560, 640, sh.T, 10, 28, rng, s);
638            const int ng = S.plan_sizes(*sh.sizes, 0, rng);
639            // host: the arena in pinned host memory, read by the kernels over PCIe (the B70's mirrored experts)
640            uint8_t* arena = host ? (uint8_t*) sycl::malloc_host(S.slot * (size_t) (nl * ng) + 256, dpct::get_in_order_queue())
641                                  : dalloc<uint8_t>(S.slot * (size_t) (nl * ng));
642            std::vector<unsigned long long*> lp;
643            for (int l = 0; l < nl; ++l) {
644                std::vector<unsigned long long> p;
645                for (int j = 0; j < ng; ++j) {
646                    uint8_t* d = arena + S.slot * (size_t) (l * ng + j);
647                    dpct::get_in_order_queue().memcpy(d, S.blobs + S.slot * (size_t) (j % S.n_blobs), S.L.bytes).wait();
648                    p.push_back((unsigned long long) d);
649                }
650                unsigned long long* dp = dalloc<unsigned long long>(p.size());
651                dpct::get_in_order_queue().memcpy(dp, p.data(), p.size() * 8).wait();
652                lp.push_back(dp);
653            }
654            dpct::experimental::command_graph_ptr g;
655            dpct::experimental::begin_recording(s);
656            for (int l = 0; l < nl; ++l)
657                k::native_expert_grouped(S.L, lp[l], S.start, S.n, S.dst, S.tok, S.cap, S.cap, S.xq, S.scr, S.out, s, 0);
658            dpct::experimental::end_recording(s, &g);
659            auto* ge = new sycl::ext::oneapi::experimental::command_graph<
660                sycl::ext::oneapi::experimental::graph_state::executable>(g->finalize());
661            delete g;
662            std::vector<float> t;
663            for (int i = 0; i < 60; ++i) {
664                const float us = launch_us(s, ge, e0, e1) * 48.0f / (float) nl;
665                if (i >= 20) t.push_back(us);
666            }
667            delete ge;
668            const double mb = (double) ng * (double) S.L.bytes / 1e6, us = median(t);
669            std::printf("  %-7s/%-6s %-26s %8.2f us  %6.2f MB  %6.1f GB/s\n", name_of(pr[0]), name_of(pr[1]), sh.what, us,
670                        mb, mb * 1e3 / us);
671            for (auto* p : lp) sycl::free(p, dpct::get_in_order_queue());
672            sycl::free(arena, dpct::get_in_order_queue());
673        }
674    }
675    dpct::destroy_event(e0);
676    dpct::destroy_event(e1);
677}
678
679}  // namespace
680
681int main(int argc, char** argv) {
682    const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";
683    dpct::queue_ptr s;
684    ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),
685       "stream");
686    std::mt19937 rng(316);
687    if (argc > 1 && std::string(argv[1]) == "--kqbench") {   // timings only (the checks: run without arguments)
688        kq_bench(s, rng, argc > 2 ? std::atoi(argv[2]) : 16, argc > 3 && std::string(argv[3]) == "host");
689        dpct::get_current_device().destroy_queue(s);
690        return 0;
691    }
692    // Q4-KQ: the K-quant downs of a UD file at expert widths divisible by 256 (Qwen3.6's UD-Q4_K_XL: Q4_K / Q5_K gate/up, Q5_K / Q6_K
693    // down, 2048 x 512), split vs per-entry bitwise and the GPU against the CPU reference, at the widths 512 and 1024
694    auto kq_down = [&] {
695        // Q4-SYCL: and the hidden width the build is compiled for (3072 in q4_mid, 4096 in q4_big; the pools' buffers follow it)
696        std::vector<int64_t> Hs = {2048, 2560};
697        if (std::find(Hs.begin(), Hs.end(), (int64_t) strata::core::kCompiledGeometry.n_embd) == Hs.end()) Hs.push_back(strata::core::kCompiledGeometry.n_embd);
698        const int gus[] = {12, 13};
699        for (const int gu : gus)
700            for (const int dt : {13
701#ifdef STRATA_Q6K_EXPERTS
702                                 , 14
703#endif
704                                })
705                for (const int64_t H : Hs)
706                    for (const int64_t FF : {512, 1024}) check_kq(gu, dt, H, FF, s, rng);
707    };
708    // Q4-KQ: --hash, a checksum of the grouped expert call's output bytes for every pair of today's sets (the IQ3_XXS pack and the
709    // Unsloth UD sets at the model's 2560 x 640), fixed seeds: run on the build before and after a kernel change, the lines must be
710    // identical (the A750 is not repeatable end to end, but a kernel call on fixed inputs is)
711    if (argc > 1 && std::string(argv[1]) == "--hash") {
712        const int pairs[][2] = {{18, 42}, {18, 20}, {18, 6}, {18, 8}, {21, 20}, {21, 6}, {21, 8}, {21, 42}, {23, 20}, {23, 6}, {16, 42}, {17, 20},
713                                {22, 42}, {29, 42}, {42, 42}, {42, 20}, {12, 7}, {12, 8}, {13, 8}, {13, 7}, {14, 8}, {8, 8}};
714        for (const auto& pr : pairs) {
715            for (const int64_t FF : {640}) {
716                std::mt19937 r2(4242 + pr[0] * 64 + pr[1]);
717                Setup S(pr[0], pr[1], 2560, FF, 6, 4, 9, r2, s);
718                uint64_t h = 1469598103934665603ull;
719                for (const int groups : {1, 3, 5, 8}) {
720                    S.plan(groups, 0, r2);
721                    const auto b = S.result(false, 0, 0x7F, s);
722                    for (const auto v : b) { h ^= (uint64_t) v; h *= 1099511628211ull; }
723                }
724                std::printf("HASH %s/%s 2560 x %lld %016llx\n", name_of(pr[0]), name_of(pr[1]), (long long) FF, (unsigned long long) h);
725            }
726        }
727        dpct::get_current_device().destroy_queue(s);
728        return 0;
729    }
730    if (argc > 1 && std::string(argv[1]) == "--kqdown") {
731        kq_down();
732        std::printf("native_grouped_parity --kqdown: %d failures\n", g_fail);
733        dpct::get_current_device().destroy_queue(s);
734        return g_fail ? 1 : 0;
735    }
736    if (argc > 1 && std::string(argv[1]) == "--kq") {   // the K-quant split and the CPU reference only
737        const int pairs[][2] = {{12, 7}, {12, 8}, {13, 8}, {14, 8}, {8, 8}, {13, 7}};
738        for (const auto& pr : pairs) check_kq(pr[0], pr[1], 2560, 640, s, rng);   // the model's shapes
739        for (const auto& pr : pairs) check_kq(pr[0], pr[1], 512, 256, s, rng);
740        std::printf("native_grouped_parity --kq: %d failures\n", g_fail);
741        dpct::get_current_device().destroy_queue(s);
742        return g_fail ? 1 : 0;
743    }
744    for (int gu : {16, 17, 18, 21, 22, 23, 29, 42, 12, 13,
745#ifdef STRATA_Q6K_EXPERTS
746                   14,
747#endif
748                   8})        // STRATA_GU_FMTS
749        for (int dt : {20, 23, 42, 7, 8, 6, 13}) check(gu, dt, 512, 256, s, rng);   // STRATA_D_FMTS (6 = Q5_0: UD-IQ4_XS / Q3_K_XL); IQ4_XS: n_ff % 256
750    kq_down();                                                          // Q4-KQ: Q5_K / Q6_K downs at widths 512 and 1024
751    check(21, 20, 2560, 640, s, rng);                                   // a model's shapes
752    // round 0214: every expert type pair of the new Unsloth Qwen3.8-Flash-Next sets at the model's 2560 x 640
753    // (IQ1_M/IQ2_XXS/IQ2_XS/IQ2_S/Q2_0/IQ3_XXS/IQ4_XS gate/up; Q2_0/IQ4_NL/Q5_0/Q8_0 down; IQ4_XS is 256-wide so n_ff 640 needs a 32-block down)
754    for (int gu : {29, 16, 17, 22, 42, 18, 23})
755        for (int dt : {42, 20, 6, 8}) check(gu, dt, 2560, 640, s, rng);
756    check(21, 23, 2560, 768, s, rng);
757    // Q4-SYCL: the build's own expert shape (q4_lite 2048 x 512, q4_mid 3072 x 1024, q4_big 4096 x 1024): the UD mix's pairs (Q4_K / Q5_K gate/up;
758    // Q5_K, Q6_K, Q5_1, IQ4_NL, Q8_0 downs) against the CPU reference and split vs per-entry
759    if (strata::core::kCompiledGeometry.n_embd != 2560 || strata::core::kCompiledGeometry.n_ff != 640) {
760        const int64_t KH = strata::core::kCompiledGeometry.n_embd, KF = strata::core::kCompiledGeometry.n_ff;
761        std::printf("compiled shape %lld x %lld\n", (long long) KH, (long long) KF);
762        for (int gu : {12, 13})
763            for (int dt : {13,
764#ifdef STRATA_Q6K_EXPERTS
765                           14,
766#endif
767                           7, 8})   // (check_kq's reference has no IQ4_NL down: those pairs are in the loop below)
768                check_kq(gu, dt, KH, KF, s, rng);
769        for (int gu : {29, 16, 17, 22, 42, 18, 23, 21})
770            for (int dt : {42, 20, 6, 8}) check(gu, dt, KH, KF, s, rng);
771    }
772    if (do_bench) bench(s, rng);
773    std::printf("native_grouped_parity: %d failures\n", g_fail);
774    dpct::get_current_device().destroy_queue(s);
775    return g_fail ? 1 : 0;
776}