okami.mom/strata

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

Niko1221Merge branch 'f-142-intel' into f-1423fb23b146

main
34.0 KiB682 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#define DPCT_PROFILING_ENABLED
18#include <sycl/sycl.hpp>
19#include <dpct/dpct.hpp>
20#include "strata/kernels/f16_bits.hpp"
21#include "strata/kernels/iq_kernels.hpp"
22#include "strata/kernels/native_mmvq.hpp"
23
24#include <algorithm>
25#include <cmath>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29#include <numeric>
30#include <random>
31#include <string>
32#include <vector>
33
34namespace k = strata::kernels;
35
36namespace {
37
38int g_fail = 0;
39
40void ck(dpct::err0 e, const char *w) {
41}
42
43template<typename T>
44T* dalloc(size_t n) {
45    T* p = nullptr;
46    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
47                            n * sizeof(T) + 256, dpct::get_in_order_queue())),
48       "malloc");
49    ck(DPCT_CHECK_ERROR(
50           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 256).wait()),
51       "memset");
52    return p;
53}
54
55const char* name_of(int t) {
56    switch (t) {
57        case 16: return "IQ2_XXS";
58        case 17: return "IQ2_XS";
59        case 18: return "IQ3_XXS";
60        case 20: return "IQ4_NL";
61        case 21: return "IQ3_S";
62        case 22: return "IQ2_S";
63        case 23: return "IQ4_XS";
64        case 29: return "IQ1_M";
65        case 42: return "Q2_0";
66        default: return "?";
67    }
68}
69int block_values(int t) { return t == 20 ? 32 : t == 42 ? 64 : 256; }
70
71// `rows` rows of `n` values of format t: random bytes, then a finite fp16 scale in every block
72std::vector<uint8_t> random_rows(int t, int64_t rows, int64_t n, std::mt19937& rng) {
73    const size_t rb = k::iq_row_bytes(t, n), bs = k::iq_row_bytes(t, block_values(t));
74    std::vector<uint8_t> w((size_t) rows * rb);
75    std::uniform_int_distribution<int> byte(0, 255), ex(2, 8), man(0, 1023), sgn(0, 3);
76    for (auto& b : w) b = (uint8_t) byte(rng);
77    for (size_t o = 0; o < w.size(); o += bs) {
78        if (t == 29) {
79            // IQ1_M: the fp16 scale is the top nibbles of the four scale words (bytes 48..55); nibble 3 carries the
80            // sign and the exponent's top bits: 0x1 / 0x2 (or 0x9 / 0xA) keeps it in 2^-11 .. 2^-3
81            const uint8_t nib = (uint8_t) ((sgn(rng) == 0 ? 0x8 : 0x0) | (1 + (byte(rng) & 1)));
82            w[o + 55] = (uint8_t) ((w[o + 55] & 0x0F) | (nib << 4));
83        } else {
84            const uint16_t h = (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));   // 2^-13 .. 2^-6
85            std::memcpy(&w[o], &h, 2);
86        }
87    }
88    return w;
89}
90
91std::vector<float> random_x(size_t n, std::mt19937& rng) {
92    std::normal_distribution<float> nd(0.f, 1.f);
93    std::vector<float> x(n);
94    for (auto& v : x) v = nd(rng);
95    return x;
96}
97
98// q8_1 blocks (fp16 scale, fp16 sum, 32 int8) back to floats
99std::vector<double> dequant_q8_1(const std::vector<uint8_t>& q, size_t n) {
100    std::vector<double> v(n);
101    for (size_t b = 0; b < n / 32; ++b) {
102        uint16_t dh;
103        std::memcpy(&dh, &q[b * 36], 2);
104        const double d = k::f32_from_f16(dh);
105        for (int i = 0; i < 32; ++i) v[b * 32 + i] = d * (int8_t) q[b * 36 + 4 + i];
106    }
107    return v;
108}
109
110#include "iq2xs_host_tables.inc"
111// IQ2_XS decoded on the CPU from ggml's tables (dequantize_row_iq2_xs), a reference independent of the GPU dequantizer
112std::vector<float> host_iq2_xs(const std::vector<uint8_t>& w, size_t n) {
113    std::vector<float> y(n);
114    const size_t nb = n / 256;
115    for (size_t i = 0; i < nb; ++i) {
116        const uint8_t* b = w.data() + i * 74;   // fp16 d, 32 x uint16 qs, 8 scales
117        uint16_t dh; std::memcpy(&dh, b, 2);
118        const float d = k::f32_from_f16(dh);
119        const uint8_t* sc = b + 66;
120        for (int ib = 0; ib < 8; ++ib) {
121            const float db[2] = {d * (0.5f + (sc[ib] & 0xf)) * 0.25f, d * (0.5f + (sc[ib] >> 4)) * 0.25f};
122            for (int l = 0; l < 4; ++l) {
123                uint16_t q; std::memcpy(&q, b + 2 + 2 * (4 * ib + l), 2);
124                const uint64_t g = host_iq2xs_grid[q & 511];
125                const uint8_t signs = host_ksigns_iq2xs[q >> 9];
126                for (int j = 0; j < 8; ++j) {
127                    const float v = (float) ((g >> (8 * j)) & 0xff);
128                    y[i * 256 + ib * 32 + l * 8 + j] = db[l / 2] * v * ((signs >> j) & 1 ? -1.f : 1.f);
129                }
130            }
131        }
132    }
133    return y;
134}
135
136// ------------------------------------------------------------------------------------------------ (1) iq_mmvq
137void check_mmvq(int t, int n_in, int n_out, dpct::queue_ptr s,
138                std::mt19937 &rng) {
139    const auto w = random_rows(t, n_out, n_in, rng);
140    uint8_t* dw = dalloc<uint8_t>(w.size());
141    /*
142    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
143    in the original code the source host memory is pageable memory. If the
144    memory is not pageable, call wait() on event return by memcpy API to ensure
145    synchronization behavior.
146    */
147    ck(DPCT_CHECK_ERROR(
148           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dw, w.data(), w.size()).wait()),
149       "w");
150    // the double reference's weights: the GPU dequantizer (iq_parity checks it against gguf-py)
151    float* dwf = dalloc<float>((size_t) n_out * n_in);
152    k::iq_dequant_f32(t, dw, (int64_t) n_out * n_in, dwf, s);
153    std::vector<float> wf((size_t) n_out * n_in);
154    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
155                            .memcpy(wf.data(), dwf, wf.size() * 4)
156                            .wait()),
157       "wf");
158    const int max_cols = 11;
159    const auto x = random_x((size_t) max_cols * n_in, rng);
160    float* dx = dalloc<float>(x.size());
161    /*
162    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
163    in the original code the source host memory is pageable memory. If the
164    memory is not pageable, call wait() on event return by memcpy API to ensure
165    synchronization behavior.
166    */
167    ck(DPCT_CHECK_ERROR(
168           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
169       "x");
170    const size_t xq_bytes = (size_t) max_cols * (n_in / 32) * 36;
171    uint8_t* dxq = dalloc<uint8_t>(xq_bytes);
172    k::quantize_q8_1_rows(dx, max_cols, n_in, dxq, s);
173    std::vector<uint8_t> xq(xq_bytes);
174    ck(DPCT_CHECK_ERROR(
175           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(xq.data(), dxq, xq_bytes).wait()),
176       "xq");
177    const auto xd = dequant_q8_1(xq, (size_t) max_cols * n_in);
178    std::vector<float> hw;
179    if (t == 17) {   // IQ2_XS: the GPU dequantizer against the CPU decode
180        hw = host_iq2_xs(w, (size_t) n_out * n_in);
181        double md = 0, mx = 0;
182        size_t nd = 0;
183        for (size_t i = 0; i < hw.size(); ++i) {
184            md = std::max(md, (double) std::fabs(hw[i] - wf[i]));
185            mx = std::max(mx, (double) std::fabs(hw[i]));
186            nd += hw[i] != wf[i];
187        }
188        std::printf("  IQ2_XS GPU dequant vs CPU decode: %zu of %zu differ, worst %.3g (max |w| %.3g); w[0..3] cpu %g %g %g %g gpu %g %g %g %g\n",
189                    nd, hw.size(), md, mx, hw[0], hw[1], hw[2], hw[3], wf[0], wf[1], wf[2], wf[3]);
190    }
191    float* dy_old = dalloc<float>((size_t) max_cols * n_out);
192    float* dy_new = dalloc<float>((size_t) max_cols * n_out);
193    std::vector<float> y_old((size_t) max_cols * n_out), y_new(y_old.size());
194    const int cols[] = {1, 2, 3, 4, 5, 6, 7, 8, 11};
195    int bad = 0;
196    double worst = 0.0;
197    for (int nc : cols) {
198        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
199                                .memset(dy_old, 0xFF, y_old.size() * 4)
200                                .wait()),
201           "memset");
202        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
203                                .memset(dy_new, 0xFF, y_new.size() * 4)
204                                .wait()),
205           "memset");
206        k::iq_set_old_kernels(true);
207        k::iq_mmvq(t, dw, dxq, dy_old, n_in, n_out, nc, s);
208        k::iq_set_old_kernels(false);
209        k::iq_mmvq(t, dw, dxq, dy_new, n_in, n_out, nc, s);
210        ck(DPCT_CHECK_ERROR(s->wait()), "sync");
211        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
212                                .memcpy(y_old.data(), dy_old, y_old.size() * 4)
213                                .wait()),
214           "y_old");
215        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
216                                .memcpy(y_new.data(), dy_new, y_new.size() * 4)
217                                .wait()),
218           "y_new");
219        size_t diff = 0;
220        for (size_t i = 0; i < y_old.size(); ++i) diff += std::memcmp(&y_old[i], &y_new[i], 4) != 0;
221        double num = 0, den = 0;
222        bool finite = true;
223        for (int c = 0; c < nc; ++c)
224            for (int r = 0; r < n_out; ++r) {
225                double acc = 0;
226                for (int i = 0; i < n_in; ++i) acc += (double) wf[(size_t) r * n_in + i] * xd[(size_t) c * n_in + i];
227                const float g = y_new[(size_t) c * n_out + r];
228                finite = finite && std::isfinite(g);
229                num += std::fabs(g - acc);
230                den += std::fabs(acc);
231            }
232        const double rel = num / (den + 1e-30);
233        if (t == 17 && nc == 1) {
234            double hn = 0, hd = 0;
235            for (int r = 0; r < n_out; ++r) {
236                double acc = 0;
237                for (int i = 0; i < n_in; ++i) acc += (double) hw[(size_t) r * n_in + i] * xd[(size_t) i];
238                hn += std::fabs(y_new[(size_t) r] - acc); hd += std::fabs(acc);
239            }
240            std::printf("  IQ2_XS mmvq vs the CPU-decode reference: rel %.2e; y[0..2] gpu %g %g %g\n", hn / (hd + 1e-30),
241                        y_new[0], y_new[1], y_new[2]);
242        }
243        worst = std::max(worst, rel);
244        if (diff != 0 || !finite || !(rel < 1e-2)) {
245            std::printf("  %-8s %5d x %5d  ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s  FAIL\n",
246                        name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite");
247            ++bad;
248        }
249    }
250    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,
251                bad ? "FAIL" : "bitwise equal to the old kernel", worst);
252    g_fail += bad;
253    sycl::free(dw, dpct::get_in_order_queue());
254        sycl::free(dwf, dpct::get_in_order_queue());
255        sycl::free(dx, dpct::get_in_order_queue());
256        sycl::free(dxq, dpct::get_in_order_queue());
257        sycl::free(dy_old, dpct::get_in_order_queue());
258        sycl::free(dy_new, dpct::get_in_order_queue());
259}
260
261// ---------------------------------------------------------------------------------- (2) native_expert_grouped
262struct Grouped {
263    k::NativeExpertLayout L;
264    int n_groups = 0, n_ent = 0, cap_groups = 0, cap_ent = 0, n_tok = 0;
265    std::vector<uint8_t*> blobs;
266    unsigned long long* dptr = nullptr;
267    int32_t *dstart = nullptr, *dn = nullptr, *ddst = nullptr, *dtok = nullptr;
268    float* dx = nullptr;
269    uint8_t *dxq = nullptr, *dscr = nullptr;
270    float* dout = nullptr;
271    size_t out_floats = 0;
272    std::vector<int32_t> h_start, h_tok, h_dst;   // the host copies, for reference()
273
274    Grouped(int gu, int dt, int64_t H, int64_t FF, const std::vector<int>& counts, int tokens, std::mt19937& rng) {
275        L = k::native_expert_layout(gu, dt, H, FF);
276        n_groups = (int) counts.size();
277        cap_groups = n_groups + 2;              // the extra grid rows must exit
278        n_tok = tokens;
279        std::vector<int32_t> start(1, 0), tok, dst;
280        for (int c : counts) start.push_back(start.back() + c);
281        n_ent = start.back();
282        cap_ent = n_ent + 3;
283        h_start = start;
284        std::uniform_int_distribution<int> tk(0, tokens - 1);
285        for (int e = 0; e < n_ent; ++e) tok.push_back(tk(rng));
286        dst.resize(n_ent);
287        std::iota(dst.begin(), dst.end(), 0);
288        std::shuffle(dst.begin(), dst.end(), rng);
289        h_tok = tok;
290        h_dst = dst;
291        std::vector<unsigned long long> ptr;
292        for (int g = 0; g < n_groups; ++g) {
293            // one blob per group: gate rows | up rows (format gu, H values) | down rows (format dt, FF values)
294            auto b = random_rows(gu, 2 * FF, H, rng);
295            const auto d = random_rows(dt, H, FF, rng);
296            b.insert(b.end(), d.begin(), d.end());
297            if (b.size() != L.bytes) { std::fprintf(stderr, "blob size %zu != %zu\n", b.size(), L.bytes); std::exit(2); }
298            uint8_t* db = dalloc<uint8_t>(b.size());
299            /*
300            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
301            assuming in the original code the source host memory is pageable
302            memory. If the memory is not pageable, call wait() on event return
303            by memcpy API to ensure synchronization behavior.
304            */
305            ck(DPCT_CHECK_ERROR(
306                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(db, b.data(), b.size()).wait()),
307               "blob");
308            blobs.push_back(db);
309            ptr.push_back((unsigned long long) db);
310        }
311        dptr = dalloc<unsigned long long>(cap_groups);
312        dstart = dalloc<int32_t>(cap_groups + 1);
313        dn = dalloc<int32_t>(1);
314        ddst = dalloc<int32_t>(cap_ent);
315        dtok = dalloc<int32_t>(cap_ent);
316        /*
317        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
318        assuming in the original code the source host memory is pageable memory.
319        If the memory is not pageable, call wait() on event return by memcpy API
320        to ensure synchronization behavior.
321        */
322        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dptr, ptr.data(),
323                                                              ptr.size() * 8).wait()),
324           "ptr");
325        /*
326        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
327        assuming in the original code the source host memory is pageable memory.
328        If the memory is not pageable, call wait() on event return by memcpy API
329        to ensure synchronization behavior.
330        */
331        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
332               dstart, start.data(), start.size() * 4).wait()),
333           "start");
334        ck(DPCT_CHECK_ERROR(
335               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dn, &n_groups, 4).wait()),
336           "n");
337        if (n_ent) {
338            /*
339            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
340            assuming in the original code the source host memory is pageable
341            memory. If the memory is not pageable, call wait() on event return
342            by memcpy API to ensure synchronization behavior.
343            */
344            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
345                   ddst, dst.data(), dst.size() * 4).wait()),
346               "dst");
347            /*
348            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
349            assuming in the original code the source host memory is pageable
350            memory. If the memory is not pageable, call wait() on event return
351            by memcpy API to ensure synchronization behavior.
352            */
353            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
354                   dtok, tok.data(), tok.size() * 4).wait()),
355               "tok");
356        }
357        const auto x = random_x((size_t) tokens * H, rng);
358        dx = dalloc<float>(x.size());
359        /*
360        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
361        assuming in the original code the source host memory is pageable memory.
362        If the memory is not pageable, call wait() on event return by memcpy API
363        to ensure synchronization behavior.
364        */
365        ck(DPCT_CHECK_ERROR(
366               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
367           "x");
368        dxq = dalloc<uint8_t>((size_t) tokens * (H / 32) * 36);
369        dscr = dalloc<uint8_t>(k::native_expert_scratch_bytes(cap_ent, FF));
370        out_floats = (size_t) cap_ent * H;
371        dout = dalloc<float>(out_floats);
372    }
373    ~Grouped() {
374        for (auto *b : blobs)
375            DPCT_CHECK_ERROR(sycl::free(b, dpct::get_in_order_queue()));
376        sycl::free(dptr, dpct::get_in_order_queue());
377            sycl::free(dstart, dpct::get_in_order_queue());
378            sycl::free(dn, dpct::get_in_order_queue());
379            sycl::free(ddst, dpct::get_in_order_queue());
380            sycl::free(dtok, dpct::get_in_order_queue());
381        sycl::free(dx, dpct::get_in_order_queue());
382            sycl::free(dxq, dpct::get_in_order_queue());
383            sycl::free(dscr, dpct::get_in_order_queue());
384            sycl::free(dout, dpct::get_in_order_queue());
385    }
386    void run(bool old, dpct::queue_ptr s) {
387        k::iq_set_old_kernels(old);
388        k::quantize_q8_1_rows(dx, n_tok, L.n_embd, dxq, s);
389        k::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, cap_groups, cap_ent, dxq, dscr, dout, s);
390        k::iq_set_old_kernels(false);
391    }
392    // An independent reference: every entry through iq_mmvq (itself checked against a double-precision CPU reference
393    // above), one column at a time - gate and up rows against the token's q8_1 activations, SwiGLU into q8_1, the down
394    // rows against that.  Not bitwise the grouped path (accumulation order), so it is compared with a tolerance.
395    std::vector<float> reference(dpct::queue_ptr s) {
396        const int64_t H = L.n_embd, FF = L.n_ff;
397        float *g = dalloc<float>(FF), *u = dalloc<float>(FF), *y = dalloc<float>(H);
398        uint8_t* hq = dalloc<uint8_t>((size_t) (FF / 32) * 36 + 64);
399        std::vector<float> out(out_floats, 0.0f);
400        std::vector<unsigned long long> ptr(n_groups);
401        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
402                                .memcpy(ptr.data(), dptr, ptr.size() * 8).wait()), "ptr");
403        for (int gi = 0; gi < n_groups; ++gi) {
404            const uint8_t* blob = (const uint8_t*) ptr[gi];
405            for (int e = h_start[gi]; e < h_start[gi + 1]; ++e) {
406                const uint8_t* xq = dxq + (size_t) h_tok[e] * (H / 32) * 36;
407                k::iq_mmvq(L.gu_type, blob, xq, g, (int) H, (int) FF, 1, s);
408                k::iq_mmvq(L.gu_type, blob + L.up_off, xq, u, (int) H, (int) FF, 1, s);
409                k::native_swiglu_quantize_q8_1(g, u, hq, (int) FF, 1, s);
410                k::iq_mmvq(L.d_type, blob + L.down_off, hq, y, (int) FF, (int) H, 1, s);
411                ck(DPCT_CHECK_ERROR(s->wait()), "ref sync");
412                ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
413                                        .memcpy(out.data() + (size_t) h_dst[e] * H, y, (size_t) H * 4).wait()), "ref out");
414            }
415        }
416        sycl::free(g, dpct::get_in_order_queue()); sycl::free(u, dpct::get_in_order_queue());
417        sycl::free(y, dpct::get_in_order_queue()); sycl::free(hq, dpct::get_in_order_queue());
418        return out;
419    }
420    std::vector<float> result(bool old, dpct::queue_ptr s) {
421        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
422                                .memset(dout, 0xFF, out_floats * 4)
423                                .wait()),
424           "memset"); // NaN rows: must stay NaN where nothing writes
425        ck(DPCT_CHECK_ERROR(
426               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
427                   .memset(dscr, 0,
428                           k::native_expert_scratch_bytes(cap_ent, L.n_ff))
429                   .wait()),
430           "memset");
431        run(old, s);
432        ck(DPCT_CHECK_ERROR(s->wait()), "sync");
433        std::vector<float> o(out_floats);
434        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
435                                .memcpy(o.data(), dout, o.size() * 4)
436                                .wait()),
437           "out");
438        return o;
439    }
440};
441
442void check_grouped(int gu, int dt, int64_t H, int64_t FF, dpct::queue_ptr s,
443                   std::mt19937 &rng) {
444    // 0..11 entries per group: one pass, a partial pass, two passes and three passes of GRP_NC = 4
445    Grouped G(gu, dt, H, FF, {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8, rng);
446    const auto a = G.result(true, s), b = G.result(false, s);
447    size_t diff = 0, written = 0;
448    bool finite = true;
449    for (size_t i = 0; i < a.size(); ++i) {
450        diff += std::memcmp(&a[i], &b[i], 4) != 0;
451        if (i < (size_t) G.n_ent * H) { ++written; finite = finite && std::isfinite(b[i]); }
452    }
453    // against the independent reference: the lane kernels (the default) and the other path, rows that are written
454    {
455        const auto r = G.reference(s);
456        auto bad = [&](const std::vector<float>& v) {
457            float mx = 0;
458            for (size_t i = 0; i < (size_t) G.n_ent * H; ++i) mx = std::max(mx, std::fabs(r[i]));
459            size_t n = 0;
460            for (size_t i = 0; i < (size_t) G.n_ent * H; ++i) n += !(std::fabs(v[i] - r[i]) <= 0.05f * mx);
461            return n;
462        };
463        const size_t ba = bad(a), bb = bad(b);
464        std::printf("%-8s/%-7s %5lld x %4lld  vs the mmvq reference: lane kernels %zu, other path %zu of %zu rows-values "
465                    "outside 5%% of the max%s\n", name_of(gu), name_of(dt), (long long) H, (long long) FF, ba, bb,
466                    (size_t) G.n_ent * H, ba || bb ? "  <== FAIL" : "");
467        if (ba) ++g_fail;
468    }
469    const bool ok = diff == 0 && finite;
470    std::printf("%-8s/%-7s %5lld x %4lld  native_expert_grouped, %d groups, %d entries: %s\n", name_of(gu),
471                name_of(dt), (long long) H, (long long) FF, G.n_groups, G.n_ent,
472                ok ? "bitwise equal to the old kernels" : "FAIL");
473    if (!ok) {
474        std::printf("  %zu of %zu floats differ%s\n", diff, a.size(), finite ? "" : ", non-finite outputs");
475        ++g_fail;
476    }
477}
478
479// ------------------------------------------------------------------------------------------------ --bench
480float time_ms(dpct::queue_ptr s, int it, const auto &fn) {
481    dpct::event_ptr e0, e1;
482    e0 = new sycl::event();
483    e1 = new sycl::event();
484    fn();
485    dpct::sync_barrier(e0, s);
486    for (int i = 0; i < it; ++i) fn();
487    dpct::sync_barrier(e1, s);
488    ck(DPCT_CHECK_ERROR(e1->wait_and_throw()), "bench");
489    float ms = 0;
490    ms =
491        (e1->get_profiling_info<sycl::info::event_profiling::command_end>() -
492         e0->get_profiling_info<sycl::info::event_profiling::command_start>()) /
493        1000000.0f;
494    dpct::destroy_event(e0);
495    dpct::destroy_event(e1);
496    return ms / it;
497}
498
499void bench(dpct::queue_ptr s, std::mt19937 &rng) {
500    std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n");
501    const int n_in = 2560, n_out = 8192, it = 200;
502    for (int t : {16, 17, 18, 21, 22, 29}) {
503        const auto w = random_rows(t, n_out, n_in, rng);
504        uint8_t* dw = dalloc<uint8_t>(w.size());
505        /*
506        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
507        assuming in the original code the source host memory is pageable memory.
508        If the memory is not pageable, call wait() on event return by memcpy API
509        to ensure synchronization behavior.
510        */
511        ck(DPCT_CHECK_ERROR(
512               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dw, w.data(), w.size()).wait()),
513           "w");
514        const auto x = random_x((size_t) 8 * n_in, rng);
515        float* dx = dalloc<float>(x.size());
516        /*
517        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
518        assuming in the original code the source host memory is pageable memory.
519        If the memory is not pageable, call wait() on event return by memcpy API
520        to ensure synchronization behavior.
521        */
522        ck(DPCT_CHECK_ERROR(
523               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
524           "x");
525        uint8_t* dxq = dalloc<uint8_t>((size_t) 8 * (n_in / 32) * 36);
526        k::quantize_q8_1_rows(dx, 8, n_in, dxq, s);
527        float* dy = dalloc<float>((size_t) 8 * n_out);
528        std::printf("%-8s iq_mmvq %d x %d:", name_of(t), n_out, n_in);
529        for (int nc = 1; nc <= 8; ++nc) {
530            float us[2];
531            for (int old = 1; old >= 0; --old) {
532                k::iq_set_old_kernels(old != 0);
533                us[old] = 1e3f * time_ms(s, it, [&] { k::iq_mmvq(t, dw, dxq, dy, n_in, n_out, nc, s); });
534            }
535            std::printf("  %d: %.1f/%.1f", nc, us[1], us[0]);
536        }
537        std::printf("\n");
538        k::iq_set_old_kernels(false);
539        sycl::free(dw, dpct::get_in_order_queue());
540            sycl::free(dx, dpct::get_in_order_queue());
541            sycl::free(dxq, dpct::get_in_order_queue());
542            sycl::free(dy, dpct::get_in_order_queue());
543    }
544    // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each
545    for (int gu : {16, 17, 18, 21, 22, 29}) {
546        std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu));
547        for (int m : {1, 2, 3, 4, 8}) {
548            Grouped G(gu, 42, 2560, 640, std::vector<int>(16, m), 8, rng);
549            float us[2];
550            for (int old = 1; old >= 0; --old)
551                us[old] = 1e3f * time_ms(s, 50, [&] { G.run(old != 0, s); });
552            std::printf("  m=%d: %.1f/%.1f", m, us[1], us[0]);
553        }
554        std::printf("\n");
555    }
556}
557
558// #606: the q8_1 activation quantizers (quantize_q8_1_rows, native_quantize_q8_1 and the shared expert's fused
559// native_swiglu_quantize_q8_1) against a host transcription of the 0.1.38 formula: every finite block bit for bit; a
560// block whose sum (or scale) overflowed fp16 is now stored finite (the largest half, its sign), with its values in the
561// int8 range.  The fused one gets gate = 32 and up = x / 32: silu(32) is 32 in float, so its activations are x exactly.
562void check_q8_1_finite(dpct::queue_ptr s, std::mt19937 &rng) {
563    const int n = 2560, rows = 3, nb = n / 32;
564    std::vector<float> x = random_x((size_t) rows * n, rng);
565    for (int i = 0; i < 32; ++i) x[(size_t) 5 * 32 + i] = 3000.0f;                  // sum 96,000: overflowed
566    for (int i = 0; i < 32; ++i) x[(size_t) 9 * 32 + i] = i == 3 ? -70000.0f : 0.5f;   // sum -69,984.5
567    for (int i = 0; i < 32; ++i) x[(size_t) 13 * 32 + i] = 2000.0f + i;            // sum 64,496: finite, kept
568    x[(size_t) n + 40] = 2.0e7f;                                                    // amax / 127 overflowed too
569    float* dx = dalloc<float>(x.size());
570    /*
571    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
572    in the original code the source host memory is pageable memory. If the
573    memory is not pageable, call wait() on event return by memcpy API to ensure
574    synchronization behavior.
575    */
576    ck(DPCT_CHECK_ERROR(
577           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, x.data(), x.size() * 4).wait()),
578       "x");
579    std::vector<float> gate(x.size(), 32.0f), up(x.size());
580    for (size_t i = 0; i < x.size(); ++i) up[i] = x[i] / 32.0f;
581    float* dg = dalloc<float>(x.size());
582    float* du = dalloc<float>(x.size());
583    /*
584    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
585    in the original code the source host memory is pageable memory. If the
586    memory is not pageable, call wait() on event return by memcpy API to ensure
587    synchronization behavior.
588    */
589    ck(DPCT_CHECK_ERROR(
590           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dg, gate.data(), x.size() * 4).wait()),
591       "gate");
592    /*
593    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming
594    in the original code the source host memory is pageable memory. If the
595    memory is not pageable, call wait() on event return by memcpy API to ensure
596    synchronization behavior.
597    */
598    ck(DPCT_CHECK_ERROR(
599           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(du, up.data(), x.size() * 4).wait()),
600       "up");
601    uint8_t* dq = dalloc<uint8_t>((size_t) rows * nb * 36);
602    for (int path = 0; path < 3; ++path) {
603        if (path == 0) k::quantize_q8_1_rows(dx, rows, n, dq, s);
604        else if (path == 1) k::native_quantize_q8_1(dx, dq, n, rows, s);
605        else k::native_swiglu_quantize_q8_1(dg, du, dq, n, rows, s);
606        ck(DPCT_CHECK_ERROR(s->wait()), "quantize");
607        std::vector<uint8_t> got((size_t) rows * nb * 36);
608        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
609                                .memcpy(got.data(), dq, got.size())
610                                .wait()),
611           "q");
612        int same = 0, clamped = 0, bad = 0;
613        for (int b = 0; b < rows * nb; ++b) {
614            const float* v = x.data() + (size_t) b * 32;
615            float lane[32], amax = 0.0f;
616            for (int i = 0; i < 32; ++i) { lane[i] = v[i]; amax = std::max(amax, std::fabs(v[i])); }
617            for (int o = 16; o > 0; o >>= 1) {   // the warp's butterfly: every lane ends with the same sum
618                float nx[32];
619                for (int i = 0; i < 32; ++i) nx[i] = lane[i] + lane[i ^ o];
620                std::memcpy(lane, nx, sizeof lane);
621            }
622            const float d = amax / 127.0f, sum = lane[0];
623            const uint8_t* g = got.data() + (size_t) b * 36;
624            uint16_t gd, gs;
625            std::memcpy(&gd, g, 2);
626            std::memcpy(&gs, g + 2, 2);
627            const uint16_t od = k::f16_from_f32(d), os = k::f16_from_f32(sum);
628            const bool finite_before = (od & 0x7c00) != 0x7c00 && (os & 0x7c00) != 0x7c00;
629            if (finite_before) {
630                uint8_t want[36];
631                std::memcpy(want, &od, 2);
632                std::memcpy(want + 2, &os, 2);
633                for (int i = 0; i < 32; ++i)   // CUDA's roundf: half away from zero, as std::round
634                    want[4 + i] = (uint8_t) (int8_t) (amax == 0.0f ? 0.0f : std::round(v[i] / d));
635                // native_mmvq.cu is built with --use_fast_math (its divisions are approximate): there the sum must be
636                // the same bits, the scale within one fp16 step and each value within one step
637                bool near = path >= 1 && gs == os && std::abs((int) gd - (int) od) <= 1;
638                for (int i = 0; near && i < 32; ++i) near = std::abs((int) (int8_t) g[4 + i] - (int) (int8_t) want[4 + i]) <= 1;
639                if (std::memcmp(want, g, 36) == 0 || near) ++same;
640                else { ++bad; std::printf("  q8_1 path %d block %d: changed although it was finite\n", path, b); }
641            } else {
642                const float fd = k::f32_from_f16(gd), fs = k::f32_from_f16(gs);
643                bool ok = std::isfinite(fd) && std::isfinite(fs) && fd > 0.0f &&
644                          ((os & 0x7c00) != 0x7c00 ? gs == os : std::fabs(fs) == 65504.0f && (fs < 0) == (sum < 0));
645                for (int i = 0; i < 32; ++i) ok = ok && (int8_t) g[4 + i] >= -127 && (int8_t) g[4 + i] <= 127;
646                if (ok) ++clamped;
647                else { ++bad; std::printf("  q8_1 path %d block %d: d %g sum %g not finite and clamped\n", path, b, fd, fs); }
648            }
649        }
650        std::printf("q8_1 finite (%s): %d finite blocks as before, %d overflowed blocks clamped finite%s\n",
651                    path == 0 ? "quantize_q8_1_rows" : path == 1 ? "native_quantize_q8_1" : "native_swiglu_quantize_q8_1",
652                    same, clamped, bad ? "  FAIL" : "");
653        g_fail += bad + (clamped != 3);
654    }
655    sycl::free(dx, dpct::get_in_order_queue());
656    sycl::free(dg, dpct::get_in_order_queue());
657    sycl::free(du, dpct::get_in_order_queue());
658    sycl::free(dq, dpct::get_in_order_queue());
659}
660
661}  // namespace
662
663int main(int argc, char** argv) {
664    const bool do_bench = argc > 1 && std::string(argv[1]) == "--bench";
665    dpct::queue_ptr s;
666    ck(DPCT_CHECK_ERROR(s = dpct::get_current_device().create_queue(true)),
667       "stream");
668    std::mt19937 rng(18);
669    for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) {
670        check_mmvq(t, 2560, 67, s, rng);   // the model's n_embd; 67 rows: a partial block of 4 rows
671        check_mmvq(t, 1024, 5, s, rng);
672    }
673    for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) {
674        for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng);   // the model's shape
675        check_grouped(gu, 23, 1024, 512, s, rng);                           // IQ4_XS down needs n_ff % 256 == 0
676    }
677    check_q8_1_finite(s, rng);
678    if (do_bench) bench(s, rng);
679    std::printf("iq_multi_parity: %d failures\n", g_fail);
680    dpct::get_current_device().destroy_queue(s);
681    return g_fail ? 1 : 0;
682}