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
15.3 KiB290 linesraw
1// sycl/src/kernels/dq_dense_parity.cpp - model-free check of the Qwen engine's dense weight kernels on a SYCL device against the
2// CPU dequantizers of include/strata/artifact/dequant.hpp (ggml's dequantize_row_*): for every dense type the engine reads
3// (Q4_0 Q5_0 Q5_1 Q8_0 Q3_K Q4_K Q5_K Q6_K IQ4_NL IQ4_XS Q2_0), random legal blocks, no model file.
4//   dequant   dequant_f32 / dequant_f16 / dequant_bf16 / dequant_f16_ld, the per-group kernels (and, with -DDQ_HAVE_WIDE, the
5//             CUDA wide ones: dequant_set_wide 0 / 1), whole matrices and row slices, widths with k % 1024 == 0 and without
6//   mmvq      native_mmvq (the decode token's GEMV, 1 .. 8 columns) against a double reference on the Q8_1 activations as the
7//             kernel got them
8// Every element must be written (the output starts as NaN), finite, and equal to the CPU value (F32: 1e-6 relative; F16 / BF16:
9// the CPU value rounded the same way; mmvq: 5e-3 of the sum of |terms|).  Prints RESULT lines and SUMMARY; exit 1 on any failure.
10//   dq_dense_parity [--quick]
11#define DPCT_PROFILING_ENABLED
12#include <sycl/sycl.hpp>
13#include <dpct/dpct.hpp>
14#include "strata/artifact/dequant.hpp"
15#include "strata/kernels/dequant_bf16.hpp"
16#include "strata/kernels/native_mmvq.hpp"
17#include "strata/sycl_queue.hpp"
18
19#include <algorithm>
20#include <cmath>
21#include <cstdint>
22#include <cstdio>
23#include <cstring>
24#include <map>
25#include <random>
26#include <string>
27#include <vector>
28
29namespace K = strata::kernels;
30
31namespace {
32
33struct Ty { int id; const char* name; int be, bb; };
34const Ty kTys[] = {{2, "Q4_0", 32, 18}, {6, "Q5_0", 32, 22}, {7, "Q5_1", 32, 24}, {8, "Q8_0", 32, 34}, {11, "Q3_K", 256, 110},
35                   {12, "Q4_K", 256, 144}, {13, "Q5_K", 256, 176}, {14, "Q6_K", 256, 210}, {20, "IQ4_NL", 32, 18},
36                   {23, "IQ4_XS", 256, 136}, {42, "Q2_0", 64, 18}};
37
38uint16_t f2h(float f) {
39    uint32_t u; std::memcpy(&u, &f, 4);
40    const uint32_t s = (u >> 16) & 0x8000u;
41    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) (s | 0x7e00u);
42    const float a = std::fabs(f);
43    if (a >= 65520.0f) return (uint16_t) (s | 0x7c00u);
44    if (a < 6.103515625e-05f) return (uint16_t) (s | (uint32_t) std::nearbyint(std::ldexp((double) a, 24)));
45    const int e = (int) ((u >> 23) & 0xff) - 127 + 15;
46    uint32_t v = ((uint32_t) e << 10) | ((u & 0x7fffffu) >> 13);
47    const uint32_t rem = u & 0x1fffu;
48    if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
49    return (uint16_t) (s | v);
50}
51uint16_t f2bf(float f) {
52    uint32_t u; std::memcpy(&u, &f, 4);
53    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40u);
54    return (uint16_t) ((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
55}
56
57// F16 scales at the right place, sane
58void sane(int id, uint8_t* p, std::mt19937_64& rng) {
59    auto put = [&](int off) { const uint16_t h = f2h(0.02f + 0.0002f * (float) (rng() % 600)); std::memcpy(p + off, &h, 2); };
60    switch (id) {
61        case 11: put(108); break;
62        case 14: put(208); break;
63        case 12: case 13: put(0); put(2); break;
64        case 7: put(0); put(2); break;   // Q5_1: d, m
65        default: put(0); break;
66    }
67}
68void cpu_block(int id, const uint8_t* b, float* out) {
69    using namespace strata;
70    switch (id) {
71        case 2: dequantize_q4_0(b, out); break;
72        case 6: dequantize_q5_0(b, out); break;
73        case 7: dequantize_q5_1(b, out); break;
74        case 8: dequantize_q8_0(b, out); break;
75        case 11: dequantize_q3_K(b, out); break;
76        case 12: dequantize_q4_K(b, out); break;
77        case 13: dequantize_q5_K(b, out); break;
78        case 14: dequantize_q6_K(b, out); break;
79        case 20: dequantize_iq4_nl(b, out); break;
80        case 23: dequantize_iq4_xs(b, out); break;
81        case 42: dequantize_q2_0(b, out); break;
82    }
83}
84
85struct Tally { int cases = 0, fail = 0; std::string first; };
86std::map<std::string, Tally> g_res;
87int g_fails = 0;
88void fail(Tally& t, const std::string& s) {
89    ++t.fail; ++g_fails;
90    if (t.first.empty()) t.first = s;
91    std::printf("  FAIL %s\n", s.c_str());
92}
93
94sycl::queue& Q() { return *strata::q_of(nullptr); }
95void* S() { return (void*) &Q(); }   // (native MMVQ wants an explicit, non-null stream)
96
97void run_dequant(const Ty& ty, bool quick) {
98    sycl::queue& q = Q();
99    const int cols_list[] = {256, 512, 1024, 2048, 4096, 5120};
100    const int rows_list[] = {1, 3, 33, 130};
101    for (int mode : {0, 1}) {
102#ifndef DQ_HAVE_WIDE   // (the wide kernels are CUDA's: the SYCL build declares dequant_set_wide and does not define it)
103        if (mode) continue;
104#else
105        K::dequant_set_wide(mode);
106#endif
107        for (int form = 0; form < 4; ++form) {   // 0 f32, 1 f16, 2 bf16, 3 f16 with a padded row stride
108            const char* fn[] = {"f32", "f16", "bf16", "f16_ld"};
109            Tally& t = g_res[std::string(ty.name) + " dequant-" + fn[form] + (mode ? " wide" : " group")];
110            for (int cols : cols_list) {
111                if (quick && cols != 1024 && cols != 5120) continue;
112                if (cols % ty.be) continue;
113                for (int rows : rows_list) {
114                    if (quick && rows != 33) continue;
115                    for (int row0 : {0, 2}) {
116                        std::mt19937_64 rng((uint64_t) ty.id * 7919 + cols * 13 + rows + row0 * 101);
117                        const size_t rb = (size_t) cols / ty.be * ty.bb;
118                        std::vector<uint8_t> raw((size_t) (rows + row0) * rb);
119                        for (auto& b : raw) b = (uint8_t) rng();
120                        for (size_t b = 0; b < raw.size() / ty.bb; ++b) sane(ty.id, &raw[b * ty.bb], rng);
121                        std::vector<float> ref((size_t) rows * cols);
122                        for (int r = 0; r < rows; ++r)
123                            for (int b = 0; b < cols / ty.be; ++b) cpu_block(ty.id, &raw[(size_t) (r + row0) * rb + (size_t) b * ty.bb], &ref[(size_t) r * cols + (size_t) b * ty.be]);
124                        uint8_t* d_raw = sycl::malloc_device<uint8_t>(raw.size(), q);
125                        q.memcpy(d_raw, raw.data(), raw.size()).wait();
126                        const int64_t ld = form == 3 ? cols + 8 : cols;
127                        const size_t cnt = (size_t) rows * ld;
128                        const size_t esz = form == 0 ? 4 : 2;
129                        void* d_out = sycl::malloc_device(cnt * esz + 64, q);
130                        std::vector<uint8_t> nanv(cnt * esz, 0xFF);
131                        q.memcpy(d_out, nanv.data(), nanv.size()).wait();
132                        ++t.cases;
133                        char tag[160];
134                        std::snprintf(tag, sizeof tag, "%s %s %s cols=%d rows=%d row0=%d", ty.name, fn[form], mode ? "wide" : "group", cols, rows, row0);
135                        try {
136                            if (form == 0) K::dequant_f32(ty.id, d_raw, row0, rows, cols, (float*) d_out, S());
137                            else if (form == 1) K::dequant_f16(ty.id, d_raw, row0, rows, cols, (uint16_t*) d_out, S());
138                            else if (form == 2) K::dequant_bf16(ty.id, d_raw, row0, rows, cols, (uint16_t*) d_out, S());
139                            else if (!K::dequant_f16_ld(ty.id, d_raw, row0, rows, cols, ld, (uint16_t*) d_out, S())) {
140                                std::printf("  note: %s refused by dequant_f16_ld\n", tag);
141                                sycl::free(d_raw, q); sycl::free(d_out, q);
142                                continue;
143                            }
144                            q.wait();
145                        } catch (const std::exception& e) {
146                            fail(t, std::string(tag) + ": exception " + e.what());
147                            sycl::free(d_raw, q); sycl::free(d_out, q);
148                            continue;
149                        }
150                        std::vector<uint8_t> out(cnt * esz);
151                        q.memcpy(out.data(), d_out, out.size()).wait();
152                        size_t bad = 0, unw = 0, nonf = 0;
153                        size_t first = (size_t) -1;
154                        for (int r = 0; r < rows; ++r)
155                            for (int c = 0; c < cols; ++c) {
156                                const size_t i = (size_t) r * ld + c, ri = (size_t) r * cols + c;
157                                bool ok;
158                                if (form == 0) {
159                                    float v; std::memcpy(&v, &out[i * 4], 4);
160                                    uint32_t u; std::memcpy(&u, &out[i * 4], 4);
161                                    if (u == 0xFFFFFFFFu) { ++unw; ok = false; }
162                                    else if (!std::isfinite(v)) { ++nonf; ok = false; }
163                                    else ok = std::fabs(v - ref[ri]) <= 1e-6 * std::fabs(ref[ri]) + 1e-30;
164                                } else {
165                                    uint16_t h; std::memcpy(&h, &out[i * 2], 2);
166                                    if (h == 0xFFFFu) { ++unw; ok = false; }
167                                    else {
168                                        const uint16_t want = form == 2 ? f2bf(ref[ri]) : f2h(ref[ri]);
169                                        ok = h == want || std::abs((int) h - (int) want) == 1;   // (1 ulp: reported as ok, the CPU rounds from a different path)
170                                    }
171                                }
172                                if (!ok) { ++bad; if (first == (size_t) -1) first = ri; }
173                            }
174                        if (bad) {
175                            char b[300];
176                            std::snprintf(b, sizeof b, "%s: %zu wrong (%zu unwritten, %zu non-finite), first at element %zu", tag, bad, unw, nonf, first);
177                            fail(t, b);
178                        }
179                        sycl::free(d_raw, q); sycl::free(d_out, q);
180                    }
181                }
182            }
183        }
184    }
185#ifdef DQ_HAVE_WIDE
186    K::dequant_set_wide(-1);
187#endif
188}
189
190void run_mmvq(const Ty& ty, bool quick) {
191    if (!K::native_mmvq_supported(ty.id)) return;
192    sycl::queue& q = Q();
193    Tally& t = g_res[std::string(ty.name) + " mmvq"];
194    std::mt19937_64 xr(5);
195    std::normal_distribution<float> nd(0.f, 1.f);
196    for (int n_in : {256, 1024, 2048, 2560, 3072, 4096}) {   // Q4-SYCL: and the Qwen4 test shapes' hidden widths 2048 and 3072
197        if (n_in % ty.be) continue;
198        if (quick && n_in != 1024 && n_in != 2048 && n_in != 2560 && n_in != 3072 && n_in != 4096) continue;
199        for (int n_out : {1, 7, 8, 33, 130}) {
200            if (quick && n_out != 33) continue;
201            for (int nc : {1, 2, 4, 5, 8}) {
202                if (quick && nc != 1 && nc != 5) continue;
203                std::mt19937_64 rng((uint64_t) ty.id * 31 + n_in + n_out * 7);
204                const size_t rb = (size_t) n_in / ty.be * ty.bb;
205                std::vector<uint8_t> raw((size_t) n_out * rb);
206                for (auto& b : raw) b = (uint8_t) rng();
207                for (size_t b = 0; b < raw.size() / ty.bb; ++b) sane(ty.id, &raw[b * ty.bb], rng);
208                std::vector<float> wf((size_t) n_out * n_in);
209                for (int r = 0; r < n_out; ++r)
210                    for (int b = 0; b < n_in / ty.be; ++b) cpu_block(ty.id, &raw[(size_t) r * rb + (size_t) b * ty.bb], &wf[(size_t) r * n_in + (size_t) b * ty.be]);
211                std::vector<float> x((size_t) nc * n_in);
212                for (auto& v : x) v = nd(xr);
213                uint8_t* d_w = sycl::malloc_device<uint8_t>(raw.size(), q);
214                float* d_x = sycl::malloc_device<float>(x.size(), q);
215                const size_t qb = K::native_q8_1_bytes(n_in, nc);
216                void* d_q = sycl::malloc_device(qb, q);
217                float* d_y = sycl::malloc_device<float>((size_t) nc * n_out, q);
218                q.memcpy(d_w, raw.data(), raw.size()).wait();
219                q.memcpy(d_x, x.data(), x.size() * 4).wait();
220                std::vector<float> nanv((size_t) nc * n_out, NAN);
221                q.memcpy(d_y, nanv.data(), nanv.size() * 4).wait();
222                ++t.cases;
223                char tag[160];
224                std::snprintf(tag, sizeof tag, "%s mmvq n_in=%d n_out=%d ncols=%d", ty.name, n_in, n_out, nc);
225                try {
226                    K::native_quantize_q8_1(d_x, d_q, n_in, nc, S());
227                    K::native_mmvq(ty.id, d_w, d_q, d_y, n_in, n_out, nc, S());
228                    q.wait();
229                } catch (const std::exception& e) {
230                    fail(t, std::string(tag) + ": exception " + e.what());
231                    sycl::free(d_w, q); sycl::free(d_x, q); sycl::free(d_q, q); sycl::free(d_y, q);
232                    continue;
233                }
234                std::vector<uint8_t> qh(qb);
235                std::vector<float> y((size_t) nc * n_out);
236                q.memcpy(qh.data(), d_q, qb).wait();
237                q.memcpy(y.data(), d_y, y.size() * 4).wait();
238                // the activations as the kernel got them: block = half d, half s, int8 qs[32]
239                std::vector<float> xh((size_t) nc * n_in);
240                for (int c = 0; c < nc; ++c)
241                    for (int b = 0; b < n_in / 32; ++b) {
242                        const uint8_t* p = &qh[((size_t) c * (n_in / 32) + b) * 36];
243                        uint16_t hd; std::memcpy(&hd, p, 2);
244                        const float d = strata::fp16_to_fp32(hd);
245                        for (int j = 0; j < 32; ++j) xh[(size_t) c * n_in + b * 32 + j] = d * (float) (int8_t) p[4 + j];
246                    }
247                size_t bad = 0, nonf = 0;
248                double worst = 0;
249                for (int c = 0; c < nc; ++c)
250                    for (int r = 0; r < n_out; ++r) {
251                        const float v = y[(size_t) c * n_out + r];
252                        if (!std::isfinite(v)) { ++nonf; continue; }
253                        double s = 0, sa = 0;
254                        for (int i = 0; i < n_in; ++i) { const double tt = (double) wf[(size_t) r * n_in + i] * xh[(size_t) c * n_in + i]; s += tt; sa += std::fabs(tt); }
255                        const double e = std::fabs((double) v - s) / (sa + 1e-30);
256                        worst = std::max(worst, e);
257                        if (e > 5e-3) ++bad;   // (Q4_0 / Q5_0 take the offset term from the Q8_1 block's sum of the ORIGINAL activations, not from the int8 values: 1e-3 of the sum of |terms| is that, not a bug)
258                    }
259                if (bad || nonf) {
260                    char b[300];
261                    std::snprintf(b, sizeof b, "%s: %zu beyond 5e-3 (worst %.2e), %zu non-finite", tag, bad, worst, nonf);
262                    fail(t, b);
263                }
264                sycl::free(d_w, q); sycl::free(d_x, q); sycl::free(d_q, q); sycl::free(d_y, q);
265            }
266        }
267    }
268}
269
270}  // namespace
271
272int main(int argc, char** argv) {
273    bool quick = false;
274    std::string only;
275    for (int i = 1; i < argc; ++i) {
276        if (!std::strcmp(argv[i], "--quick")) quick = true;
277        else if (!std::strcmp(argv[i], "--type") && i + 1 < argc) only = argv[++i];
278    }
279    std::printf("DEVICE %s\n", Q().get_device().get_info<sycl::info::device::name>().c_str());
280    for (const Ty& ty : kTys) {
281        if (!only.empty() && only != ty.name) continue;
282        run_dequant(ty, quick);
283        run_mmvq(ty, quick);
284    }
285    for (const auto& kv : g_res)
286        std::printf("RESULT %-28s cases=%d fail=%d %s\n%s", kv.first.c_str(), kv.second.cases, kv.second.fail, kv.second.fail ? "FAIL" : "ok",
287                    kv.second.first.empty() ? "" : ("  first: " + kv.second.first + "\n").c_str());
288    std::printf("SUMMARY fails=%d\n", g_fails);
289    return g_fails ? 1 : 0;
290}