okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
38.9 KiB717 linesraw
1// src/kernels/elementwise_parity.cpp - P2.S5's test for the layer glue.
2//
3// The ops are small; the CONVENTIONS in them are not, and each one is a place where a plausible reading
4// gives a plausible number:
5//
6//   1. `softplus` HAS A LARGE-x BRANCH.  `log1p(exp(x))` overflows f32 at x > 88 and loses relative precision
7//      well before that; `ggml_compute_softplus_f32` returns `x` above 20.  A rival without the branch is
8//      asserted observable, because a gate that saturates to +inf makes `exp(gate)` inf and the whole
9//      recurrence NaN - which reads as a state bug and not as a missing branch.
10//   2. `ssm_a` IS NEGATIVE.  `gate = softplus(...) * ssm_a`, so `exp(gate) < 1` and the state DECAYS.  A
11//      fixture with a positive `ssm_a` would still produce finite output and the recurrence would blow up
12//      instead of decaying, so the sign is checked as a property and not assumed.
13//   3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does.  f32 `expf` differs in the
14//      last bits, and the test measures that rather than asserting it away.
15#define DPCT_PROFILING_ENABLED
16#include <sycl/sycl.hpp>
17#include <dpct/dpct.hpp>
18#include "strata/kernels/dequant_bf16.hpp"
19#include "strata/kernels/elementwise.hpp"
20#include "strata/kernels/f16_bits.hpp"
21
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <random>
27#include <string>
28#include <vector>
29
30namespace {
31
32void check(dpct::err0 e, const char *what) {
33}
34
35double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
36    double d = 0, m = 0;
37    for (size_t i = 0; i < a.size(); ++i) {
38        d += std::fabs((double) a[i] - (double) b[i]);
39        m += std::fabs((double) a[i]);
40    }
41    return d / (m > 1e-30 ? m : 1e-30);
42}
43
44}  // namespace
45
46int main(int argc, char** argv) {
47    bool selftest = false;
48    for (int i = 1; i < argc; ++i) {
49        if (std::string(argv[i]) == "--selftest") selftest = true;
50        else { std::fprintf(stderr, "usage: elementwise_parity [--selftest]\n"); return 2; }
51    }
52    int bad = 0;
53    const int64_t H_V = 48;
54
55    // ---- 1. gdn_gate, with the reference's own softplus
56    {
57        const int n = (int) H_V;
58        std::mt19937 rng(11);
59        std::normal_distribution<float> g(0.0f, 1.0f);
60        std::vector<float> alpha(n), dt(n), a(n), want(n);
61        for (int i = 0; i < n; ++i) {
62            // A MIXTURE THAT ACTUALLY CROSSES THE BRANCH.  The first version drew alpha from a normal with
63            // sigma 3, so the largest value was about 9 and `softplus` never took its `x > 20` path - the
64            // "branch is observable" check then reported **0.00% apart, 0 non-finite**, which is the fixture
65            // saying it cannot see the thing it was written to see.  Every third head is now large.
66            const bool large = (i % 3) == 0;
67            // Up to ~120, so the fixture spans WELL PAST f32's `exp` overflow at 88.  A fixture that stopped
68            // at 88 would show the branch as unobservable and would be right: `log1pf(expf(x))` equals `x` to
69            // f32 precision for the whole range 20..88, so ggml's threshold of 20 is CONSERVATIVE and the
70            // behaviour only actually changes where `expf` overflows.
71            alpha[i] = large ? (22.0f + 6.0f * (float) (i % 17)) : g(rng) * 3.0f;
72            dt[i] = g(rng) * 0.5f;
73            // NEGATIVE, as the artifact's `ssm_a = -exp(A_log)` is.  Checked below as a property.
74            a[i] = -(std::fabs(g(rng)) + 0.1f);
75            const double x = (double) alpha[i] + (double) dt[i];
76            const double sp = x > 20.0 ? x : std::log1p(std::exp(x));
77            want[(size_t) i] = (float) (sp * (double) a[i]);
78        }
79        // the fixture must EXERCISE the branch, or check 1 below measures nothing
80        {
81            int over = 0, past_overflow = 0;
82            for (int i = 0; i < n; ++i) {
83                const float x = alpha[(size_t) i] + dt[(size_t) i];
84                if (x > 20.0f) ++over;
85                if (x > 88.0f) ++past_overflow;
86            }
87            std::printf("  %-44s %s (%d above 20, %d above 88)\n", "the fixture crosses the branch",
88                        over ? "yes" : "*** NO ***", over, past_overflow);
89            if (!over) ++bad;
90        }
91        // the sign property, asserted rather than assumed
92        int positive = 0;
93        for (int i = 0; i < n; ++i) if (a[(size_t) i] >= 0.0f) ++positive;
94        std::printf("  %-44s %s (%d of %d non-negative)\n", "the fixture's ssm_a is negative",
95                    positive ? "*** NO ***" : "yes", positive, n);
96        if (positive) ++bad;
97
98        float *d_a = nullptr, *d_dt = nullptr, *d_sa = nullptr, *d_g = nullptr;
99        check(DPCT_CHECK_ERROR(d_a = (float *)sycl::malloc_device(
100                                   n * 4, dpct::get_in_order_queue())),
101              "a");
102        check(DPCT_CHECK_ERROR(d_dt = (float *)sycl::malloc_device(
103                                   n * 4, dpct::get_in_order_queue())),
104              "dt");
105        check(DPCT_CHECK_ERROR(d_sa = (float *)sycl::malloc_device(
106                                   n * 4, dpct::get_in_order_queue())),
107              "sa");
108        check(DPCT_CHECK_ERROR(d_g = (float *)sycl::malloc_device(
109                                   n * 4, dpct::get_in_order_queue())),
110              "g");
111        /*
112        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
113        assuming in the original code the source host memory is pageable memory.
114        If the memory is not pageable, call wait() on event return by memcpy API
115        to ensure synchronization behavior.
116        */
117        check(DPCT_CHECK_ERROR(
118                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_a, alpha.data(), n * 4).wait()),
119              "ca");
120        /*
121        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
122        assuming in the original code the source host memory is pageable memory.
123        If the memory is not pageable, call wait() on event return by memcpy API
124        to ensure synchronization behavior.
125        */
126        check(DPCT_CHECK_ERROR(
127                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_dt, dt.data(), n * 4).wait()),
128              "cd");
129        /*
130        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
131        assuming in the original code the source host memory is pageable memory.
132        If the memory is not pageable, call wait() on event return by memcpy API
133        to ensure synchronization behavior.
134        */
135        check(DPCT_CHECK_ERROR(
136                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_sa, a.data(), n * 4).wait()),
137              "cs");
138        strata::kernels::gdn_gate(d_a, d_dt, d_sa, d_g, 1, H_V, nullptr);
139        std::vector<float> got((size_t) n);
140        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
141                                   .memcpy(got.data(), d_g, n * 4)
142                                   .wait()),
143              "cg");
144
145        const double rel = rel_l1(want, got);
146        std::printf("  %-44s rel %.3e\n", "gdn_gate vs the reference", rel);
147        // double softplus and double multiply on both sides, then one cast
148        if (!(rel <= 1e-6)) { std::printf("    *** over 1e-6 ***\n"); ++bad; }
149
150        // TRAP: no large-x branch.  `log1p(exp(x))` in f32, with no `x > 20` path.
151        //
152        // AND THE MEASUREMENT SAYS WHERE THE BRANCH ACTUALLY MATTERS.  The first version of this fixture
153        // spanned 20..88 and reported **0 heads differ**: `log1pf(expf(x))` agrees with `x` to f32 precision
154        // over that whole range, so ggml's threshold of 20 is CONSERVATIVE - the branch changes the answer only
155        // where `expf` OVERFLOWS, at about 88.  The check reports the smallest x at which the two readings
156        // part company, so the number is in the output rather than in this comment.
157        {
158            int wrong = 0, differing = 0;
159            float first_differ = -1.0f;
160            std::vector<float> rival((size_t) n);
161            for (int i = 0; i < n; ++i) {
162                const float x = alpha[(size_t) i] + dt[(size_t) i];
163                const float sp = std::log1p(std::exp(x));       // no branch, f32
164                rival[(size_t) i] = sp * a[(size_t) i];
165                if (!std::isfinite(sp)) ++wrong;
166                const float branched = x > 20.0f ? x : std::log1pf(std::exp(x));
167                if (sp != branched) {
168                    ++differing;
169                    if (first_differ < 0.0f || x < first_differ) first_differ = x;
170                }
171            }
172            const double r = rel_l1(want, rival);
173            const bool visible = r > 0.05 || wrong > 0;
174            std::printf("  %-44s %s (%.2f%% apart, %d non-finite, %d heads differ, first at x = %.1f)\n",
175                        "the softplus large-x branch is observable", visible ? "yes" : "*** NO ***",
176                        r * 100, wrong, differing, (double) first_differ);
177            if (!visible) ++bad;
178        }
179        // PROPERTY: exp(gate) < 1 for every element, which is what makes the state decay
180        {
181            int over = 0;
182            for (float v : got) if (!(std::exp(v) < 1.0f)) ++over;
183            std::printf("  %-44s %s (%d of %d not < 1)\n", "exp(gate) < 1 for every head",
184                        over ? "*** NO ***" : "yes", over, n);
185            if (over) ++bad;
186        }
187        sycl::free(d_a, dpct::get_in_order_queue());
188            sycl::free(d_dt, dpct::get_in_order_queue());
189            sycl::free(d_sa, dpct::get_in_order_queue());
190            sycl::free(d_g, dpct::get_in_order_queue());
191    }
192
193    // ---- 2. silu, in double then cast
194    {
195        const int n = 4096;
196        std::mt19937 rng(22);
197        std::normal_distribution<float> g(0.0f, 3.0f);
198        std::vector<float> x((size_t) n), want((size_t) n);
199        for (int i = 0; i < n; ++i) {
200            x[(size_t) i] = g(rng);
201            const double v = (double) x[(size_t) i];
202            want[(size_t) i] = (float) (v / (1.0 + std::exp(-v)));
203        }
204        float* d_x = nullptr;
205        check(DPCT_CHECK_ERROR(d_x = (float *)sycl::malloc_device(
206                                   n * 4, dpct::get_in_order_queue())),
207              "sx");
208        /*
209        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
210        assuming in the original code the source host memory is pageable memory.
211        If the memory is not pageable, call wait() on event return by memcpy API
212        to ensure synchronization behavior.
213        */
214        check(DPCT_CHECK_ERROR(
215                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(), n * 4).wait()),
216              "csx");
217        strata::kernels::silu_inplace(d_x, n, nullptr);
218        std::vector<float> got((size_t) n);
219        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
220                                   .memcpy(got.data(), d_x, n * 4)
221                                   .wait()),
222              "csg");
223        const double rel = rel_l1(want, got);
224        std::printf("\n  %-44s rel %.3e\n", "silu (double) vs the reference", rel);
225        if (!(rel <= 1e-7)) { std::printf("    *** over 1e-7 ***\n"); ++bad; }
226        sycl::free(d_x, dpct::get_in_order_queue());
227    }
228
229    // ---- 3. scale and the f32->f16 bridge
230    {
231        const int n = 1024;
232        std::vector<float> x((size_t) n), want((size_t) n);
233        for (int i = 0; i < n; ++i) x[(size_t) i] = (float) (i - n / 2) * 0.013f;
234        const float s = 1.0f / std::sqrt(128.0f);
235        for (int i = 0; i < n; ++i) want[(size_t) i] = x[(size_t) i] * s;
236
237        float* d_x = nullptr;
238        uint16_t* d_h = nullptr;
239        check(DPCT_CHECK_ERROR(d_x = (float *)sycl::malloc_device(
240                                   n * 4, dpct::get_in_order_queue())),
241              "ex");
242        check(DPCT_CHECK_ERROR(d_h = (uint16_t *)sycl::malloc_device(
243                                   n * 2, dpct::get_in_order_queue())),
244              "eh");
245        /*
246        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
247        assuming in the original code the source host memory is pageable memory.
248        If the memory is not pageable, call wait() on event return by memcpy API
249        to ensure synchronization behavior.
250        */
251        check(DPCT_CHECK_ERROR(
252                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(), n * 4).wait()),
253              "cex");
254        strata::kernels::scale_inplace(d_x, n, s, nullptr);
255        std::vector<float> got((size_t) n);
256        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
257                                   .memcpy(got.data(), d_x, n * 4)
258                                   .wait()),
259              "ceg");
260        int diff = 0;
261        for (int i = 0; i < n; ++i) if (got[(size_t) i] != want[(size_t) i]) ++diff;
262        std::printf("  %-44s %d of %d differ\n", "scale_inplace is exact", diff, n);
263        if (diff) ++bad;
264
265        strata::kernels::f32_to_f16_bulk(d_x, d_h, n, nullptr);
266        std::vector<uint16_t> h((size_t) n);
267        check(
268            DPCT_CHECK_ERROR(
269                (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(h.data(), d_h, n * 2).wait()),
270            "ceh");
271        int hbad = 0;
272        for (int i = 0; i < n; ++i)
273            if (h[(size_t) i] != strata::kernels::f16_from_f32(got[(size_t) i])) ++hbad;
274        std::printf("  %-44s %d of %d differ\n", "f32_to_f16_bulk uses the shared conversion", hbad, n);
275        if (hbad) ++bad;
276        sycl::free(d_x, dpct::get_in_order_queue());
277            sycl::free(d_h, dpct::get_in_order_queue());
278    }
279
280    // ---- 4. rms_norm_weighted, and the TWO RIVAL READINGS it exists to be told apart from.
281    //
282    // This kernel's whole reason for being a separate entry point from `gdn_l2_norm` is that the two differ by
283    // one `/ cols`, and that a swap produces a well-scaled, plausible tensor.  So the test computes BOTH wrong
284    // readings and requires each to differ from the right one by more than the tolerance before it judges the
285    // kernel - the same discipline the shared-expert test uses for silu-on-gate.
286    {
287        const int64_t rows = 24, cols = 256;          // the real `attn_q`-norm shape
288        const float eps = 1e-6f;
289        std::vector<float> x((size_t) (rows * cols));
290        for (size_t i = 0; i < x.size(); ++i) x[i] = (float) std::sin((double) i * 0.017) * 1.7f + 0.4f;
291        std::vector<float> w((size_t) cols);
292        for (int64_t c = 0; c < cols; ++c) w[(size_t) c] = 0.5f + 0.002f * (float) (c % 97);
293
294        // the oracle: f64, mean, times w
295        auto ref = [&](bool use_sum, bool use_w) {
296            std::vector<double> y((size_t) (rows * cols));
297            for (int64_t r = 0; r < rows; ++r) {
298                double ss = 0;
299                for (int64_t c = 0; c < cols; ++c) {
300                    const double v = x[(size_t) (r * cols + c)];
301                    ss += v * v;
302                }
303                const double den = std::sqrt((use_sum ? ss : ss / (double) cols) + (double) eps);
304                for (int64_t c = 0; c < cols; ++c) {
305                    const double v = x[(size_t) (r * cols + c)];
306                    y[(size_t) (r * cols + c)] = (v / den) * (use_w ? (double) w[(size_t) c] : 1.0);
307                }
308            }
309            std::vector<float> out((size_t) (rows * cols));
310            for (size_t i = 0; i < out.size(); ++i) out[i] = (float) y[i];
311            return out;
312        };
313        const std::vector<float> want = ref(false, true);
314        const std::vector<float> rival_sum = ref(true, false);    // what gdn_l2_norm computes
315        const std::vector<float> rival_now = ref(false, false);   // the (1+w)-vs-w / no-weight confusion
316
317        auto rel = [&](const std::vector<float>& a, const std::vector<float>& b) {
318            double d = 0, m = 0;
319            for (size_t i = 0; i < a.size(); ++i) {
320                d += std::fabs((double) a[i] - (double) b[i]);
321                m += std::fabs((double) a[i]);
322            }
323            return d / (m > 1e-30 ? m : 1e-30);
324        };
325        const double r_sum = rel(want, rival_sum), r_now = rel(want, rival_now);
326        std::printf("  %-44s %.2f%% apart\n", "sum-vs-mean is observable", r_sum * 100);
327        std::printf("  %-44s %.2f%% apart\n", "with-w-vs-without-w is observable", r_now * 100);
328        // `sqrt(cols)` = 16 for the first and the weight's own spread for the second; a fixture that cannot
329        // separate them is not testing the kernel that was written.
330        if (!(r_sum > 0.5)) { std::printf("  *** the sum reading is NOT observable ***\n"); ++bad; }
331        if (!(r_now > 0.5)) { std::printf("  *** the no-weight reading is NOT observable ***\n"); ++bad; }
332
333        float* d_x = nullptr;
334        float* d_w = nullptr;
335        check(DPCT_CHECK_ERROR(d_x = (float *)sycl::malloc_device(
336                                   x.size() * 4, dpct::get_in_order_queue())),
337              "m rmsx");
338        check(DPCT_CHECK_ERROR(d_w = (float *)sycl::malloc_device(
339                                   w.size() * 4, dpct::get_in_order_queue())),
340              "m rmsw");
341        /*
342        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
343        assuming in the original code the source host memory is pageable memory.
344        If the memory is not pageable, call wait() on event return by memcpy API
345        to ensure synchronization behavior.
346        */
347        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(),
348                                                                 x.size() * 4).wait()),
349              "c rmsx");
350        /*
351        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
352        assuming in the original code the source host memory is pageable memory.
353        If the memory is not pageable, call wait() on event return by memcpy API
354        to ensure synchronization behavior.
355        */
356        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_w, w.data(),
357                                                                 w.size() * 4).wait()),
358              "c rmsw");
359        strata::kernels::rms_norm_weighted(d_x, d_w, rows, cols, eps, nullptr);
360        std::vector<float> got((size_t) (rows * cols));
361        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
362                                   .memcpy(got.data(), d_x, got.size() * 4)
363                                   .wait()),
364              "c rmsg");
365
366        const double r_got = rel(want, got);
367        double worst = 0;
368        for (size_t i = 0; i < got.size(); ++i) {
369            const double m = std::fabs((double) want[i]);
370            const double e = std::fabs((double) got[i] - (double) want[i]) / (m > 1e-30 ? m : 1e-30);
371            if (e > worst) worst = e;
372        }
373        int nonfinite = 0;
374        for (float v : got) if (!std::isfinite(v)) ++nonfinite;
375        std::printf("  %-44s rel %.3e  worst %.3e  nonfinite %d\n", "rms_norm_weighted vs f64 oracle", r_got,
376                    worst, nonfinite);
377        if (nonfinite) ++bad;
378        // The kernel accumulates in f32 over 256 terms; 1e-6 is loose enough for that and far tighter than the
379        // 16x the rival readings are off by.
380        if (!(r_got < 1e-6)) { std::printf("  *** rms_norm_weighted is WRONG ***\n"); ++bad; }
381        // and a null `w` must be legal, because `ref/qsa.py` allows it.
382        //
383        // THE INPUT HAS TO BE RE-UPLOADED FIRST.  The kernel is IN PLACE, so `d_x` currently holds the
384        // NORMALISED tensor from the call above; running it again normalises a second time and every element
385        // differs.  That is exactly what the first version of this check reported - "6144 of 6144 differ" -
386        // and it is a fixture bug rather than a kernel bug: the oracle reads the ORIGINAL `x`, so the two
387        // sides were never looking at the same input.
388        const std::vector<float> want_null = ref(false, false);
389        /*
390        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
391        assuming in the original code the source host memory is pageable memory.
392        If the memory is not pageable, call wait() on event return by memcpy API
393        to ensure synchronization behavior.
394        */
395        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(),
396                                                                 x.size() * 4).wait()),
397              "c rmsx2");
398        strata::kernels::rms_norm_weighted(d_x, nullptr, rows, cols, eps, nullptr);
399        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
400                                   .memcpy(got.data(), d_x, got.size() * 4)
401                                   .wait()),
402              "c rmsn");
403        int null_bad = 0;
404        for (size_t i = 0; i < got.size(); ++i)
405            if (std::fabs((double) got[i] - (double) want_null[i]) > 1e-6) ++null_bad;
406        std::printf("  %-44s %d of %zu differ\n", "a null weight is legal", null_bad, got.size());
407        if (null_bad) ++bad;
408        sycl::free(d_x, dpct::get_in_order_queue());
409        sycl::free(d_w, dpct::get_in_order_queue());
410    }
411
412    // Packed embedding rows: every code width, scale-group size, optional offset,
413    // row boundary and partial CUDA block. Compare bits with a scalar CPU decoder.
414    // Volatile materializes the multiply so this oracle cannot silently use FMA.
415    {
416        dpct::queue_ptr stream;
417        /*
418        DPCT1025: The SYCL queue is created ignoring the flag and priority
419        options.
420        */
421        check(DPCT_CHECK_ERROR(
422                  stream = dpct::get_current_device().create_queue(true)),
423              "embedding stream");
424        std::mt19937 rng(77);
425        std::uniform_real_distribution<float> values(-2.0f, 2.0f);
426        int mismatches = 0, guards = 0, fma_diff = 0, cases = 0;
427        for (const int bits : {2, 4, 8}) {
428            const int bias = bits == 2 ? -1 : bits == 4 ? -7 : -16;
429            const int per_byte = 8 / bits;
430            const unsigned mask = (1u << bits) - 1u;
431            for (const int group : {16, 32, 64}) {
432                for (const int n : {320, 2560}) {
433                    const int row_bytes = n / per_byte, row_groups = n / group;
434                    std::vector<uint8_t> codes((size_t) 3 * row_bytes, 0);
435                    std::vector<float> scales((size_t) 3 * row_groups), offsets(scales.size());
436                    std::vector<int> unpacked((size_t) 3 * n);
437                    for (size_t i = 0; i < unpacked.size(); ++i) {
438                        const unsigned code = (unsigned) (i * 13 + i / n * 7) & mask;
439                        unpacked[i] = (int) code;
440                        codes[i / per_byte] |= (uint8_t) (code << ((i % per_byte) * bits));
441                    }
442                    for (size_t i = 0; i < scales.size(); ++i) {
443                        scales[i] = values(rng);
444                        offsets[i] = values(rng);
445                    }
446                    scales[0] = -0.0f;
447                    offsets[0] = 0.0f;
448                    uint8_t* dc = nullptr;
449                    float *ds = nullptr, *dof = nullptr, *out = nullptr;
450                    check(DPCT_CHECK_ERROR(
451                              dc = (uint8_t *)sycl::malloc_device(
452                                  codes.size(), dpct::get_in_order_queue())),
453                          "embedding codes");
454                    check(DPCT_CHECK_ERROR(
455                              ds = sycl::malloc_device<float>(
456                                  scales.size(), dpct::get_in_order_queue())),
457                          "embedding scales");
458                    check(DPCT_CHECK_ERROR(
459                              dof = sycl::malloc_device<float>(
460                                  offsets.size(), dpct::get_in_order_queue())),
461                          "embedding offsets");
462                    check(DPCT_CHECK_ERROR(
463                              out = sycl::malloc_device<float>(
464                                  ((size_t)n + 2), dpct::get_in_order_queue())),
465                          "embedding output");
466                    /*
467                    DPCT1124: cudaMemcpyAsync is migrated to asynchronous
468                    memcpy API. While the origin API might be synchronous, it
469                    depends on the type of operand memory, so you may need to
470                    call wait() on event return by memcpy API to ensure
471                    synchronization behavior.
472                    */
473                    check(DPCT_CHECK_ERROR(
474                              stream->memcpy(dc, codes.data(), codes.size())),
475                          "embedding codes upload");
476                    /*
477                    DPCT1124: cudaMemcpyAsync is migrated to asynchronous
478                    memcpy API. While the origin API might be synchronous, it
479                    depends on the type of operand memory, so you may need to
480                    call wait() on event return by memcpy API to ensure
481                    synchronization behavior.
482                    */
483                    check(
484                        DPCT_CHECK_ERROR(stream->memcpy(
485                            ds, scales.data(), scales.size() * sizeof(float))),
486                        "embedding scales upload");
487                    /*
488                    DPCT1124: cudaMemcpyAsync is migrated to asynchronous
489                    memcpy API. While the origin API might be synchronous, it
490                    depends on the type of operand memory, so you may need to
491                    call wait() on event return by memcpy API to ensure
492                    synchronization behavior.
493                    */
494                    check(DPCT_CHECK_ERROR(
495                              stream->memcpy(dof, offsets.data(),
496                                             offsets.size() * sizeof(float))),
497                          "embedding offsets upload");
498                    check(DPCT_CHECK_ERROR(stream->wait()),
499                          "embedding upload sync");
500
501                    for (const bool with_offset : {false, true}) {
502                        for (int row = 0; row < 3; ++row) {
503                            std::vector<float> want((size_t) n), got((size_t) n + 2, -12345.0f);
504                            for (int i = 0; i < n; ++i) {
505                                const size_t gi = (size_t) row * row_groups + i / group;
506                                const float code = (float) (unpacked[(size_t) row * n + i] + bias);
507                                volatile float product = code * scales[gi];
508                                const float offset = with_offset ? offsets[gi] : 0.0f;
509                                want[(size_t) i] = product + offset;
510                                const float fused = std::fma(code, scales[gi], offset);
511                                if (std::memcmp(&fused, &want[(size_t) i], sizeof(float)) != 0) ++fma_diff;
512                            }
513                            /*
514                            DPCT1124: cudaMemcpyAsync is migrated to
515                            asynchronous memcpy API. While the origin API might
516                            be synchronous, it depends on the type of operand
517                            memory, so you may need to call wait() on event
518                            return by memcpy API to ensure synchronization
519                            behavior.
520                            */
521                            check(DPCT_CHECK_ERROR(stream->memcpy(
522                                      out, got.data(),
523                                      got.size() * sizeof(float))),
524                                  "embedding output guards");
525                            strata::kernels::embedding_gather(dc + (size_t) row * row_bytes,
526                                ds + (size_t) row * row_groups,
527                                with_offset ? dof + (size_t) row * row_groups : nullptr,
528                                n, bits, bias, group, out + 1, stream);
529                            /*
530                            DPCT1124: cudaMemcpyAsync is migrated to
531                            asynchronous memcpy API. While the origin API might
532                            be synchronous, it depends on the type of operand
533                            memory, so you may need to call wait() on event
534                            return by memcpy API to ensure synchronization
535                            behavior.
536                            */
537                            check(DPCT_CHECK_ERROR(stream->memcpy(
538                                      got.data(), out,
539                                      got.size() * sizeof(float))),
540                                  "embedding result");
541                            check(DPCT_CHECK_ERROR(stream->wait()),
542                                  "embedding sync");
543                            for (int i = 0; i < n; ++i) {
544                                if (std::memcmp(&want[(size_t) i], &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches;
545                            }
546                            if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards;
547                            ++cases;
548
549                            // Capturing the gather proves that it has no hidden synchronization.
550                            // A following scale also checks that it uses the caller's stream.
551                            if (row == 1) {
552                                dpct::experimental::command_graph_ptr graph;
553                                dpct::experimental::command_graph_exec_ptr exec;
554                                check(DPCT_CHECK_ERROR(
555                                          dpct::experimental::begin_recording(
556                                              stream)),
557                                      "embedding capture");
558                                strata::kernels::embedding_gather(dc + (size_t) row * row_bytes,
559                                    ds + (size_t) row * row_groups,
560                                    with_offset ? dof + (size_t) row * row_groups : nullptr,
561                                    n, bits, bias, group, out + 1, stream);
562                                strata::kernels::scale_inplace(out + 1, n, 2.0f, stream);
563                                check(DPCT_CHECK_ERROR(
564                                          dpct::experimental::end_recording(
565                                              stream, &graph)),
566                                      "embedding capture end");
567                                check(
568                                    DPCT_CHECK_ERROR(
569                                        exec = new sycl::ext::oneapi::
570                                            experimental::command_graph<
571                                                sycl::ext::oneapi::
572                                                    experimental::graph_state::
573                                                        executable>(
574                                                graph->finalize())),
575                                    "embedding instantiate");
576                                check(DPCT_CHECK_ERROR(
577                                          stream->ext_oneapi_graph(*exec)),
578                                      "embedding replay");
579                                /*
580                                DPCT1124: cudaMemcpyAsync is migrated to
581                                asynchronous memcpy API. While the origin API
582                                might be synchronous, it depends on the type of
583                                operand memory, so you may need to call wait()
584                                on event return by memcpy API to ensure
585                                synchronization behavior.
586                                */
587                                check(DPCT_CHECK_ERROR(stream->memcpy(
588                                          got.data(), out,
589                                          got.size() * sizeof(float))),
590                                      "embedding graph result");
591                                check(DPCT_CHECK_ERROR(stream->wait()),
592                                      "embedding graph sync");
593                                for (int i = 0; i < n; ++i) {
594                                    const float expected = want[(size_t) i] * 2.0f;
595                                    if (std::memcmp(&expected, &got[(size_t) i + 1], sizeof(float)) != 0) ++mismatches;
596                                }
597                                if (got.front() != -12345.0f || got.back() != -12345.0f) ++guards;
598                                check(DPCT_CHECK_ERROR(delete (exec)),
599                                      "embedding exec destroy");
600                                check(DPCT_CHECK_ERROR(delete (graph)),
601                                      "embedding graph destroy");
602                            }
603                        }
604                    }
605                    sycl::free(dc, dpct::get_in_order_queue());
606                        sycl::free(ds, dpct::get_in_order_queue());
607                        sycl::free(dof, dpct::get_in_order_queue());
608                        sycl::free(out, dpct::get_in_order_queue());
609                }
610            }
611        }
612        check(
613            DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(stream)),
614            "embedding stream destroy");
615        std::printf("  embedding gather: %d row cases, %d bit mismatches, %d guard failures, %d FMA differences\n",
616                    cases, mismatches, guards, fma_diff);
617        if (mismatches || guards || fma_diff == 0) ++bad;
618    }
619
620    // ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN.  `f32_to_bf16_bulk` (the header's `bf16_from_f32`
621    // on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule;
622    // before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf.  `bf16_bits_test` covers every f32 on
623    // the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu.
624    {
625        auto ggml_bf16 = [](uint32_t u) -> uint16_t {
626            if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
627            return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
628        };
629        std::vector<uint32_t> bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu,
630                                      0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u,
631                                      0x3F818000u, 0x00008000u, 0x7F7F8000u};
632        std::mt19937 rng(13);
633        while (bits.size() < 4096) bits.push_back((uint32_t) rng());
634        const size_t n = bits.size();
635        float* dx = nullptr;
636        uint16_t* dy = nullptr;
637        check(DPCT_CHECK_ERROR(dx = (float *)sycl::malloc_device(
638                                   n * 4, dpct::get_in_order_queue())),
639              "bf16 x");
640        check(DPCT_CHECK_ERROR(dy = (uint16_t *)sycl::malloc_device(
641                                   n * 2, dpct::get_in_order_queue())),
642              "bf16 y");
643        /*
644        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
645        assuming in the original code the source host memory is pageable memory.
646        If the memory is not pageable, call wait() on event return by memcpy API
647        to ensure synchronization behavior.
648        */
649        check(DPCT_CHECK_ERROR(
650                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dx, bits.data(), n * 4).wait()),
651              "bf16 cx");
652        strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr);
653        std::vector<uint16_t> got(n);
654        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
655                                   .memcpy(got.data(), dy, n * 2)
656                                   .wait()),
657              "bf16 cy");
658        int wrong = 0;
659        for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]);
660
661        // A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must
662        // still be one in BF16.  A second block with an ordinary scale checks the finite path did not move.
663        std::vector<uint8_t> blk(2 * 34, 0);
664        blk[0] = 0x00; blk[1] = 0x7E;                        // fp16 quiet NaN
665        blk[34] = 0x00; blk[35] = 0x3C;                      // fp16 1.0
666        for (int j = 0; j < 32; ++j) {
667            blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16);
668            blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50);
669        }
670        uint8_t* db = nullptr;
671        uint16_t* dq = nullptr;
672        check(DPCT_CHECK_ERROR(db = (uint8_t *)sycl::malloc_device(
673                                   blk.size(), dpct::get_in_order_queue())),
674              "q8 blk");
675        check(DPCT_CHECK_ERROR(dq = (uint16_t *)sycl::malloc_device(
676                                   64 * 2, dpct::get_in_order_queue())),
677              "q8 out");
678        /*
679        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
680        assuming in the original code the source host memory is pageable memory.
681        If the memory is not pageable, call wait() on event return by memcpy API
682        to ensure synchronization behavior.
683        */
684        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(db, blk.data(),
685                                                                 blk.size()).wait()),
686              "q8 cblk");
687        strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr);
688        check(DPCT_CHECK_ERROR(
689                  dpct::get_current_device().queues_wait_and_throw()),
690              "dequant_bf16");
691        std::vector<uint16_t> q(64);
692        check(
693            DPCT_CHECK_ERROR(
694                (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(q.data(), dq, 64 * 2).wait()),
695            "q8 cout");
696        int dq_wrong = 0;
697        for (int j = 0; j < 32; ++j) {
698            if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong;           // row 0: NaN scale -> NaN
699            const float v = (float) (3 * j - 50);                                // row 1: d = 1.0 -> the integer
700            uint32_t vb;
701            std::memcpy(&vb, &v, 4);
702            if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;
703        }
704        std::printf("  f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n",
705                    wrong, n, dq_wrong);
706        if (wrong || dq_wrong) ++bad;
707        sycl::free(dx, dpct::get_in_order_queue());
708            sycl::free(dy, dpct::get_in_order_queue());
709            sycl::free(db, dpct::get_in_order_queue());
710            sycl::free(dq, dpct::get_in_order_queue());
711    }
712
713    std::printf("\nelementwise: %d failures\n", bad);
714    if (bad) return 1;
715    if (selftest) std::printf("elementwise_parity OK\n");
716    return 0;
717}