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
68.5 KiB1290 linesraw
1// src/kernels/gr_parity.cpp - P2.S2's test for the gated residual / hyper-connection.
2//
3// `ref/gr.py` opens by listing the details "a prose reading gets wrong", and every one of them is a reading
4// that has the RIGHT SHAPES and produces a PLAUSIBLE number.  So each is computed here the wrong way round and
5// required to differ materially BEFORE the kernel is judged against the right one.  A test that only does the
6// second half passes against either reading:
7//
8//   1. PER-STREAM RMSNorm.  The source comment reads ambiguously; the code reduces over ne[0] = n_embd, i.e.
9//      one RMS per stream.  The rival reading is one RMS over the whole hc*n_embd stack.
10//   2. `/ hc` INSIDE the silu: `lo = silu(proj / hc)`.  Moving it outside is a one-line change that keeps
11//      every shape.
12//   3. SiLU on `lo` and SIGMOID on the gate, a few lines apart in the same function.  Swapping them is the
13//      obvious slip, and both are monotone saturating functions so the magnitudes stay comparable.
14//   4. `mean` over the stream axis, not `sum`.  A factor of hc = 4, which is exactly the kind of error that
15//      looks like a scale problem rather than a structural one.
16//   5. ACTIVATION PRECISION. The historical BF16-rounded CPU contract and the pinned CUDA single-token
17//      FP32-activation contract must be distinguishable. Both are tested against explicit references;
18//      neither is selected merely because the weight is BF16. The scalar fixture isolates xn and lo
19//      rounding from reduction order, and graph replay must preserve the precision chosen at capture.
20//   6. `gr_write`'s `2*sigmoid`, which centres the gate on 1 so a ZERO injection is a plain residual add.
21//      Asserted as a property, not as a value, because that is what the source comment claims.
22#define DPCT_PROFILING_ENABLED
23#include <sycl/sycl.hpp>
24#include <dpct/dpct.hpp>
25#include "strata/kernels/gr.hpp"
26#include "strata/kernels/fused_gr.hpp"
27#include "strata/kernels/native_mmvq.hpp"
28#include "strata/core/geometry.hpp"
29
30#include <cmath>
31#include <cstdio>
32#include <algorithm>
33#include <cstdlib>
34#include <cstring>
35#include <random>
36#include <string>
37#include <vector>
38
39namespace {
40
41void check(dpct::err0 e, const char *what) {
42}
43
44/// The same rule the kernel uses, on the host - `ref/quant.py::bf16`.
45float to_bf16(float f) {
46    uint32_t i;
47    std::memcpy(&i, &f, 4);
48    i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
49    float o;
50    std::memcpy(&o, &i, 4);
51    return o;
52}
53
54uint16_t bf16_bits(float f) {
55    uint32_t i;
56    std::memcpy(&i, &f, 4);
57    return (uint16_t) (i >> 16);
58}
59
60struct Opts {
61    bool per_stream_norm = true;   ///< false: one RMS over the whole stack (WRONG)
62    bool scale_inside_silu = true; ///< false: silu(proj)/hc instead of silu(proj/hc) (WRONG)
63    bool sigmoid_on_gate = true;   ///< false: silu on the gate and sigmoid on lo (WRONG)
64    bool mean_over_streams = true; ///< false: sum over streams instead of mean (WRONG)
65    bool round_activation = true;  ///< false: pinned CUDA single-token BF16 MMVF contract
66};
67
68/// `ref/gr.py::gr_read`, transcribed with switches for the rival readings.
69void reference(const std::vector<float>& R, const std::vector<float>& w_norm,
70               const std::vector<float>& w_down, const std::vector<float>& w_up,
71               const std::vector<float>& w_inject, float eps, long long n_embd, long long hc, long long hc_lr,
72               const Opts& o, std::vector<float>& mixed, std::vector<float>& inject) {
73    const long long hc_dim = hc * n_embd;
74    std::vector<float> xn((size_t) hc_dim);
75    if (o.per_stream_norm) {
76        for (long long c = 0; c < hc; ++c) {
77            double ms = 0;
78            for (long long d = 0; d < n_embd; ++d) ms += (double) R[(size_t) (c * n_embd + d)] * R[(size_t) (c * n_embd + d)];
79            ms /= (double) n_embd;
80            const float rs = (float) (1.0 / std::sqrt(ms + (double) eps));
81            for (long long d = 0; d < n_embd; ++d) {
82                const size_t i = (size_t) (c * n_embd + d);
83                xn[i] = R[i] * rs * w_norm[i];
84            }
85        }
86    } else {
87        double ms = 0;
88        for (long long i = 0; i < hc_dim; ++i) ms += (double) R[(size_t) i] * R[(size_t) i];
89        ms /= (double) hc_dim;
90        const float rs = (float) (1.0 / std::sqrt(ms + (double) eps));
91        for (long long i = 0; i < hc_dim; ++i) xn[(size_t) i] = R[(size_t) i] * rs * w_norm[(size_t) i];
92    }
93
94    std::vector<float> act((size_t) hc_dim);
95    for (long long i = 0; i < hc_dim; ++i) act[(size_t) i] = o.round_activation ? to_bf16(xn[(size_t) i]) : xn[(size_t) i];
96
97    // lo
98    std::vector<float> lo((size_t) hc_lr);
99    for (long long k = 0; k < hc_lr; ++k) {
100        double a = 0;
101        for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_down[(size_t) (k * hc_dim + i)];
102        const float p = (float) a;
103        if (o.sigmoid_on_gate) lo[(size_t) k] = o.scale_inside_silu ? (p / (float) hc) / (1.0f + std::exp(-(p / (float) hc)))
104                                                                  : (p / (1.0f + std::exp(-p))) / (float) hc;
105        else                   lo[(size_t) k] = o.scale_inside_silu ? 1.0f / (1.0f + std::exp(-(p / (float) hc)))
106                                                                    : (1.0f / (1.0f + std::exp(-p))) / (float) hc;
107    }
108    std::vector<float> lq((size_t) hc_lr);
109    for (long long k = 0; k < hc_lr; ++k)
110        lq[(size_t) k] = o.round_activation ? to_bf16(lo[(size_t) k]) : lo[(size_t) k];
111
112    // gate and the gated mean
113    mixed.assign((size_t) n_embd, 0.0f);
114    for (long long d = 0; d < n_embd; ++d) {
115        float m = 0.0f;
116        for (long long c = 0; c < hc; ++c) {
117            const long long i = c * n_embd + d;
118            double a = 0;
119            for (long long k = 0; k < hc_lr; ++k) a += (double) lq[(size_t) k] * (double) w_up[(size_t) (i * hc_lr + k)];
120            const float g = (float) a;
121            const float s = o.sigmoid_on_gate ? 1.0f / (1.0f + std::exp(-g)) : g / (1.0f + std::exp(-g));
122            m += xn[(size_t) i] * s;
123        }
124        mixed[(size_t) d] = o.mean_over_streams ? m / (float) hc : m;
125    }
126
127    inject.assign((size_t) hc, 0.0f);
128    for (long long c = 0; c < hc; ++c) {
129        double a = 0;
130        for (long long i = 0; i < hc_dim; ++i) a += (double) act[(size_t) i] * (double) w_inject[(size_t) (c * hc_dim + i)];
131        inject[(size_t) c] = (float) a;
132    }
133}
134
135/// Normalised L1 difference.  `mag_out` returns the mean |a|, for reporting.
136double rel_diff(const std::vector<float>& a, const std::vector<float>& b, double* mag_out = nullptr) {
137    double d = 0, mag = 0;
138    for (size_t i = 0; i < a.size(); ++i) {
139        d += std::fabs((double) a[i] - (double) b[i]);
140        mag += std::fabs((double) a[i]);
141    }
142    if (mag_out) *mag_out = mag / (double) (a.empty() ? 1 : a.size());
143    return d / (mag > 1e-30 ? mag : 1e-30);
144}
145
146/// Relative error against the magnitude of the TERMS, not of the result.
147///
148/// `R + block_out * w` cancels wherever block_out*w is close to -R, and a plain |want-got|/|want| then
149/// reports the CONDITION NUMBER instead of the arithmetic.  This is the same metric mistake the project has
150/// now made four times: rounds 169 (Q4_K), 189 (RoPE), 194 (shared_expert) and this one.  For a sum, the
151/// denominator is the sum of the term magnitudes.
152double rel_terms(double want, double got, double term_a, double term_b) {
153    const double den = std::fabs(term_a) + std::fabs(term_b);
154    return std::fabs(want - got) / (den > 1e-30 ? den : 1e-30);
155}
156
157const char* activation_mode_name(int mode) {
158    return mode == 2 ? "native pinned GR" : (mode == 1 ? "FP32" : "BF16");
159}
160void select_activation_mode(int mode) {
161    strata::kernels::gr_set_native_mmvf(mode == 2);
162    // In mode 2 the precision-only switch is deliberately false: native MMVF must imply FP32 by itself.
163    strata::kernels::gr_set_fp32_activations(mode == 1);
164}
165
166// A diagonal GR fixture makes activation precision observable without summation-order ambiguity.
167// Two-wide matrices satisfy native MMVF's pair ABI, while each nonzero dot has only one nonzero product.
168// At R=1 and eps=0, xn=gamma exactly; any rounding in xn or lo comes from the selected activation contract.
169int scalar_activation_contract() {
170    using namespace strata::kernels;
171    const GrShapes sh{2, 1, 2};
172    float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr;
173    uint16_t* d_weights = nullptr;
174    void* d_scratch = nullptr;
175    check(DPCT_CHECK_ERROR(
176              d_R = sycl::malloc_device<float>(2, dpct::get_in_order_queue())),
177          "scalar R");
178    check(DPCT_CHECK_ERROR(d_norm = sycl::malloc_device<float>(
179                               2, dpct::get_in_order_queue())),
180          "scalar norm");
181    check(DPCT_CHECK_ERROR(d_mixed = sycl::malloc_device<float>(
182                               2, dpct::get_in_order_queue())),
183          "scalar mixed");
184    check(DPCT_CHECK_ERROR(d_inject = sycl::malloc_device<float>(
185                               1, dpct::get_in_order_queue())),
186          "scalar inject");
187    check(DPCT_CHECK_ERROR(d_weights = sycl::malloc_device<uint16_t>(
188                               10, dpct::get_in_order_queue())),
189          "scalar weights");
190    check(DPCT_CHECK_ERROR(
191              d_scratch = (void *)sycl::malloc_device(
192                  gr_workspace_bytes(sh), dpct::get_in_order_queue())),
193          "scalar scratch");
194    GrWorkspace ws;
195    gr_workspace_init(sh, d_scratch, ws);
196    const float ones[] = {1.0f, 1.0f};
197    const uint16_t weights[] = {
198        bf16_bits(0.5f), 0, 0, 0,             // down: lo[0]=silu(xn[0]/2), lo[1]=0
199        bf16_bits(1.5f), 0, bf16_bits(1.5f), 0, // both gate rows consume lo[0]
200        bf16_bits(2.0f), 0                     // injection: 2*xn[0]
201    };
202    /*
203    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
204    the original code the source host memory is pageable memory. If the memory
205    is not pageable, call wait() on event return by memcpy API to ensure
206    synchronization behavior.
207    */
208    check(DPCT_CHECK_ERROR(
209              (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_R, ones, sizeof(ones)).wait()),
210          "scalar upload R");
211    /*
212    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
213    the original code the source host memory is pageable memory. If the memory
214    is not pageable, call wait() on event return by memcpy API to ensure
215    synchronization behavior.
216    */
217    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_weights, weights,
218                                                             sizeof(weights)).wait()),
219          "scalar upload weights");
220    dpct::queue_ptr stream;
221    /*
222    DPCT1025: The SYCL queue is created ignoring the flag and priority
223    options.
224    */
225    check(DPCT_CHECK_ERROR(stream =
226                               dpct::get_current_device().create_queue(true)),
227          "scalar stream");
228    int bad = 0;
229    for (float gamma : {1.0f, 1.00390625f}) {
230        const float gammas[] = {gamma, gamma};
231        /*
232        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
233        assuming in the original code the source host memory is pageable memory.
234        If the memory is not pageable, call wait() on event return by memcpy API
235        to ensure synchronization behavior.
236        */
237        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
238                  d_norm, gammas, sizeof(gammas)).wait()),
239              "scalar upload norm");
240        float mixed_by_mode[3][2] = {}, inject_by_mode[3] = {};
241        for (int mode = 0; mode < 3; ++mode) {
242            select_activation_mode(mode);
243            gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f,
244                    sh, ws, d_mixed, d_inject, stream);
245            check(DPCT_CHECK_ERROR(stream->wait()), "scalar warmup");
246            dpct::experimental::command_graph_ptr graph;
247            dpct::experimental::command_graph_exec_ptr executable;
248            check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(stream)),
249                  "scalar capture begin");
250            gr_read(d_R, d_norm, d_weights, d_weights + 4, d_weights + 8, 0.0f,
251                    sh, ws, d_mixed, d_inject, stream);
252            check(DPCT_CHECK_ERROR(
253                      dpct::experimental::end_recording(stream, &graph)),
254                  "scalar capture end");
255            check(DPCT_CHECK_ERROR(
256                      executable =
257                          new sycl::ext::oneapi::experimental::command_graph<
258                              sycl::ext::oneapi::experimental::graph_state::
259                                  executable>(graph->finalize())),
260                  "scalar instantiate");
261            // Changing both host options after capture cannot change the graph's selected kernels.
262            select_activation_mode((mode + 1) % 3);
263            // Warmup results must not make a missing/no-op captured launch pass.
264            // Poison the outputs and intermediate workspace before replay.
265            check(DPCT_CHECK_ERROR(
266                      stream->memset(d_mixed, 0xa5, 2 * sizeof(float))),
267                  "scalar poison mixed");
268            check(
269                DPCT_CHECK_ERROR(stream->memset(d_inject, 0xa5, sizeof(float))),
270                "scalar poison inject");
271            check(DPCT_CHECK_ERROR(stream->memset(d_scratch, 0xa5, ws.bytes)),
272                  "scalar poison workspace");
273            check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*executable)),
274                  "scalar replay");
275            check(DPCT_CHECK_ERROR(stream->wait()), "scalar replay sync");
276            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
277                                       .memcpy(mixed_by_mode[mode], d_mixed,
278                                               2 * sizeof(float))
279                                       .wait()),
280                  "scalar mixed copy");
281            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
282                                       .memcpy(&inject_by_mode[mode], d_inject,
283                                               sizeof(float))
284                                       .wait()),
285                  "scalar inject copy");
286            const float activation = mode ? gamma : to_bf16(gamma);
287            const float projection = activation * 0.5f;
288            const float lo = projection / (1.0f + std::exp(-projection));
289            const float gate = (mode ? lo : to_bf16(lo)) * 1.5f;
290            const float expected_mixed = gamma / (1.0f + std::exp(-gate));
291            const float expected_inject = activation * 2.0f;
292            // Each mode has its own activation contract and bounded scalar-formula
293            // check. Native fast exp/div need not match ordinary FP32 postops bit
294            // for bit: native_gr_postops_parity establishes that arithmetic with
295            // actual pinned CUDA graphs. The nonzero projection/injection here
296            // has only one exactly representable product and remains exact.
297            const bool ok = std::fabs(mixed_by_mode[mode][0] - expected_mixed) <= 2e-7f &&
298                            mixed_by_mode[mode][0] == mixed_by_mode[mode][1] &&
299                            inject_by_mode[mode] == expected_inject;
300            std::printf("  scalar gamma %.8f %s activation/capture %s (mixed %.9f, ref %.9f)\n",
301                        gamma, activation_mode_name(mode), ok ? "pass" : "FAIL",
302                        mixed_by_mode[mode][0], expected_mixed);
303            if (!ok) ++bad;
304            check(DPCT_CHECK_ERROR(delete (executable)),
305                  "scalar graph exec destroy");
306            check(DPCT_CHECK_ERROR(delete (graph)), "scalar graph destroy");
307
308            const float sentinel = -73.25f;
309            check(
310                DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
311                                     .memcpy(d_inject, &sentinel, sizeof(float))
312                                     .wait()),
313                "scalar sentinel");
314            select_activation_mode(mode);
315            gr_read(d_R, d_norm, d_weights, d_weights + 4, nullptr, 0.0f,
316                    sh, ws, d_mixed, d_inject, stream);
317            check(DPCT_CHECK_ERROR(stream->wait()), "scalar final mixer sync");
318            float final_mixed[2] = {}, untouched = 0.0f;
319            check(DPCT_CHECK_ERROR(
320                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
321                          .memcpy(final_mixed, d_mixed, sizeof(final_mixed))
322                          .wait()),
323                  "scalar final mixed");
324            check(DPCT_CHECK_ERROR(
325                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
326                          .memcpy(&untouched, d_inject, sizeof(float))
327                          .wait()),
328                  "scalar sentinel copy");
329            const bool final_ok = std::memcmp(final_mixed, mixed_by_mode[mode], sizeof(final_mixed)) == 0 && untouched == sentinel;
330            std::printf("  scalar final mixer %s %s\n", activation_mode_name(mode), final_ok ? "pass" : "FAIL");
331            if (!final_ok) ++bad;
332        }
333        if (std::fabs(mixed_by_mode[1][0] - mixed_by_mode[0][0]) <= 1e-5f ||
334            (gamma != 1.0f && inject_by_mode[0] == inject_by_mode[1])) {
335            std::printf("  scalar precision fixture is not observable\n");
336            ++bad;
337        }
338        if (inject_by_mode[1] != inject_by_mode[2]) {
339            std::printf("  native MMVF changed the exact scalar FP32 injection projection\n");
340            ++bad;
341        }
342    }
343    select_activation_mode(0);
344    check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(stream)),
345          "scalar stream destroy");
346    sycl::free(d_R, dpct::get_in_order_queue());
347        sycl::free(d_norm, dpct::get_in_order_queue());
348        sycl::free(d_mixed, dpct::get_in_order_queue());
349        sycl::free(d_inject, dpct::get_in_order_queue());
350    sycl::free(d_weights, dpct::get_in_order_queue());
351        sycl::free(d_scratch, dpct::get_in_order_queue());
352    return bad;
353}
354
355int fused_multi_lds_parity(const float* d_norm, const uint16_t* d_down, const uint16_t* d_up,
356                           const uint16_t* d_inject, float eps) {
357    using namespace strata::kernels;
358    constexpr int N = strata::core::kCompiledGeometry.n_embd, HC = strata::core::kCompiledGeometry.hc, LR = strata::core::kCompiledGeometry.hc_lr, D = N * HC, T = kFusedGrMaxT;   // the compiled shape (Q4-SYCL; Flash-Next: 2560 / 4 / 320)
359    std::mt19937 rng(0x6f8a);
360    std::normal_distribution<float> normal(0.0f, 0.3f);
361    std::vector<float> r((size_t) T * D), bo((size_t) T * N), inj((size_t) T * HC);
362    for (auto& x : r) x = normal(rng);
363    for (auto& x : bo) x = normal(rng);
364    for (auto& x : inj) x = normal(rng);
365
366    float *d_r = nullptr, *d_r_out = nullptr, *d_bo = nullptr, *d_inj = nullptr;
367    float *d_lo = nullptr, *d_rs = nullptr, *d_inj_out = nullptr, *d_mixed = nullptr, *d_xn = nullptr;
368    check(DPCT_CHECK_ERROR(d_r = sycl::malloc_device<float>(
369                               r.size(), dpct::get_in_order_queue())),
370          "multi R");
371    check(DPCT_CHECK_ERROR(d_r_out = sycl::malloc_device<float>(
372                               r.size(), dpct::get_in_order_queue())),
373          "multi R_out");
374    check(DPCT_CHECK_ERROR(d_bo = sycl::malloc_device<float>(
375                               bo.size(), dpct::get_in_order_queue())),
376          "multi bo");
377    check(DPCT_CHECK_ERROR(d_inj = sycl::malloc_device<float>(
378                               inj.size(), dpct::get_in_order_queue())),
379          "multi inj");
380    check(DPCT_CHECK_ERROR(d_lo = sycl::malloc_device<float>(
381                               (size_t)T * LR, dpct::get_in_order_queue())),
382          "multi lo");
383    check(DPCT_CHECK_ERROR(d_rs = sycl::malloc_device<float>(
384                               (size_t)T * HC, dpct::get_in_order_queue())),
385          "multi rs");
386    check(DPCT_CHECK_ERROR(d_inj_out = sycl::malloc_device<float>(
387                               (size_t)T * HC, dpct::get_in_order_queue())),
388          "multi injection");
389    check(DPCT_CHECK_ERROR(d_mixed = sycl::malloc_device<float>(
390                               (size_t)T * N, dpct::get_in_order_queue())),
391          "multi mixed");
392    check(DPCT_CHECK_ERROR(d_xn = sycl::malloc_device<float>(
393                               (size_t)T * D, dpct::get_in_order_queue())),
394          "multi xn");
395    /*
396    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
397    the original code the source host memory is pageable memory. If the memory
398    is not pageable, call wait() on event return by memcpy API to ensure
399    synchronization behavior.
400    */
401    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
402              d_r, r.data(), r.size() * sizeof(float)).wait()),
403          "multi copy R");
404    /*
405    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
406    the original code the source host memory is pageable memory. If the memory
407    is not pageable, call wait() on event return by memcpy API to ensure
408    synchronization behavior.
409    */
410    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
411              d_bo, bo.data(), bo.size() * sizeof(float)).wait()),
412          "multi copy bo");
413    /*
414    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
415    the original code the source host memory is pageable memory. If the memory
416    is not pageable, call wait() on event return by memcpy API to ensure
417    synchronization behavior.
418    */
419    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
420              d_inj, inj.data(), inj.size() * sizeof(float)).wait()),
421          "multi copy inj");
422
423    std::vector<FusedGrArgs> args(T);
424    for (int t = 0; t < T; ++t) {
425        auto& a = args[t];
426        a.R = d_r + (size_t) t * D;
427        a.R_out = d_r_out + (size_t) t * D;
428        a.apply = true;
429        a.bo_prev = d_bo + (size_t) t * N;
430        a.inj_prev = d_inj + (size_t) t * HC;
431        a.w_norm = d_norm;
432        a.w_down = d_down;
433        a.w_up = d_up;
434        a.w_inject = d_inject;
435        a.eps = eps;
436        a.lo = d_lo + (size_t) t * LR;
437        a.rs = d_rs + (size_t) t * HC;
438        a.inject_out = d_inj_out + (size_t) t * HC;
439        a.mixed = d_mixed + (size_t) t * N;
440    }
441
442    struct Snapshot {
443        std::vector<float> r_out, lo, rs, inject, mixed;
444    };
445    auto snapshot = [&]() {
446        try {
447    Snapshot s;
448        s.r_out.resize((size_t) T * D);
449        s.lo.resize((size_t) T * LR);
450        s.rs.resize((size_t) T * HC);
451        s.inject.resize((size_t) T * HC);
452        s.mixed.resize((size_t) T * N);
453        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
454                                   .memcpy(s.r_out.data(), d_r_out,
455                                           s.r_out.size() * sizeof(float))
456                                   .wait()),
457              "multi read R_out");
458        check(DPCT_CHECK_ERROR(
459                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
460                      .memcpy(s.lo.data(), d_lo, s.lo.size() * sizeof(float))
461                      .wait()),
462              "multi read lo");
463        check(DPCT_CHECK_ERROR(
464                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
465                      .memcpy(s.rs.data(), d_rs, s.rs.size() * sizeof(float))
466                      .wait()),
467              "multi read rs");
468        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
469                                   .memcpy(s.inject.data(), d_inj_out,
470                                           s.inject.size() * sizeof(float))
471                                   .wait()),
472              "multi read inject");
473        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
474                                   .memcpy(s.mixed.data(), d_mixed,
475                                           s.mixed.size() * sizeof(float))
476                                   .wait()),
477              "multi read mixed");
478        return s;
479    }
480    catch (sycl::exception const &exc) {
481      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
482                << ", line:" << __LINE__ << std::endl;
483      std::exit(1);
484    }
485    };
486    // the split read (STRATA_GR_V3=1) sums in another order than the single-token kernel: equal within float
487    // rounding, not to the bit, so it is compared with a relative tolerance; the default kernels bit for bit
488    static const bool v3 = [] { const char* v = std::getenv("STRATA_GR_V3"); return v != nullptr && std::atoi(v) != 0; }();
489    auto close = [](const std::vector<float>& x, const std::vector<float>& y) {
490        double worst = 0.0, mag = 1e-30;
491        for (size_t i = 0; i < x.size(); ++i) {
492            worst = std::max(worst, (double) std::fabs(x[i] - y[i]));
493            mag = std::max(mag, (double) std::fabs(y[i]));
494        }
495        if (worst > 2e-6 * mag)
496            std::printf("    tolerance: worst %.3e of max |ref| %.3e (rel %.3e), n %zu\n", worst, mag, worst / mag, x.size());
497        return worst <= 2e-6 * mag;
498    };
499    auto same = [&](const Snapshot& a, const Snapshot& b) {
500        if (v3)   // `lo` is the default kernels' workspace between down and up; the split read keeps it in shared memory
501            return close(a.r_out, b.r_out) && close(a.rs, b.rs) && close(a.inject, b.inject) && close(a.mixed, b.mixed);
502        return std::memcmp(a.r_out.data(), b.r_out.data(), a.r_out.size() * sizeof(float)) == 0 &&
503               std::memcmp(a.lo.data(), b.lo.data(), a.lo.size() * sizeof(float)) == 0 &&
504               std::memcmp(a.rs.data(), b.rs.data(), a.rs.size() * sizeof(float)) == 0 &&
505               std::memcmp(a.inject.data(), b.inject.data(), a.inject.size() * sizeof(float)) == 0 &&
506               std::memcmp(a.mixed.data(), b.mixed.data(), a.mixed.size() * sizeof(float)) == 0;
507    };
508
509    dpct::queue_ptr stream = &dpct::get_in_order_queue();
510    /*
511    DPCT1025: The SYCL queue is created ignoring the flag and priority
512    options.
513    */
514    check(DPCT_CHECK_ERROR(stream =
515                               dpct::get_current_device().create_queue(true)),
516          "multi stream");
517    // Max T forces the HIP kernel's full dynamic-LDS request: 8 * 1280 * sizeof(float) = 40 KiB.
518    fused_gr_read_multi(args.data(), T, d_xn, stream);
519    check(DPCT_CHECK_ERROR(stream->wait()), "multi max-T sync");
520    const Snapshot multi = snapshot();
521    for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream);
522    check(DPCT_CHECK_ERROR(stream->wait()), "single reference sync");
523    const Snapshot single = snapshot();
524    int bad = 0;
525    if (!same(multi, single)) {
526        std::printf("  fused GR multi max-T differs from single-token calls\n");
527        ++bad;
528    }
529
530    dpct::experimental::command_graph_ptr graph = nullptr;
531    dpct::experimental::command_graph_exec_ptr graph_exec = nullptr;
532    check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(stream)),
533          "multi graph begin");
534    fused_gr_read_multi(args.data(), T, d_xn, stream);
535    check(DPCT_CHECK_ERROR(dpct::experimental::end_recording(stream, &graph)),
536          "multi graph end");
537    check(DPCT_CHECK_ERROR(
538              graph_exec = new sycl::ext::oneapi::experimental::command_graph<
539                  sycl::ext::oneapi::experimental::graph_state::executable>(
540                  graph->finalize())),
541          "multi graph instantiate");
542    check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*graph_exec)),
543          "multi graph initial replay");
544    check(DPCT_CHECK_ERROR(stream->wait()), "multi graph initial sync");
545    const Snapshot captured = snapshot();
546    if (!same(multi, captured)) {
547        std::printf("  fused GR multi captured graph differs from direct max-T call\n");
548        ++bad;
549    }
550
551    // Reuse the same captured pointers with new payloads; then independently run the single-token path again.
552    for (size_t i = 0; i < r.size(); ++i) r[i] = -0.7f * r[i] + 0.001f * (float) (i % 17);
553    for (size_t i = 0; i < bo.size(); ++i) bo[i] = -0.4f * bo[i] + 0.02f;
554    for (size_t i = 0; i < inj.size(); ++i) inj[i] += 0.3f;
555    /*
556    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
557    the origin API might be synchronous, it depends on the type of operand
558    memory, so you may need to call wait() on event return by memcpy API to
559    ensure synchronization behavior.
560    */
561    check(DPCT_CHECK_ERROR(
562              stream->memcpy(d_r, r.data(), r.size() * sizeof(float))),
563          "multi replay R");
564    /*
565    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
566    the origin API might be synchronous, it depends on the type of operand
567    memory, so you may need to call wait() on event return by memcpy API to
568    ensure synchronization behavior.
569    */
570    check(DPCT_CHECK_ERROR(
571              stream->memcpy(d_bo, bo.data(), bo.size() * sizeof(float))),
572          "multi replay bo");
573    /*
574    DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While
575    the origin API might be synchronous, it depends on the type of operand
576    memory, so you may need to call wait() on event return by memcpy API to
577    ensure synchronization behavior.
578    */
579    check(DPCT_CHECK_ERROR(
580              stream->memcpy(d_inj, inj.data(), inj.size() * sizeof(float))),
581          "multi replay inj");
582    check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*graph_exec)),
583          "multi graph changed replay");
584    check(DPCT_CHECK_ERROR(stream->wait()), "multi graph changed sync");
585    const Snapshot replay = snapshot();
586    if (std::memcmp(multi.mixed.data(), replay.mixed.data(), multi.mixed.size() * sizeof(float)) == 0) {
587        std::printf("  fused GR graph replay ignored changed inputs\n");
588        ++bad;
589    }
590    for (int t = 0; t < T; ++t) fused_gr_read(args[t], stream);
591    check(DPCT_CHECK_ERROR(stream->wait()), "changed single reference sync");
592    if (!same(replay, snapshot())) {
593        std::printf("  fused GR changed graph replay differs from single-token calls\n");
594        ++bad;
595    }
596
597
598    // S26 STRATA_QFUSE: the read's own q8_1 image of `mixed` must be the bytes native_quantize_q8_1 writes from it -
599    // for every T (1..8), directly and through a captured graph replayed twice (the group counters must reset)
600    {
601        uint8_t *d_q = nullptr, *d_ref = nullptr;
602        unsigned* d_cnt = nullptr;
603        const size_t qbytes = (size_t) T * (N / 32) * 36;
604        check(DPCT_CHECK_ERROR(d_q = (uint8_t *)sycl::malloc_device(
605                                   qbytes, dpct::get_in_order_queue())),
606              "qfuse q8");
607        check(DPCT_CHECK_ERROR(d_ref = (uint8_t *)sycl::malloc_device(
608                                   qbytes, dpct::get_in_order_queue())),
609              "qfuse ref");
610        check(DPCT_CHECK_ERROR(d_cnt = sycl::malloc_device<unsigned int>(
611                                   (N / 32), dpct::get_in_order_queue())),
612              "qfuse counters");
613        check(
614            DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
615                                 .memset(d_cnt, 0, (N / 32) * sizeof(unsigned))
616                                 .wait()),
617            "qfuse counters zero");
618        int qbad = 0;
619        bool qskip = false;   // SYCL port: see below
620        std::vector<uint8_t> hq(qbytes), hr(qbytes);
621        for (int tt = 1; tt <= T && !qbad && !qskip; ++tt) {
622            std::vector<FusedGrArgs> qa(args.begin(), args.begin() + tt);
623            for (int t = 0; t < tt; ++t) { qa[t].q8_mixed = d_q + (size_t) t * (N / 32) * 36; qa[t].q8_cnt = d_cnt; }
624            for (int rep = 0; rep < 3 && !qbad; ++rep) {
625                check(DPCT_CHECK_ERROR(stream->memset(d_q, 0x5a, qbytes)),
626                      "qfuse poison");
627                bool wrote = false;
628                dpct::experimental::command_graph_ptr qg = nullptr;
629                dpct::experimental::command_graph_exec_ptr qx = nullptr;
630                if (rep == 0) {
631                    wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
632                } else {   // a captured read, replayed (twice: rep 1 and 2 use fresh captures, each replayed twice)
633                    check(DPCT_CHECK_ERROR(
634                              dpct::experimental::begin_recording(stream)),
635                          "qfuse begin");
636                    wrote = fused_gr_read_multi(qa.data(), tt, d_xn, stream);
637                    check(DPCT_CHECK_ERROR(
638                              dpct::experimental::end_recording(stream, &qg)),
639                          "qfuse end");
640                    check(
641                        DPCT_CHECK_ERROR(
642                            qx = new sycl::ext::oneapi::experimental::
643                                command_graph<sycl::ext::oneapi::experimental::
644                                                  graph_state::executable>(
645                                    qg->finalize())),
646                        "qfuse instantiate");
647                    check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*qx)),
648                          "qfuse replay 1");
649                    check(DPCT_CHECK_ERROR(stream->memset(d_q, 0x5a, qbytes)),
650                          "qfuse poison 2");
651                    check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*qx)),
652                          "qfuse replay 2");
653                }
654                strata::kernels::native_quantize_q8_1(d_mixed, d_ref, N, tt, stream);
655                check(DPCT_CHECK_ERROR(stream->wait()), "qfuse sync");
656                if (qx) { delete (qx); delete (qg); }
657                if (v3) { std::printf("  QFUSE: the v3 read writes no q8_1 (%s)\n", wrote ? "WRONG: it says it did" : "ok"); qbad += wrote; break; }
658                // SYCL port: fused_gr_read_multi never writes the q8_1 image here (fused_gr.dp.cpp: the caller quantizes),
659                // so there is nothing to compare - the engine's STRATA_QFUSE path falls back to native_quantize_q8_1
660                if (!wrote && tt == 1 && rep == 0) { std::printf("  QFUSE: not built in the SYCL port (the caller quantizes): skipped\n"); qskip = true; break; }
661                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
662                                           .memcpy(hq.data(), d_q,
663                                                   (size_t)tt * (N / 32) * 36)
664                                           .wait()),
665                      "qfuse read");
666                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
667                                           .memcpy(hr.data(), d_ref,
668                                                   (size_t)tt * (N / 32) * 36)
669                                           .wait()),
670                      "qfuse ref read");
671                if (!wrote || std::memcmp(hq.data(), hr.data(), (size_t) tt * (N / 32) * 36) != 0) {
672                    std::printf("  QFUSE: T=%d rep %d: %s\n", tt, rep, wrote ? "q8_1 bytes differ" : "not written");
673                    ++qbad;
674                }
675            }
676        }
677        std::printf("  fused GR read + q8_1 (STRATA_QFUSE), T 1..8, direct and graph replays: %s\n", qbad ? "FAIL" : qskip ? "skipped" : "pass");
678        bad += qbad;
679        sycl::free(d_q, dpct::get_in_order_queue());
680            sycl::free(d_ref, dpct::get_in_order_queue());
681            sycl::free(d_cnt, dpct::get_in_order_queue());
682    }
683    std::printf("  fused GR multi max-T=8 LDS launch and changing graph replay %s\n",
684                bad == 0 ? "pass" : "FAIL");
685    check(DPCT_CHECK_ERROR(delete (graph_exec)), "multi graph exec destroy");
686    check(DPCT_CHECK_ERROR(delete (graph)), "multi graph destroy");
687    check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(stream)),
688          "multi stream destroy");
689    check(DPCT_CHECK_ERROR(sycl::free(d_xn, dpct::get_in_order_queue())),
690          "free multi xn");
691    check(DPCT_CHECK_ERROR(sycl::free(d_mixed, dpct::get_in_order_queue())),
692          "free multi mixed");
693    check(DPCT_CHECK_ERROR(sycl::free(d_inj_out, dpct::get_in_order_queue())),
694          "free multi injection");
695    check(DPCT_CHECK_ERROR(sycl::free(d_rs, dpct::get_in_order_queue())),
696          "free multi rs");
697    check(DPCT_CHECK_ERROR(sycl::free(d_lo, dpct::get_in_order_queue())),
698          "free multi lo");
699    check(DPCT_CHECK_ERROR(sycl::free(d_inj, dpct::get_in_order_queue())),
700          "free multi inj");
701    check(DPCT_CHECK_ERROR(sycl::free(d_bo, dpct::get_in_order_queue())),
702          "free multi bo");
703    check(DPCT_CHECK_ERROR(sycl::free(d_r_out, dpct::get_in_order_queue())),
704          "free multi R_out");
705    check(DPCT_CHECK_ERROR(sycl::free(d_r, dpct::get_in_order_queue())),
706          "free multi R");
707    return bad;
708}
709
710}  // namespace
711
712int main(int argc, char** argv) {
713    bool selftest = false;
714    for (int i = 1; i < argc; ++i) {
715        if (std::string(argv[i]) == "--selftest") selftest = true;
716        else { std::fprintf(stderr, "usage: gr_parity [--selftest]\n"); return 2; }
717    }
718
719    const long long n_embd = 256, hc = 4, hc_lr = 32;
720    const long long hc_dim = hc * n_embd;
721    const float eps = 1e-6f;
722    std::mt19937 rng(1234);
723    std::normal_distribution<float> gauss(0.0f, 1.0f);
724
725    // Weights are BF16-VALUED f32, which is what the pack holds for a BF16 source type.  Generating plain f32
726    // weights would make the kernel (which stores 16 bits) differ from the reference by the rounding itself,
727    // and the test would then be measuring the fixture.
728    auto bf16_weight = [&](size_t n, float sigma) {
729        std::vector<float> v(n);
730        for (auto& x : v) x = to_bf16(gauss(rng) * sigma);
731        return v;
732    };
733    std::vector<float> R((size_t) hc_dim);
734    for (auto& x : R) x = gauss(rng);
735    // STREAM SCALES 1, 4, 16, 64.  Without them trap 1 is only ~5% observable, because four streams of i.i.d.
736    // normal noise have nearly the same RMS by accident - so a whole-stack RMS and a per-stream RMS agree to
737    // within the noise, and the fixture would be asserting a distinction it cannot see.  Giving the streams
738    // different magnitudes is what makes "per-stream" a claim with content.
739    for (long long c = 0; c < hc; ++c)
740        for (long long d = 0; d < n_embd; ++d) R[(size_t) (c * n_embd + d)] *= std::pow(4.0f, (float) c);
741    // gamma stored as (1 + w), so values near 1 - a reader expecting a plain scale is the one this catches
742    std::vector<float> w_norm((size_t) hc_dim);
743    for (auto& x : w_norm) x = 1.0f + 0.1f * gauss(rng);
744    std::vector<float> w_down = bf16_weight((size_t) (hc_lr * hc_dim), 0.2f);
745    std::vector<float> w_up = bf16_weight((size_t) (hc_dim * hc_lr), 0.2f);
746    std::vector<float> w_inject = bf16_weight((size_t) (hc * hc_dim), 0.05f);
747
748    // NO PERMUTATION: the kernel takes both matrices exactly as the manifest (and `ref/gr.py`) store them.
749    // `w_down` is (hc_lr, hc_dim) row-major and `w_up` is (hc_dim, hc_lr) row-major, so the bit-copy below is
750    // the whole conversion.  An earlier version of this kernel wanted both TRANSPOSED - the test built them
751    // that way and asserted the orientation observable - and that is gone because the warp-per-row mapping
752    // makes it unnecessary.  What replaces it is the general orientation trap further down: a weight array
753    // read with the wrong index expression must still produce a visibly different answer.
754    std::vector<uint16_t> q_down(w_down.size()), q_up(w_up.size()), q_inject(w_inject.size());
755    for (size_t i = 0; i < w_down.size(); ++i) q_down[i] = bf16_bits(w_down[i]);
756    for (size_t i = 0; i < w_up.size(); ++i) q_up[i] = bf16_bits(w_up[i]);
757    for (size_t i = 0; i < w_inject.size(); ++i) q_inject[i] = bf16_bits(w_inject[i]);
758
759    // ---- device side
760    float *d_R = nullptr, *d_norm = nullptr, *d_mixed = nullptr, *d_inject = nullptr;
761    uint16_t *d_down = nullptr, *d_up = nullptr, *d_inj = nullptr;
762    check(DPCT_CHECK_ERROR(d_R = sycl::malloc_device<float>(
763                               R.size(), dpct::get_in_order_queue())),
764          "m R");
765    check(DPCT_CHECK_ERROR(d_norm = sycl::malloc_device<float>(
766                               w_norm.size(), dpct::get_in_order_queue())),
767          "m norm");
768    check(DPCT_CHECK_ERROR(d_down = sycl::malloc_device<uint16_t>(
769                               q_down.size(), dpct::get_in_order_queue())),
770          "m down");
771    check(DPCT_CHECK_ERROR(d_up = sycl::malloc_device<uint16_t>(
772                               q_up.size(), dpct::get_in_order_queue())),
773          "m up");
774    check(DPCT_CHECK_ERROR(d_inj = sycl::malloc_device<uint16_t>(
775                               q_inject.size(), dpct::get_in_order_queue())),
776          "m inj");
777    check(DPCT_CHECK_ERROR(d_mixed = sycl::malloc_device<float>(
778                               (size_t)n_embd, dpct::get_in_order_queue())),
779          "m mixed");
780    check(DPCT_CHECK_ERROR(d_inject = sycl::malloc_device<float>(
781                               (size_t)hc, dpct::get_in_order_queue())),
782          "m inject");
783    /*
784    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
785    the original code the source host memory is pageable memory. If the memory
786    is not pageable, call wait() on event return by memcpy API to ensure
787    synchronization behavior.
788    */
789    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
790              d_R, R.data(), R.size() * sizeof(float)).wait()),
791          "c R");
792    /*
793    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
794    the original code the source host memory is pageable memory. If the memory
795    is not pageable, call wait() on event return by memcpy API to ensure
796    synchronization behavior.
797    */
798    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
799              d_norm, w_norm.data(), w_norm.size() * sizeof(float)).wait()),
800          "c norm");
801    /*
802    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
803    the original code the source host memory is pageable memory. If the memory
804    is not pageable, call wait() on event return by memcpy API to ensure
805    synchronization behavior.
806    */
807    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
808              d_down, q_down.data(), q_down.size() * sizeof(uint16_t)).wait()),
809          "c down");
810    /*
811    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
812    the original code the source host memory is pageable memory. If the memory
813    is not pageable, call wait() on event return by memcpy API to ensure
814    synchronization behavior.
815    */
816    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
817              d_up, q_up.data(), q_up.size() * sizeof(uint16_t)).wait()),
818          "c up");
819    /*
820    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
821    the original code the source host memory is pageable memory. If the memory
822    is not pageable, call wait() on event return by memcpy API to ensure
823    synchronization behavior.
824    */
825    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
826              d_inj, q_inject.data(), q_inject.size() * sizeof(uint16_t)).wait()),
827          "c inj");
828
829    const strata::kernels::GrShapes sh{n_embd, hc, hc_lr};
830    // DEVICE memory: the workspace is written by the kernel.
831    void* d_ws_raw = nullptr;
832    check(DPCT_CHECK_ERROR(d_ws_raw = (void *)sycl::malloc_device(
833                               strata::kernels::gr_workspace_bytes(sh),
834                               dpct::get_in_order_queue())),
835          "m ws");
836    strata::kernels::GrWorkspace ws;
837    strata::kernels::gr_workspace_init(sh, d_ws_raw, ws);
838    strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
839    std::vector<float> got_mixed((size_t) n_embd), got_inject((size_t) hc);
840    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
841                               .memcpy(got_mixed.data(), d_mixed,
842                                       got_mixed.size() * sizeof(float))
843                               .wait()),
844          "c mixed");
845    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
846                               .memcpy(got_inject.data(), d_inject,
847                                       got_inject.size() * sizeof(float))
848                               .wait()),
849          "c inject");
850
851    int bad = 0;
852
853    // ---- the traps, asserted OBSERVABLE before the kernel is judged against the right reading
854    Opts right;
855    std::vector<float> want_mixed, want_inject;
856    reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, right, want_mixed, want_inject);
857
858    struct Trap { const char* name; Opts o; double floor; };
859    const Trap traps[] = {
860        {"per-stream RMSNorm vs whole-stack", {false, true, true, true, true}, 0.05},
861        {"/hc inside the silu vs outside", {true, false, true, true, true}, 0.05},
862        {"SiLU on lo / sigmoid on gate, swapped", {true, true, false, true, true}, 0.05},
863        {"mean over streams vs sum", {true, true, true, false, true}, 0.50},
864        {"BF16 vs FP32 activation contracts", {true, true, true, true, false}, 1e-4},
865    };
866    for (const Trap& t : traps) {
867        std::vector<float> m, i;
868        reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, t.o, m, i);
869        const double rel = rel_diff(want_mixed, m);
870        const bool observable = rel > t.floor;
871        std::printf("  %-40s %-4s (%.4f%% apart, floor %.3f%%)\n", t.name, observable ? "yes" : "*** NO ***",
872                    rel * 100, t.floor * 100);
873        if (!observable) {
874            std::printf("      *** the fixture cannot see this trap, so passing proves nothing about it ***\n");
875            ++bad;
876        }
877    }
878
879    // ---- the kernel against the correct reference
880    double mag = 0;
881    const double rel_mixed = rel_diff(want_mixed, got_mixed, &mag);
882    std::printf("\n  %-40s worst %.3e (mean |ref| %.4f)\n", "mixed vs reference", rel_mixed, mag);
883
884    // The tolerance is set by SUMMATION ORDER, not by the structure: both sides round the activation to bf16
885    // and both weights are bf16-valued, so every product is exact in f32 and only the order differs.  A
886    // structural error is several orders of magnitude larger - the trap floors above say so.
887    if (!(rel_mixed <= 1e-4)) {
888        std::printf("    *** over 1e-4, which summation order does not explain - look for a structural bug ***\n");
889        ++bad;
890    }
891
892    const double rel_inject = rel_diff(want_inject, got_inject);
893    std::printf("  %-40s rel %.3e\n", "inject vs reference", rel_inject);
894    if (!(rel_inject <= 1e-4)) {
895        // Say WHICH elements and by how much: a whole-array L1 hides whether this is one stream wrong (an
896        // indexing bug) or all of them slightly wrong (a precision bug), and those need different responses.
897        std::printf("    want:");
898        for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) want_inject[(size_t) c]);
899        std::printf("\n    got :");
900        for (long long c = 0; c < hc; ++c) std::printf(" %12.6f", (double) got_inject[(size_t) c]);
901        std::printf("\n");
902        ++bad;
903    }
904
905    // Same geometry and weights with the CUDA single-token activation contract.  The scalar fixture
906    // below is the independent precision check; this case exercises multi-stream reductions and indexing.
907    {
908        Opts fp32;
909        fp32.round_activation = false;
910        std::vector<float> wm, wi, gm((size_t) n_embd), gi((size_t) hc);
911        reference(R, w_norm, w_down, w_up, w_inject, eps, n_embd, hc, hc_lr, fp32, wm, wi);
912        strata::kernels::gr_set_fp32_activations(true);
913        strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
914        check(DPCT_CHECK_ERROR(
915                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
916                      .memcpy(gm.data(), d_mixed, gm.size() * sizeof(float))
917                      .wait()),
918              "FP32 mixed");
919        check(DPCT_CHECK_ERROR(
920                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
921                      .memcpy(gi.data(), d_inject, gi.size() * sizeof(float))
922                      .wait()),
923              "FP32 inject");
924        strata::kernels::gr_set_fp32_activations(false);
925        const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi);
926        const bool ok = rm <= 1e-4 && ri <= 1e-4;
927        std::printf("  FP32 activations vs reference: %s (mixed %.3e, inject %.3e)\n",
928                    ok ? "pass" : "FAIL", rm, ri);
929        if (!ok) ++bad;
930        strata::kernels::gr_read(d_R, d_norm, d_down, d_up, d_inj, eps, sh, ws, d_mixed, d_inject, nullptr);
931        check(DPCT_CHECK_ERROR(
932                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
933                      .memcpy(gm.data(), d_mixed, gm.size() * sizeof(float))
934                      .wait()),
935              "restored mixed");
936        check(DPCT_CHECK_ERROR(
937                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
938                      .memcpy(gi.data(), d_inject, gi.size() * sizeof(float))
939                      .wait()),
940              "restored inject");
941        const bool restored = std::memcmp(gm.data(), got_mixed.data(), gm.size() * sizeof(float)) == 0 &&
942                              std::memcmp(gi.data(), got_inject.data(), gi.size() * sizeof(float)) == 0;
943        std::printf("  restoring default activation contract: %s\n", restored ? "byte-identical" : "FAIL");
944        if (!restored) ++bad;
945    }
946
947    // ---- THE WEIGHT ORIENTATION MUST BE OBSERVABLE.  The kernel now takes both matrices exactly as the
948    // manifest stores them, so there is no permutation for a loader to forget - but the INDEX EXPRESSIONS
949    // inside the kernel are still a place to be wrong, and a wrong one gives right-shaped, wrong-valued
950    // output.  Feed transposed copies through the same code path and require the answer to differ.
951    {
952        uint16_t *d_down_bad = nullptr, *d_up_bad = nullptr;
953        check(DPCT_CHECK_ERROR(d_down_bad = sycl::malloc_device<uint16_t>(
954                                   q_down.size(), dpct::get_in_order_queue())),
955              "m down_bad");
956        check(DPCT_CHECK_ERROR(d_up_bad = sycl::malloc_device<uint16_t>(
957                                   q_up.size(), dpct::get_in_order_queue())),
958              "m up_bad");
959        std::vector<uint16_t> tr_down(q_down.size()), tr_up(q_up.size());
960        for (long long k = 0; k < hc_lr; ++k)
961            for (long long i = 0; i < hc_dim; ++i)
962                tr_down[(size_t) (i * hc_lr + k)] = q_down[(size_t) (k * hc_dim + i)];
963        for (long long i = 0; i < hc_dim; ++i)
964            for (long long k = 0; k < hc_lr; ++k)
965                tr_up[(size_t) (k * hc_dim + i)] = q_up[(size_t) (i * hc_lr + k)];
966        /*
967        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
968        assuming in the original code the source host memory is pageable memory.
969        If the memory is not pageable, call wait() on event return by memcpy API
970        to ensure synchronization behavior.
971        */
972        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
973                  d_down_bad, tr_down.data(), tr_down.size() * 2).wait()),
974              "cb d");
975        /*
976        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
977        assuming in the original code the source host memory is pageable memory.
978        If the memory is not pageable, call wait() on event return by memcpy API
979        to ensure synchronization behavior.
980        */
981        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
982                  d_up_bad, tr_up.data(), tr_up.size() * 2).wait()),
983              "cb u");
984        std::vector<float> bad_mixed((size_t) n_embd);
985        float* d_bad = nullptr;
986        check(
987            DPCT_CHECK_ERROR(d_bad = sycl::malloc_device<float>(
988                                 bad_mixed.size(), dpct::get_in_order_queue())),
989            "m bad");
990        strata::kernels::gr_read(d_R, d_norm, d_down_bad, d_up_bad, d_inj, eps, sh, ws, d_bad, d_inject,
991                                 nullptr);
992        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
993                                   .memcpy(bad_mixed.data(), d_bad,
994                                           bad_mixed.size() * sizeof(float))
995                                   .wait()),
996              "cb b");
997        const double rel = rel_diff(want_mixed, bad_mixed);
998        const bool visible = rel > 0.05;
999        std::printf("  %-40s %s (%.1f%% apart)\n", "weight orientation is observable",
1000                    visible ? "yes" : "*** NO ***", rel * 100);
1001        if (!visible) ++bad;
1002        sycl::free(d_down_bad, dpct::get_in_order_queue());
1003            sycl::free(d_up_bad, dpct::get_in_order_queue());
1004            sycl::free(d_bad, dpct::get_in_order_queue());
1005    }
1006
1007    // ---- the FINAL mixer passes w_inject = nullptr, and then nothing may be written
1008    float sentinel = -12345.0f;
1009    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1010                               .memcpy(d_inject, &sentinel, sizeof(float))
1011                               .wait()),
1012          "c sentinel");
1013    strata::kernels::gr_read(d_R, d_norm, d_down, d_up, nullptr, eps, sh, ws, d_mixed, d_inject, nullptr);
1014    float after = 0.0f;
1015    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1016                               .memcpy(&after, d_inject, sizeof(float))
1017                               .wait()),
1018          "c after");
1019    const bool untouched = (after == sentinel);
1020    std::printf("  %-40s %s\n", "null w_inject writes nothing", untouched ? "yes" : "*** NO ***");
1021    if (!untouched) ++bad;
1022
1023    // ---- gr_write: the `2*sigmoid` centring, asserted as the PROPERTY the source comment claims
1024    std::vector<float> block_out((size_t) n_embd);
1025    for (auto& x : block_out) x = gauss(rng);
1026    std::vector<float> zero_inj((size_t) hc, 0.0f);
1027    float *d_Rw = nullptr, *d_bo = nullptr, *d_zi = nullptr, *d_outw = nullptr;
1028    check(DPCT_CHECK_ERROR(d_Rw = sycl::malloc_device<float>(
1029                               R.size(), dpct::get_in_order_queue())),
1030          "m Rw");
1031    check(DPCT_CHECK_ERROR(d_bo = sycl::malloc_device<float>(
1032                               block_out.size(), dpct::get_in_order_queue())),
1033          "m bo");
1034    check(DPCT_CHECK_ERROR(d_zi = sycl::malloc_device<float>(
1035                               zero_inj.size(), dpct::get_in_order_queue())),
1036          "m zi");
1037    check(DPCT_CHECK_ERROR(d_outw = sycl::malloc_device<float>(
1038                               R.size(), dpct::get_in_order_queue())),
1039          "m outw");
1040    /*
1041    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
1042    the original code the source host memory is pageable memory. If the memory
1043    is not pageable, call wait() on event return by memcpy API to ensure
1044    synchronization behavior.
1045    */
1046    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1047              d_Rw, R.data(), R.size() * sizeof(float)).wait()),
1048          "c Rw");
1049    /*
1050    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
1051    the original code the source host memory is pageable memory. If the memory
1052    is not pageable, call wait() on event return by memcpy API to ensure
1053    synchronization behavior.
1054    */
1055    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1056              d_bo, block_out.data(), block_out.size() * sizeof(float)).wait()),
1057          "c bo");
1058    /*
1059    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
1060    the original code the source host memory is pageable memory. If the memory
1061    is not pageable, call wait() on event return by memcpy API to ensure
1062    synchronization behavior.
1063    */
1064    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1065              d_zi, zero_inj.data(), zero_inj.size() * sizeof(float)).wait()),
1066          "c zi");
1067
1068    strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr);
1069    std::vector<float> got_write((size_t) hc_dim);
1070    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1071                               .memcpy(got_write.data(), d_outw,
1072                                       got_write.size() * sizeof(float))
1073                               .wait()),
1074          "c outw");
1075
1076    double worst_plain = 0;
1077    for (long long c = 0; c < hc; ++c)
1078        for (long long d = 0; d < n_embd; ++d) {
1079            const size_t i = (size_t) (c * n_embd + d);
1080            const double want = (double) R[i] + (double) block_out[(size_t) d];
1081            worst_plain = std::fmax(worst_plain, rel_terms(want, (double) got_write[i], (double) R[i],
1082                                                           (double) block_out[(size_t) d]));
1083        }
1084    const bool plain = worst_plain < 1e-6;
1085    std::printf("  %-40s %s (worst rel %.3e)\n", "zero injection -> plain residual add",
1086                plain ? "yes" : "*** NO ***", worst_plain);
1087    if (!plain) ++bad;
1088
1089    // the rival reading: sigmoid without the 2 halves the update, and must be visible.
1090    //
1091    // The comparison is on the DELTA `out - R`, not on `out`.  The claim is about the gate WEIGHT, and `R`
1092    // now reaches 64 in the last stream, so measuring `R + block_out*w` against the wrong reading dilutes a
1093    // 100% error in `w` down to 2.27% - which is how this check first passed as "not observable" while being
1094    // perfectly observable.  Measure the quantity the claim is about.
1095    {
1096        std::vector<float> got_delta((size_t) hc_dim), want_delta((size_t) hc_dim), wrong_delta((size_t) hc_dim);
1097        for (long long c = 0; c < hc; ++c)
1098            for (long long d = 0; d < n_embd; ++d) {
1099                const size_t i = (size_t) (c * n_embd + d);
1100                got_delta[i] = (float) ((double) got_write[i] - (double) R[i]);
1101                want_delta[i] = block_out[(size_t) d];        // 2*sigmoid(0) = 1.0
1102                wrong_delta[i] = block_out[(size_t) d] * 0.5f; // 1*sigmoid(0) = 0.5
1103            }
1104        const double rel = rel_diff(want_delta, wrong_delta);
1105        const double rel_got = rel_diff(want_delta, got_delta);
1106        const bool visible = rel > 0.05 && rel_got < 0.05;
1107        std::printf("  %-40s %s (readings %.0f%% apart, kernel within %.2e)\n",
1108                    "1*sigmoid vs 2*sigmoid is observable", visible ? "yes" : "*** NO ***", rel * 100, rel_got);
1109        if (!visible) ++bad;
1110    }
1111
1112    // a non-zero injection: every stream receives the SAME block output, differing only by weight
1113    std::vector<float> inj((size_t) hc);
1114    for (auto& x : inj) x = gauss(rng) * 3.0f;
1115    /*
1116    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
1117    the original code the source host memory is pageable memory. If the memory
1118    is not pageable, call wait() on event return by memcpy API to ensure
1119    synchronization behavior.
1120    */
1121    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1122              d_zi, inj.data(), inj.size() * sizeof(float)).wait()),
1123          "c inj2");
1124    strata::kernels::gr_write(d_Rw, d_bo, d_zi, sh, d_outw, nullptr);
1125    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1126                               .memcpy(got_write.data(), d_outw,
1127                                       got_write.size() * sizeof(float))
1128                               .wait()),
1129          "c outw2");
1130    double worst_stream = 0;
1131    for (long long c = 0; c < hc; ++c) {
1132        const double w = 2.0 / (1.0 + std::exp(-(double) inj[(size_t) c] / (double) hc));
1133        for (long long d = 0; d < n_embd; ++d) {
1134            const size_t i = (size_t) (c * n_embd + d);
1135            const double want = (double) R[i] + (double) block_out[(size_t) d] * w;
1136            worst_stream = std::fmax(worst_stream, rel_terms(want, (double) got_write[i], (double) R[i],
1137                                                             (double) block_out[(size_t) d] * w));
1138        }
1139    }
1140    const bool streams_ok = worst_stream < 1e-6;
1141    std::printf("  %-40s %s (worst rel %.3e)\n", "every stream adds the same block output",
1142                streams_ok ? "yes" : "*** NO ***", worst_stream);
1143    if (!streams_ok) ++bad;
1144
1145    // ---- THE REAL DIMENSIONS. Exercise all activation/projection variants at n_embd=2560, hc=4, hc_lr=320.
1146    // Workspace sizing and every full weight row must agree with the model geometry.
1147    {
1148        const long long rn = strata::core::kCompiledGeometry.n_embd, rhc = strata::core::kCompiledGeometry.hc, rlr = strata::core::kCompiledGeometry.hc_lr, rdim = rhc * rn;   // the compiled shape
1149        std::mt19937 rrng(99);
1150        std::normal_distribution<float> rg(0.0f, 1.0f);
1151        auto rbf16 = [&](size_t n, float sigma) {
1152            std::vector<float> v(n);
1153            for (auto& x : v) x = to_bf16(rg(rrng) * sigma);
1154            return v;
1155        };
1156        std::vector<float> rR((size_t) rdim);
1157        for (auto& x : rR) x = rg(rrng);
1158        for (long long c = 0; c < rhc; ++c)
1159            for (long long d = 0; d < rn; ++d) rR[(size_t) (c * rn + d)] *= std::pow(4.0f, (float) c);
1160        std::vector<float> rnorm((size_t) rdim);
1161        for (auto& x : rnorm) x = 1.0f + 0.1f * rg(rrng);
1162        std::vector<float> rdown = rbf16((size_t) (rlr * rdim), 0.2f);
1163        std::vector<float> rup = rbf16((size_t) (rdim * rlr), 0.2f);
1164        std::vector<float> rinj = rbf16((size_t) (rhc * rdim), 0.05f);
1165
1166        std::vector<uint16_t> qd(rdown.size()), qu(rup.size()), qi(rinj.size());
1167        for (size_t i = 0; i < rdown.size(); ++i) qd[i] = bf16_bits(rdown[i]);
1168        for (size_t i = 0; i < rup.size(); ++i) qu[i] = bf16_bits(rup[i]);
1169        for (size_t i = 0; i < rinj.size(); ++i) qi[i] = bf16_bits(rinj[i]);
1170
1171        float *dR = nullptr, *dN = nullptr, *dM = nullptr, *dI = nullptr;
1172        uint16_t *dD = nullptr, *dU = nullptr, *dJ = nullptr;
1173        check(DPCT_CHECK_ERROR(dR = (float *)sycl::malloc_device(
1174                                   rR.size() * 4, dpct::get_in_order_queue())),
1175              "rR");
1176        check(
1177            DPCT_CHECK_ERROR(dN = (float *)sycl::malloc_device(
1178                                 rnorm.size() * 4, dpct::get_in_order_queue())),
1179            "rN");
1180        check(DPCT_CHECK_ERROR(dD = (uint16_t *)sycl::malloc_device(
1181                                   qd.size() * 2, dpct::get_in_order_queue())),
1182              "rD");
1183        check(DPCT_CHECK_ERROR(dU = (uint16_t *)sycl::malloc_device(
1184                                   qu.size() * 2, dpct::get_in_order_queue())),
1185              "rU");
1186        check(DPCT_CHECK_ERROR(dJ = (uint16_t *)sycl::malloc_device(
1187                                   qi.size() * 2, dpct::get_in_order_queue())),
1188              "rJ");
1189        check(DPCT_CHECK_ERROR(dM = (float *)sycl::malloc_device(
1190                                   (size_t)rn * 4, dpct::get_in_order_queue())),
1191              "rM");
1192        check(
1193            DPCT_CHECK_ERROR(dI = (float *)sycl::malloc_device(
1194                                 (size_t)rhc * 4, dpct::get_in_order_queue())),
1195            "rI");
1196        /*
1197        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1198        assuming in the original code the source host memory is pageable memory.
1199        If the memory is not pageable, call wait() on event return by memcpy API
1200        to ensure synchronization behavior.
1201        */
1202        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1203                  dR, rR.data(), rR.size() * 4).wait()),
1204              "crR");
1205        /*
1206        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1207        assuming in the original code the source host memory is pageable memory.
1208        If the memory is not pageable, call wait() on event return by memcpy API
1209        to ensure synchronization behavior.
1210        */
1211        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1212                  dN, rnorm.data(), rnorm.size() * 4).wait()),
1213              "crN");
1214        /*
1215        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1216        assuming in the original code the source host memory is pageable memory.
1217        If the memory is not pageable, call wait() on event return by memcpy API
1218        to ensure synchronization behavior.
1219        */
1220        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1221                  dD, qd.data(), qd.size() * 2).wait()),
1222              "crD");
1223        /*
1224        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1225        assuming in the original code the source host memory is pageable memory.
1226        If the memory is not pageable, call wait() on event return by memcpy API
1227        to ensure synchronization behavior.
1228        */
1229        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1230                  dU, qu.data(), qu.size() * 2).wait()),
1231              "crU");
1232        /*
1233        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1234        assuming in the original code the source host memory is pageable memory.
1235        If the memory is not pageable, call wait() on event return by memcpy API
1236        to ensure synchronization behavior.
1237        */
1238        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1239                  dJ, qi.data(), qi.size() * 2).wait()),
1240              "crJ");
1241
1242        const strata::kernels::GrShapes rsh{rn, rhc, rlr};
1243        void* rws_raw = nullptr;
1244        check(DPCT_CHECK_ERROR(rws_raw = (void *)sycl::malloc_device(
1245                                   strata::kernels::gr_workspace_bytes(rsh),
1246                                   dpct::get_in_order_queue())),
1247              "m rws");
1248        strata::kernels::GrWorkspace rws;
1249        strata::kernels::gr_workspace_init(rsh, rws_raw, rws);
1250        for (int mode = 0; mode < 3; ++mode) {
1251            select_activation_mode(mode);
1252            strata::kernels::gr_read(dR, dN, dD, dU, dJ, eps, rsh, rws, dM, dI, nullptr);
1253            std::vector<float> gm((size_t) rn), gi((size_t) rhc);
1254            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1255                                       .memcpy(gm.data(), dM, gm.size() * 4)
1256                                       .wait()),
1257                  "cgm");
1258            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1259                                       .memcpy(gi.data(), dI, gi.size() * 4)
1260                                       .wait()),
1261                  "cgi");
1262
1263            Opts precision;
1264            precision.round_activation = mode == 0;
1265            std::vector<float> wm, wi;
1266            reference(rR, rnorm, rdown, rup, rinj, eps, rn, rhc, rlr, precision, wm, wi);
1267            const double rm = rel_diff(wm, gm), ri = rel_diff(wi, gi);
1268            const bool ok = rm <= 1e-4 && ri <= 1e-4;
1269            std::printf("\n  real dims %lld/%lld/%lld %s %s (mixed %.3e, inject %.3e)\n",
1270                        rn, rhc, rlr, activation_mode_name(mode), ok ? "pass" : "*** FAIL ***", rm, ri);
1271            if (!ok) ++bad;
1272        }
1273        bad += fused_multi_lds_parity(dN, dD, dU, dJ, eps);
1274        select_activation_mode(0);
1275        sycl::free(rws_raw, dpct::get_in_order_queue());
1276        sycl::free(dR, dpct::get_in_order_queue());
1277            sycl::free(dN, dpct::get_in_order_queue());
1278            sycl::free(dD, dpct::get_in_order_queue());
1279            sycl::free(dU, dpct::get_in_order_queue());
1280            sycl::free(dJ, dpct::get_in_order_queue());
1281            sycl::free(dM, dpct::get_in_order_queue());
1282            sycl::free(dI, dpct::get_in_order_queue());
1283    }
1284
1285    bad += scalar_activation_contract();
1286    std::printf("\ngr_read/gr_write: %d failures\n", bad);
1287    if (bad) return 1;
1288    if (selftest) std::printf("gr_parity OK\n");
1289    return 0;
1290}