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
54.3 KiB986 linesraw
1// src/kernels/gdn_parity.cpp - P2.S2's test for the GDN recurrence, the conv and the two norms.
2//
3// `ref/gdn.py` carries eleven PROPERTY checks, several of which exist because a rival reading of the SOURCE
4// produces well-formed output.  The four that the kernels here can be wrong about are re-pinned below, each
5// asserted OBSERVABLE against a deliberately-wrong computation before the kernel is judged:
6//
7//   1. MODULO head pairing, h % h_k, not INTERLEAVE.  With H_k=2 and H_v=4 the two give [0,1,0,1] and
8//      [0,0,1,1]: they differ at h=1 and h=2.  Both produce a full-rank state of the right shape.
9//   2. Decay applied BEFORE the rank-1 update.  Applying it after is a one-line move that keeps every shape
10//      and every magnitude.
11//   3. The conv's SLIDE DIRECTION.  `kernel[0]` must read the OLDEST state row and the new input must land in
12//      the LAST state row; reversing either is invisible on a symmetric state, so the state rows here are
13//      labelled so each position is identifiable.
14//   4. `l2_norm`'s `+ eps` is an absolute floor on the SQUARED NORM, not on the mean.  The mean reading
15//      differs by sqrt(S) = 11.3x at S = 128.  `ref/gdn.py` PROPERTY 1 instruments the derivation, so it is
16//      not taken on trust there either.
17//
18// It also checks the STATE LAYOUT, which is the one place these kernels intentionally differ from the
19// reference: (S, h_v, S) with j fastest instead of (S, S, h_v).  A layout mix-up is silent, so the state is
20// filled with a value that encodes its own coordinates.
21#define DPCT_PROFILING_ENABLED
22#include <sycl/sycl.hpp>
23#include <dpct/dpct.hpp>
24#include "strata/kernels/gdn.hpp"
25#include "strata/kernels/fused_gdn.hpp"
26#include "strata/kernels/verify_kernels.hpp"
27#include "strata/core/geometry.hpp"
28
29#include "strata/prefill/kernels.hpp"
30
31#include <algorithm>
32#include <chrono>
33#include <cmath>
34#include <cstdio>
35#include <cstdlib>
36#include <cstring>
37#include <random>
38#include <string>
39#include <vector>
40
41namespace {
42
43void check(dpct::err0 e, const char *what) {
44}
45
46float sigmoid_f(float x) { return 1.0f / (1.0f + std::exp(-x)); }
47
48/// The reference's `gdn_step`, with switches for the rival readings.
49///
50/// `state` is passed in the REFERENCE layout (S, S, h_v) - i.e. (i, j, h) - so that this function is a
51/// transcription of `ref/gdn.py` and not of the kernel.
52void ref_step(std::vector<double>& state, const std::vector<float>& q, const std::vector<float>& k,
53              const std::vector<float>& v, const std::vector<float>& gate, const std::vector<float>& beta,
54              int S, int h_k, int h_v, std::vector<float>& o, bool modulo_heads, bool decay_first) {
55    auto at = [&](int i, int j, int h) -> double& { return state[(size_t) (i * S + j) * h_v + h]; };
56    std::vector<float> oo((size_t) h_v * S, 0.0f);
57    for (int h = 0; h < h_v; ++h) {
58        const int src = modulo_heads ? (h % h_k) : (h / (h_v / h_k));
59        const double dec = std::exp((double) gate[(size_t) h]);
60        const double b = (double) beta[(size_t) h];
61        for (int j = 0; j < S; ++j) {
62            if (decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec;
63            double sk = 0;
64            for (int i = 0; i < S; ++i) sk += at(i, j, h) * (double) k[(size_t) (src * S + i)];
65            const double d = ((double) v[(size_t) (h * S + j)] - sk) * b;
66            for (int i = 0; i < S; ++i) at(i, j, h) += (double) k[(size_t) (src * S + i)] * d;
67            if (!decay_first) for (int i = 0; i < S; ++i) at(i, j, h) *= dec;
68            double dot = 0;
69            for (int i = 0; i < S; ++i) dot += at(i, j, h) * (double) q[(size_t) (src * S + i)];
70            oo[(size_t) (h * S + j)] = (float) dot;
71        }
72    }
73    o = oo;
74}
75
76/// `ref/gdn.py::conv_step` in its own (d_conv, C) row-major orientation.
77void ref_conv(std::vector<float>& cs, const std::vector<float>& x, const std::vector<float>& kern, int C,
78              int dc, std::vector<float>& out) {
79    out.assign((size_t) C, 0.0f);
80    for (int c = 0; c < C; ++c) {
81        double acc = 0;
82        for (int i = 0; i < dc - 1; ++i) acc += (double) cs[(size_t) (i * C + c)] * (double) kern[(size_t) (i * C + c)];
83        acc += (double) x[(size_t) c] * (double) kern[(size_t) ((dc - 1) * C + c)];
84        out[(size_t) c] = (float) acc;
85        for (int i = 0; i < dc - 2; ++i) cs[(size_t) (i * C + c)] = cs[(size_t) ((i + 1) * C + c)];
86        cs[(size_t) ((dc - 2) * C + c)] = x[(size_t) c];
87    }
88}
89
90double rel_l1(const std::vector<float>& a, const std::vector<float>& b) {
91    double d = 0, m = 0;
92    for (size_t i = 0; i < a.size(); ++i) {
93        d += std::fabs((double) a[i] - (double) b[i]);
94        m += std::fabs((double) a[i]);
95    }
96    return d / (m > 1e-30 ? m : 1e-30);
97}
98
99// Compare every state element and every token/head output, including FP16 bits.
100// Fixtures have nonzero initial state, modulo-paired heads, signed q/k/v, and
101// both shallow and deep decay. A tolerance is diagnostic only, never a pass.
102int prefill_case(int T, int seed, int repeats) {
103    constexpr int S = strata::core::kCompiledGeometry.ssm_state_size, HK = strata::core::kCompiledGeometry.ssm_k_heads, HV = strata::core::kCompiledGeometry.ssm_v_heads, C = strata::core::kCompiledGeometry.ssm_conv_channels;   // the compiled shape
104    sycl::queue q(dpct::get_in_order_queue().get_device(),
105                  sycl::property_list{sycl::property::queue::in_order{}});
106    // Variant 6 runs on Intel GPUs only (the engine throws elsewhere): skip, not fail, on any other device.
107    const auto dev = q.get_device();
108    const auto sizes = dev.get_info<sycl::info::device::sub_group_sizes>();
109    if (!dev.is_gpu() || dev.get_info<sycl::info::device::vendor_id>() != 0x8086 ||
110        std::find(sizes.begin(), sizes.end(), size_t(32)) == sizes.end() ||
111        std::find(sizes.begin(), sizes.end(), size_t(16)) == sizes.end()) {
112        static bool said = false;
113        if (!said) std::printf("prefill gdn: skipped (needs an Intel GPU with sub-groups 16 and 32)\n");
114        said = true;
115        return 0;
116    }
117    std::mt19937 rng(seed);
118    std::normal_distribution<float> gauss(0.0f, 1.0f);
119    std::vector<float> st(size_t(S) * HV * S), h(size_t(T) * C),
120        gate(size_t(T) * HV), beta(gate.size()), z(size_t(T) * HV * S), gamma(S);
121    for (auto& x : st) x = gauss(rng) * 0.03f;
122    for (int t = 0; t < T; ++t) {
123        for (int j = 0; j < C; ++j) h[size_t(t) * C + j] = gauss(rng) * (j < 2 * HK * S ? 0.08f : 0.7f);
124    }
125    for (auto& x : gate) x = -(seed % 2 ? 0.02f : 2.0f) * (1.0f + std::fabs(gauss(rng)));
126    for (auto& x : beta) x = 0.1f + float(rng() % 800) / 1000.0f;
127    for (auto& x : z) x = gauss(rng);
128    for (auto& x : gamma) x = 1.0f + 0.2f * gauss(rng);
129    auto copy = [&](const std::vector<float>& src) {
130        auto* ptr = sycl::malloc_device<float>(src.size(), q);
131        if (!ptr) throw std::bad_alloc();
132        q.memcpy(ptr, src.data(), src.size() * sizeof(float)).wait_and_throw();
133        return ptr;
134    };
135    float *dst = copy(st), *dh = copy(h), *dg = copy(gate), *db = copy(beta), *dz = copy(z), *dgm = copy(gamma);
136    float* dy = sycl::malloc_device<float>(z.size(), q);
137    uint16_t* dy16 = sycl::malloc_device<uint16_t>(z.size(), q);
138    if (!dy || !dy16) throw std::bad_alloc();
139    std::vector<float> refst(st.size()), refy(z.size()), gotst(st.size()), goty(z.size());
140    std::vector<uint16_t> ref16(z.size()), got16(z.size());
141    auto run = [&](int variant, std::vector<float>& ost, std::vector<float>& oy, std::vector<uint16_t>& o16) {
142        // Warm up the compiled kernel before measuring; every run resets state.
143        q.memcpy(dst, st.data(), st.size() * sizeof(float)).wait_and_throw();
144        if (variant == -1)
145            strata::prefill::gdn_recurrence(dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, &q);
146        else
147            strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm,
148                                                   1e-6f, dy, dy16, T, &q);
149        q.wait_and_throw();
150        double elapsed = 0;
151        for (int i = 0; i < repeats; ++i) {
152            q.memcpy(dst, st.data(), st.size() * sizeof(float)).wait_and_throw();
153            const auto start = std::chrono::steady_clock::now();
154            if (variant == -1)
155                strata::prefill::gdn_recurrence(dst, dh, dg, db, dz, dgm, 1e-6f, dy, dy16, T, &q);
156            else
157                strata::prefill::gdn_recurrence_variant(variant, dst, dh, dg, db, dz, dgm,
158                                                       1e-6f, dy, dy16, T, &q);
159            q.wait_and_throw();
160            elapsed += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
161        }
162        q.memcpy(ost.data(), dst, ost.size() * sizeof(float)).wait_and_throw();
163        q.memcpy(oy.data(), dy, oy.size() * sizeof(float)).wait_and_throw();
164        q.memcpy(o16.data(), dy16, o16.size() * sizeof(uint16_t)).wait_and_throw();
165        return elapsed / repeats;
166    };
167    const double base_ms = run(0, refst, refy, ref16);
168    const double xe_ms = run(6, gotst, goty, got16);
169    size_t state_bad = 0, y_bad = 0, half_bad = 0;
170    double max_abs = 0, max_rel = 0;
171    auto compare = [&](const std::vector<float>& a, const std::vector<float>& b, size_t& mismatches) {
172        for (size_t i = 0; i < a.size(); ++i) {
173            if (!std::isfinite(a[i]) || !std::isfinite(b[i]) ||
174                std::memcmp(&a[i], &b[i], sizeof(float)) != 0) ++mismatches;
175            const double diff = std::fabs(double(a[i]) - b[i]);
176            max_abs = std::max(max_abs, diff);
177            max_rel = std::max(max_rel, diff / std::max(std::fabs(double(a[i])), 1e-20));
178        }
179    };
180    compare(refst, gotst, state_bad);
181    compare(refy, goty, y_bad);
182    for (size_t i = 0; i < ref16.size(); ++i) half_bad += ref16[i] != got16[i];
183    std::printf("prefill T=%d seed=%d heads=%d: state=%zu y=%zu fp16=%zu mismatches; max_abs=%.9g max_rel=%.9g; baseline=%.3f ms xe=%.3f ms\n",
184                T, seed, HV, state_bad, y_bad, half_bad, max_abs, max_rel, base_ms, xe_ms);
185    // T=7 additionally checks the production entry point (variant 6 on Alchemist or under STRATA_GDN_XE=1,
186    // else variant 0) and T=0's no-op contract.
187    int extra_bad = 0;
188    if (T == 7) {
189        run(-1, gotst, goty, got16);
190        // Both variants must match anyway; compare production to baseline.
191        extra_bad += std::memcmp(refst.data(), gotst.data(), refst.size() * sizeof(float)) != 0;
192        extra_bad += std::memcmp(refy.data(), goty.data(), refy.size() * sizeof(float)) != 0;
193        extra_bad += ref16 != got16;
194        q.memcpy(dst, st.data(), st.size() * sizeof(float)).wait_and_throw();
195        strata::prefill::gdn_recurrence_variant(6, dst, dh, dg, db, dz, dgm,
196                                               1e-6f, dy, dy16, 0, &q);
197        q.memcpy(gotst.data(), dst, st.size() * sizeof(float)).wait_and_throw();
198        extra_bad += gotst != st;
199        const auto saved_y = goty;
200        const auto saved16 = got16;
201        q.memcpy(goty.data(), dy, goty.size() * sizeof(float)).wait_and_throw();
202        q.memcpy(got16.data(), dy16, got16.size() * sizeof(uint16_t)).wait_and_throw();
203        extra_bad += goty != saved_y || got16 != saved16;
204        std::printf("prefill production + T=0: %s\n", extra_bad ? "FAIL" : "OK");
205    }
206    for (auto ptr : {dst, dh, dg, db, dz, dgm, dy}) sycl::free(ptr, q);
207    sycl::free(dy16, q);
208    return state_bad || y_bad || half_bad || extra_bad ? 1 : 0;
209}
210
211}  // namespace
212
213int main(int argc, char** argv) {
214    bool selftest = false, prefill_only = false;
215    int prefill_tokens = 0, prefill_repeat = 1;
216    for (int i = 1; i < argc; ++i) {
217        const std::string arg(argv[i]);
218        if (arg == "--selftest") selftest = true;
219        else if (arg == "--prefill-only") prefill_only = true;
220        else if ((arg == "--prefill-tokens" || arg == "--prefill-repeat") && i + 1 < argc) {
221            char* end = nullptr;
222            const long n = std::strtol(argv[++i], &end, 10);
223            if (!end || *end || n < 1 || n > (arg == "--prefill-tokens" ? 32768 : 1000)) return 2;
224            (arg == "--prefill-tokens" ? prefill_tokens : prefill_repeat) = int(n);
225        } else {
226            std::fprintf(stderr, "usage: gdn_parity [--selftest] [--prefill-only] [--prefill-tokens N] [--prefill-repeat N]\n");
227            return 2;
228        }
229    }
230    const auto device = dpct::get_in_order_queue().get_device();
231    std::printf("device: %s (%s), sub-groups:", device.get_info<sycl::info::device::name>().c_str(),
232                device.is_cpu() ? "CPU" : device.is_gpu() ? "GPU" : "other");
233    for (auto n : device.get_info<sycl::info::device::sub_group_sizes>()) std::printf(" %zu", n);
234    std::printf("\n");
235    int prefill_bad = 0;
236    for (int t : prefill_tokens ? std::vector<int>{prefill_tokens} : std::vector<int>{1, 7, 256, 1000})
237        for (int seed : {2025, 2026}) prefill_bad += prefill_case(t, seed, prefill_repeat);
238    std::printf("prefill gdn: %d failures\n", prefill_bad);
239    if (prefill_only) {
240        if (selftest && !prefill_bad) std::printf("gdn_parity OK\n");
241        return prefill_bad ? 1 : 0;
242    }
243
244    const int S = strata::core::kCompiledGeometry.ssm_state_size, h_k = strata::core::kCompiledGeometry.ssm_k_heads, h_v = strata::core::kCompiledGeometry.ssm_v_heads;      // the compiled shape (Flash-Next: the artifact's 128 / 16 / 48)
245    std::mt19937 rng(2024);
246    std::normal_distribution<float> gauss(0.0f, 1.0f);
247    int bad = prefill_bad;
248
249    // ================= 1. the recurrence =================
250    {
251        // The state encodes its own coordinates, so a layout mix-up cannot pass: reading (i,j,h) where the
252        // buffer holds (i,h,j) gives a DIFFERENT number, not a wrong-but-plausible one.
253        std::vector<double> st_ref((size_t) S * S * h_v);
254        std::vector<float> st_dev((size_t) S * h_v * S);
255        for (int i = 0; i < S; ++i)
256            for (int j = 0; j < S; ++j)
257                for (int h = 0; h < h_v; ++h) {
258                    const float val = (float) (0.001 * (i + 2 * j + 3 * h) - 1.0);
259                    st_ref[(size_t) (i * S + j) * h_v + h] = val;
260                    st_dev[(size_t) (i * h_v + h) * S + j] = val;   // (S, h_v, S), j fastest
261                }
262
263        std::vector<float> q((size_t) h_k * S), k((size_t) h_k * S), v((size_t) h_v * S), gate((size_t) h_v),
264            beta((size_t) h_v);
265        for (auto& x : q) x = gauss(rng) * 0.1f;
266        for (auto& x : k) x = gauss(rng) * 0.1f;
267        for (auto& x : v) x = gauss(rng);
268        for (auto& x : gate) x = -(2.0f + 4.0f * (float) (rng() % 100) / 100.0f);   // dec in (0.0025, 0.135]
269        for (auto& x : beta) x = (float) (rng() % 100) / 100.0f;
270
271        std::vector<float> want_o;
272        std::vector<double> st_mod = st_ref;
273        ref_step(st_mod, q, k, v, gate, beta, S, h_k, h_v, want_o, true, true);
274
275        // the traps
276        {
277            std::vector<double> a = st_ref;
278            std::vector<float> oo;
279            ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, false, true);
280            const double rel = rel_l1(want_o, oo);
281            std::printf("  %-42s %-4s (%.2f%% apart)\n", "modulo vs interleave head pairing",
282                        rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
283            if (!(rel > 0.05)) ++bad;
284        }
285        {
286            std::vector<double> a = st_ref;
287            std::vector<float> oo;
288            ref_step(a, q, k, v, gate, beta, S, h_k, h_v, oo, true, false);
289            const double rel = rel_l1(want_o, oo);
290            std::printf("  %-42s %-4s (%.2f%% apart)\n", "decay before vs after the update",
291                        rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
292            // The two readings differ by exactly `k (x) (beta * v * (1 - dec))`, so the fixture is only able
293            // to see the trap when `dec` is far from 1 and `beta` is far from 0.  The first version used
294            // gate in [-0.99, 0] - dec in [0.37, 1] - and managed 3.25%, which is a threshold the wrong
295            // reading nearly clears.  Deep decay is also the realistic regime: `ssm_a = -exp(A_log) < 0` and
296            // softplus is positive, so gate is comfortably negative in the real model.
297            if (!(rel > 0.05)) ++bad;
298        }
299
300        // the kernel
301        float *d_st = nullptr, *d_q = nullptr, *d_k = nullptr, *d_v = nullptr, *d_g = nullptr, *d_b = nullptr,
302              *d_o = nullptr;
303        check(DPCT_CHECK_ERROR(
304                  d_st = (float *)sycl::malloc_device(
305                      st_dev.size() * 4, dpct::get_in_order_queue())),
306              "st");
307        check(DPCT_CHECK_ERROR(d_q = (float *)sycl::malloc_device(
308                                   q.size() * 4, dpct::get_in_order_queue())),
309              "q");
310        check(DPCT_CHECK_ERROR(d_k = (float *)sycl::malloc_device(
311                                   k.size() * 4, dpct::get_in_order_queue())),
312              "k");
313        check(DPCT_CHECK_ERROR(d_v = (float *)sycl::malloc_device(
314                                   v.size() * 4, dpct::get_in_order_queue())),
315              "v");
316        check(
317            DPCT_CHECK_ERROR(d_g = (float *)sycl::malloc_device(
318                                 gate.size() * 4, dpct::get_in_order_queue())),
319            "g");
320        check(
321            DPCT_CHECK_ERROR(d_b = (float *)sycl::malloc_device(
322                                 beta.size() * 4, dpct::get_in_order_queue())),
323            "b");
324        check(DPCT_CHECK_ERROR(
325                  d_o = (float *)sycl::malloc_device(
326                      (size_t)h_v * S * 4, dpct::get_in_order_queue())),
327              "o");
328        /*
329        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
330        assuming in the original code the source host memory is pageable memory.
331        If the memory is not pageable, call wait() on event return by memcpy API
332        to ensure synchronization behavior.
333        */
334        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
335                  d_st, st_dev.data(), st_dev.size() * 4).wait()),
336              "cst");
337        /*
338        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
339        assuming in the original code the source host memory is pageable memory.
340        If the memory is not pageable, call wait() on event return by memcpy API
341        to ensure synchronization behavior.
342        */
343        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_q, q.data(),
344                                                                 q.size() * 4).wait()),
345              "cq");
346        /*
347        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
348        assuming in the original code the source host memory is pageable memory.
349        If the memory is not pageable, call wait() on event return by memcpy API
350        to ensure synchronization behavior.
351        */
352        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_k, k.data(),
353                                                                 k.size() * 4).wait()),
354              "ck");
355        /*
356        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
357        assuming in the original code the source host memory is pageable memory.
358        If the memory is not pageable, call wait() on event return by memcpy API
359        to ensure synchronization behavior.
360        */
361        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_v, v.data(),
362                                                                 v.size() * 4).wait()),
363              "cv");
364        /*
365        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
366        assuming in the original code the source host memory is pageable memory.
367        If the memory is not pageable, call wait() on event return by memcpy API
368        to ensure synchronization behavior.
369        */
370        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
371                  d_g, gate.data(), gate.size() * 4).wait()),
372              "cg");
373        /*
374        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
375        assuming in the original code the source host memory is pageable memory.
376        If the memory is not pageable, call wait() on event return by memcpy API
377        to ensure synchronization behavior.
378        */
379        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
380                  d_b, beta.data(), beta.size() * 4).wait()),
381              "cb");
382
383        strata::kernels::GdnShapes sh{S, h_k, h_v};
384        strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
385
386        std::vector<float> got_o((size_t) h_v * S), got_st(st_dev.size());
387        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
388                                   .memcpy(got_o.data(), d_o, got_o.size() * 4)
389                                   .wait()),
390              "cgo");
391        check(
392            DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
393                                 .memcpy(got_st.data(), d_st, got_st.size() * 4)
394                                 .wait()),
395            "cgst");
396
397        // o, and the STATE read back through the declared layout
398        const double rel_o = rel_l1(want_o, got_o);
399        double rel_st = 0, mag_st = 0;
400        for (int i = 0; i < S; ++i)
401            for (int j = 0; j < S; ++j)
402                for (int h = 0; h < h_v; ++h) {
403                    const size_t dev = (size_t) (i * h_v + h) * S + j;
404                    const double w = st_mod[(size_t) (i * S + j) * h_v + h];
405                    rel_st += std::fabs(w - (double) got_st[dev]);
406                    mag_st += std::fabs(w);
407                }
408        rel_st /= (mag_st > 1e-30 ? mag_st : 1e-30);
409        std::printf("\n  %-42s rel %.3e\n", "o vs reference", rel_o);
410        std::printf("  %-42s rel %.3e\n", "state (read via (S,h_v,S)) vs reference", rel_st);
411        // The kernel accumulates in f32 and the reference in f64, and the state is a RECURRENCE over 128
412        // terms, so 1e-5 is the arithmetic's floor here and not a structural allowance.
413        if (!(rel_o <= 1e-5)) { std::printf("    *** o over 1e-5 ***\n"); ++bad; }
414        if (!(rel_st <= 1e-5)) { std::printf("    *** state over 1e-5 ***\n"); ++bad; }
415
416        // a zero state stays zero, and a zero gate/beta leaves the state untouched (the reference's
417        // PROPERTY 4 setup) - a cheap independent invariant that no layout can fake
418        {
419            std::vector<float> zero(st_dev.size(), 0.0f), zg((size_t) h_v, 0.0f), zb((size_t) h_v, 0.0f);
420            /*
421            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
422            assuming in the original code the source host memory is pageable
423            memory. If the memory is not pageable, call wait() on event return
424            by memcpy API to ensure synchronization behavior.
425            */
426            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
427                      d_st, zero.data(), zero.size() * 4).wait()),
428                  "z0");
429            /*
430            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
431            assuming in the original code the source host memory is pageable
432            memory. If the memory is not pageable, call wait() on event return
433            by memcpy API to ensure synchronization behavior.
434            */
435            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
436                      d_g, zg.data(), zg.size() * 4).wait()),
437                  "z1");
438            /*
439            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
440            assuming in the original code the source host memory is pageable
441            memory. If the memory is not pageable, call wait() on event return
442            by memcpy API to ensure synchronization behavior.
443            */
444            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
445                      d_b, zb.data(), zb.size() * 4).wait()),
446                  "z2");
447            strata::kernels::gdn_step(d_st, d_q, d_k, d_v, d_g, d_b, d_o, sh, nullptr);
448            std::vector<float> zz(zero.size());
449            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
450                                       .memcpy(zz.data(), d_st, zz.size() * 4)
451                                       .wait()),
452                  "z3");
453            double nz = 0;
454            for (float x : zz) nz += std::fabs(x);
455            const bool ok = nz == 0.0;
456            std::printf("  %-42s %s\n", "gate=beta=0 from a zero state is a no-op", ok ? "yes" : "*** NO ***");
457            if (!ok) ++bad;
458        }
459
460        // ephemeral state: unchanged when the state is untouched but beta=1 — the delta rule writing k*d
461        sycl::free(d_st, dpct::get_in_order_queue());
462            sycl::free(d_q, dpct::get_in_order_queue());
463            sycl::free(d_k, dpct::get_in_order_queue());
464            sycl::free(d_v, dpct::get_in_order_queue());
465            sycl::free(d_g, dpct::get_in_order_queue());
466            sycl::free(d_b, dpct::get_in_order_queue());
467            sycl::free(d_o, dpct::get_in_order_queue());
468    }
469
470    // ================= 2. the conv =================
471    {
472        const int C = 24, dc = 4;      // small, so the host reference is a plain loop
473        // TWO DIFFERENT LAYOUTS MEET HERE, and this is where the first version of this test failed at 0.136.
474        // `ref/gdn.py` carries the conv state as (d_conv-1, C) ROW-MAJOR - (i, c) at i*C + c - because it is
475        // numpy.  The kernel carries it as (C, d_conv-1) with c fastest - c*(dc-1) + i - because that is
476        // ggml's `ne = {d_conv-1, C}` with ne0 fast, and it is a runtime buffer so either is legal.  The
477        // mapping between them is written out below rather than assumed, in both directions.
478        std::vector<float> cs_ref((size_t) (dc - 1) * C), x((size_t) C), kern((size_t) dc * C);
479        for (int i = 0; i < dc - 1; ++i)
480            for (int c = 0; c < C; ++c) cs_ref[(size_t) (i * C + c)] = (float) (10 * (i + 1) + c);  // labelled
481        for (int c = 0; c < C; ++c) x[(size_t) c] = (float) (100 + c);
482        for (size_t i = 0; i < kern.size(); ++i) kern[i] = gauss(rng);
483
484        auto to_dev_layout = [&](const std::vector<float>& r) {
485            std::vector<float> d(r.size());
486            for (int i = 0; i < dc - 1; ++i)
487                for (int c = 0; c < C; ++c) d[(size_t) (c * (dc - 1) + i)] = r[(size_t) (i * C + c)];
488            return d;
489        };
490        auto to_ref_layout = [&](const std::vector<float>& d) {
491            std::vector<float> r(d.size());
492            for (int i = 0; i < dc - 1; ++i)
493                for (int c = 0; c < C; ++c) r[(size_t) (i * C + c)] = d[(size_t) (c * (dc - 1) + i)];
494            return r;
495        };
496
497        std::vector<float> cs = to_dev_layout(cs_ref);
498        std::vector<float> want;
499        std::vector<float> cs_want_ref = cs_ref;
500        ref_conv(cs_want_ref, x, kern, C, dc, want);
501        const std::vector<float> cs_want = to_dev_layout(cs_want_ref);
502
503        // THE LAYOUT: the manifest's `ssm_conv1d.weight` has ne = [d_conv, C], so ne0 = d_conv is fast.
504        // The kernel takes `kW[c*dc + i]`; the reference's `kern` is (dc, C) row-major.  The transcription
505        // below is the ONLY place the two meet.
506        std::vector<float> kW((size_t) C * dc);
507        for (int c = 0; c < C; ++c)
508            for (int i = 0; i < dc; ++i) kW[(size_t) (c * dc + i)] = kern[(size_t) (i * C + c)];
509        // and the rival reading, which must differ or the fixture cannot see a transposed weight
510        std::vector<float> kW_wrong((size_t) C * dc);
511        for (size_t i = 0; i < kern.size(); ++i) kW_wrong[i] = kern[i];
512        {
513            // apply the WRONG layout by hand: tap i of channel c is kW[c*dc+i] read as kW[i*C+c]
514            std::vector<float> cs2 = cs;
515            std::vector<float> out_bad((size_t) C, 0.0f);
516            for (int c = 0; c < C; ++c) {
517                double a = 0;
518                for (int i = 0; i < dc - 1; ++i) a += (double) cs2[(size_t) (i * C + c)] * (double) kW_wrong[(size_t) (c * dc + i)];
519                a += (double) x[(size_t) c] * (double) kW_wrong[(size_t) (c * dc + dc - 1)];
520                out_bad[(size_t) c] = (float) a;
521            }
522            const double rel = rel_l1(want, out_bad);
523            std::printf("\n  %-42s %-4s (%.1f%% apart)\n", "conv weight layout is observable",
524                        rel > 0.05 ? "yes" : "*** NO ***", rel * 100);
525            if (!(rel > 0.05)) ++bad;
526        }
527
528        float *d_cs = nullptr, *d_x = nullptr, *d_w = nullptr, *d_o = nullptr;
529        check(DPCT_CHECK_ERROR(d_cs = (float *)sycl::malloc_device(
530                                   cs.size() * 4, dpct::get_in_order_queue())),
531              "cs");
532        check(DPCT_CHECK_ERROR(d_x = (float *)sycl::malloc_device(
533                                   x.size() * 4, dpct::get_in_order_queue())),
534              "cx");
535        check(DPCT_CHECK_ERROR(d_w = (float *)sycl::malloc_device(
536                                   kW.size() * 4, dpct::get_in_order_queue())),
537              "cw");
538        check(DPCT_CHECK_ERROR(d_o = (float *)sycl::malloc_device(
539                                   (size_t)C * 4, dpct::get_in_order_queue())),
540              "co");
541        /*
542        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
543        assuming in the original code the source host memory is pageable memory.
544        If the memory is not pageable, call wait() on event return by memcpy API
545        to ensure synchronization behavior.
546        */
547        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
548                  d_cs, cs.data(), cs.size() * 4).wait()),
549              "ccs");
550        /*
551        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
552        assuming in the original code the source host memory is pageable memory.
553        If the memory is not pageable, call wait() on event return by memcpy API
554        to ensure synchronization behavior.
555        */
556        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(),
557                                                                 x.size() * 4).wait()),
558              "ccx");
559        /*
560        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
561        assuming in the original code the source host memory is pageable memory.
562        If the memory is not pageable, call wait() on event return by memcpy API
563        to ensure synchronization behavior.
564        */
565        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
566                  d_w, kW.data(), kW.size() * 4).wait()),
567              "ccw");
568        strata::kernels::gdn_conv_step(d_cs, d_x, d_w, d_o, C, dc, nullptr);
569        std::vector<float> got((size_t) C), got_cs(cs.size());
570        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
571                                   .memcpy(got.data(), d_o, got.size() * 4)
572                                   .wait()),
573              "cgo");
574        check(
575            DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
576                                 .memcpy(got_cs.data(), d_cs, got_cs.size() * 4)
577                                 .wait()),
578            "cgs");
579        const double rel_out = rel_l1(want, got), rel_cs = rel_l1(cs_want, got_cs);
580        std::printf("  %-42s rel %.3e\n", "conv out vs reference", rel_out);
581        std::printf("  %-42s rel %.3e\n", "conv state slide (mapped) vs reference", rel_cs);
582        if (!(rel_out <= 1e-6)) { std::printf("    *** conv out ***\n"); ++bad; }
583        if (!(rel_cs <= 1e-6)) { std::printf("    *** conv state ***\n"); ++bad; }
584        sycl::free(d_cs, dpct::get_in_order_queue());
585            sycl::free(d_x, dpct::get_in_order_queue());
586            sycl::free(d_w, dpct::get_in_order_queue());
587            sycl::free(d_o, dpct::get_in_order_queue());
588    }
589
590    // ================= 3. l2_norm =================
591    {
592        const int rows = 16, cols = 128;
593        std::vector<float> x((size_t) rows * cols), x_ref;
594        for (auto& val : x) val = gauss(rng) * 3.0f;
595        x_ref = x;
596        const float eps = 1e-6f;
597        for (int r = 0; r < rows; ++r) {
598            double acc = 0;
599            for (int i = 0; i < cols; ++i) acc += (double) x_ref[(size_t) (r * cols + i)] * (double) x_ref[(size_t) (r * cols + i)];
600            const float inv = (float) (1.0 / std::sqrt(acc + (double) eps));
601            for (int i = 0; i < cols; ++i) x_ref[(size_t) (r * cols + i)] *= inv;
602        }
603        // The rival reading puts THE SAME eps on the MEAN instead of on the squared norm, which at
604        // ||x||^2 ~ 1152 and cols = 128 changes the divisor from sqrt(1152) to sqrt(9) - a factor of 11.3, so
605        // the trap is large here.  It would be a much smaller correction on a near-zero row, where the floor
606        // is the whole answer; that regime is not what this fixture exercises.
607        std::vector<float> x_mean = x;
608        for (int r = 0; r < rows; ++r) {
609            double acc = 0;
610            for (int i = 0; i < cols; ++i) acc += (double) x_mean[(size_t) (r * cols + i)] * (double) x_mean[(size_t) (r * cols + i)];
611            const float inv = (float) (1.0 / std::sqrt(acc / cols + (double) eps));
612            for (int i = 0; i < cols; ++i) x_mean[(size_t) (r * cols + i)] *= inv;
613        }
614        const double rel_trap = rel_l1(x_ref, x_mean);
615        std::printf("\n  %-42s %-4s (%.1f%% apart)\n", "eps on sum vs on mean is observable",
616                    rel_trap > 0.05 ? "yes" : "*** NO ***", rel_trap * 100);
617        if (!(rel_trap > 0.05)) ++bad;
618
619        float* d_x = nullptr;
620        check(DPCT_CHECK_ERROR(d_x = (float *)sycl::malloc_device(
621                                   x.size() * 4, dpct::get_in_order_queue())),
622              "lx");
623        /*
624        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
625        assuming in the original code the source host memory is pageable memory.
626        If the memory is not pageable, call wait() on event return by memcpy API
627        to ensure synchronization behavior.
628        */
629        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_x, x.data(),
630                                                                 x.size() * 4).wait()),
631              "lcx");
632        strata::kernels::gdn_l2_norm(d_x, rows, cols, eps, nullptr);
633        std::vector<float> got(x.size());
634        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
635                                   .memcpy(got.data(), d_x, got.size() * 4)
636                                   .wait()),
637              "lcg");
638        const double rel = rel_l1(x_ref, got);
639        std::printf("  %-42s rel %.3e\n", "l2_norm vs reference", rel);
640        if (!(rel <= 1e-6)) ++bad;
641        sycl::free(d_x, dpct::get_in_order_queue());
642    }
643
644    // ================= 4. the closing norm =================
645    {
646        const int S2 = 128, hv2 = 8;
647        std::vector<float> o((size_t) hv2 * S2), z((size_t) hv2 * S2), sn((size_t) S2), y_ref((size_t) hv2 * S2);
648        for (auto& val : o) val = gauss(rng);
649        for (auto& val : z) val = gauss(rng);
650        for (auto& val : sn) val = 1.0f + 0.1f * gauss(rng);
651        const float eps = 1e-6f;
652        for (int h = 0; h < hv2; ++h) {
653            double acc = 0;
654            for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)];
655            const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps));
656            for (int i = 0; i < S2; ++i)
657                y_ref[(size_t) (h * S2 + i)] = o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] *
658                                              sigmoid_f(z[(size_t) (h * S2 + i)]);
659        }
660        float *d_o = nullptr, *d_z = nullptr, *d_sn = nullptr, *d_y = nullptr;
661        check(DPCT_CHECK_ERROR(d_o = (float *)sycl::malloc_device(
662                                   o.size() * 4, dpct::get_in_order_queue())),
663              "no");
664        check(DPCT_CHECK_ERROR(d_z = (float *)sycl::malloc_device(
665                                   z.size() * 4, dpct::get_in_order_queue())),
666              "nz");
667        check(DPCT_CHECK_ERROR(d_sn = (float *)sycl::malloc_device(
668                                   sn.size() * 4, dpct::get_in_order_queue())),
669              "ns");
670        check(
671            DPCT_CHECK_ERROR(d_y = (float *)sycl::malloc_device(
672                                 y_ref.size() * 4, dpct::get_in_order_queue())),
673            "ny");
674        /*
675        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
676        assuming in the original code the source host memory is pageable memory.
677        If the memory is not pageable, call wait() on event return by memcpy API
678        to ensure synchronization behavior.
679        */
680        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_o, o.data(),
681                                                                 o.size() * 4).wait()),
682              "nco");
683        /*
684        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
685        assuming in the original code the source host memory is pageable memory.
686        If the memory is not pageable, call wait() on event return by memcpy API
687        to ensure synchronization behavior.
688        */
689        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_z, z.data(),
690                                                                 z.size() * 4).wait()),
691              "ncz");
692        /*
693        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
694        assuming in the original code the source host memory is pageable memory.
695        If the memory is not pageable, call wait() on event return by memcpy API
696        to ensure synchronization behavior.
697        */
698        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
699                  d_sn, sn.data(), sn.size() * 4).wait()),
700              "ncs");
701        strata::kernels::gdn_out_norm(d_o, d_z, d_sn, d_y, hv2, S2, eps, nullptr);
702        std::vector<float> got(y_ref.size());
703        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
704                                   .memcpy(got.data(), d_y, got.size() * 4)
705                                   .wait()),
706              "ncy");
707        const double rel = rel_l1(y_ref, got);
708        std::printf("\n  %-42s rel %.3e\n", "out norm (rms * ssm_norm * sigmoid z)", rel);
709        if (!(rel <= 1e-6)) ++bad;
710
711        // SiLU instead of sigmoid is the qwen3.5 reading; `ref/gdn.py` says this artifact does NOT use it
712        std::vector<float> y_silu(y_ref.size());
713        for (int h = 0; h < hv2; ++h) {
714            double acc = 0;
715            for (int i = 0; i < S2; ++i) acc += (double) o[(size_t) (h * S2 + i)] * (double) o[(size_t) (h * S2 + i)];
716            const float inv = (float) (1.0 / std::sqrt(acc / S2 + (double) eps));
717            for (int i = 0; i < S2; ++i) {
718                const float zz = z[(size_t) (h * S2 + i)];
719                y_silu[(size_t) (h * S2 + i)] =
720                    o[(size_t) (h * S2 + i)] * inv * sn[(size_t) i] * (zz / (1.0f + std::exp(-zz)));
721            }
722        }
723        const double rel_silu = rel_l1(y_ref, y_silu);
724        std::printf("  %-42s %-4s (%.2f%% apart)\n", "sigmoid vs SiLU on the gate is observable",
725                    rel_silu > 0.05 ? "yes" : "*** NO ***", rel_silu * 100);
726        if (!(rel_silu > 0.05)) ++bad;
727        sycl::free(d_o, dpct::get_in_order_queue());
728            sycl::free(d_z, dpct::get_in_order_queue());
729            sycl::free(d_sn, dpct::get_in_order_queue());
730            sycl::free(d_y, dpct::get_in_order_queue());
731    }
732
733    // ================= 5. the verify-window kernels, T = 1..8, bitwise against the single-token kernels =================
734    // gdn_ab_multi and gdn_step_norm_multi are documented as bitwise `fused_gdn_ab` / `fused_gdn_step_norm` per
735    // token (verify_kernels.hpp). Every T from 1 to kVerifyMaxT is its own exact-T instantiation, so each is run,
736    // and every output and the state are compared with memcmp (not a tolerance).
737    {
738        const int n_embd = strata::core::kCompiledGeometry.n_embd, qk = S * h_k, C = 2 * qk + S * h_v, vd = S * h_v;
739        const float eps = 1e-6f;
740        auto bf16_of = [](float f) {
741            uint32_t u;
742            std::memcpy(&u, &f, 4);
743            return (uint16_t) (u >> 16);
744        };
745        std::vector<uint16_t> wa((size_t) h_v * n_embd), wb((size_t) h_v * n_embd);
746        for (auto& w : wa) w = bf16_of(gauss(rng) * 0.05f);
747        for (auto& w : wb) w = bf16_of(gauss(rng) * 0.05f);
748        std::vector<float> dt((size_t) h_v), ssm_a((size_t) h_v), gamma((size_t) S);
749        for (auto& x : dt) x = gauss(rng);
750        for (auto& x : ssm_a) x = -(0.1f + (float) (rng() % 100) / 50.0f);
751        for (auto& x : gamma) x = 1.0f + 0.1f * gauss(rng);
752        std::vector<float> st0((size_t) S * h_v * S);
753        for (auto& x : st0) x = gauss(rng) * 0.1f;
754
755        auto dev = [&](size_t bytes) {
756            try {
757        void *p = nullptr;
758            check(DPCT_CHECK_ERROR(p = (void *)sycl::malloc_device(
759                                       bytes, dpct::get_in_order_queue())),
760                  "m5");
761            return p;
762        }
763        catch (sycl::exception const &exc) {
764          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
765                    << ", line:" << __LINE__ << std::endl;
766          std::exit(1);
767        }
768        };
769        auto up = [&](const void *h, size_t bytes) {
770            try {
771        void *p = dev(bytes);
772            /*
773            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
774            assuming in the original code the source host memory is pageable
775            memory. If the memory is not pageable, call wait() on event return
776            by memcpy API to ensure synchronization behavior.
777            */
778            check(DPCT_CHECK_ERROR(
779                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(p, h, bytes).wait()),
780                  "u5");
781            return p;
782        }
783        catch (sycl::exception const &exc) {
784          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
785                    << ", line:" << __LINE__ << std::endl;
786          std::exit(1);
787        }
788        };
789        auto down = [&](std::vector<float> &h, const void *d) {
790            try {
791        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
792                                   .memcpy(h.data(), d, h.size() * 4)
793                                   .wait()),
794              "d5");
795        }
796        catch (sycl::exception const &exc) {
797          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
798                    << ", line:" << __LINE__ << std::endl;
799          std::exit(1);
800        }
801        };
802        auto d_wa = (uint16_t*) up(wa.data(), wa.size() * 2);
803        auto d_wb = (uint16_t*) up(wb.data(), wb.size() * 2);
804        auto d_dt = (float*) up(dt.data(), dt.size() * 4);
805        auto d_sa = (float*) up(ssm_a.data(), ssm_a.size() * 4);
806        auto d_gm = (float*) up(gamma.data(), gamma.size() * 4);
807        int ab_bad = 0, sn_bad = 0, ab_n = 0, sn_n = 0;
808        for (int T = 1; T <= strata::kernels::kVerifyMaxT; ++T) {
809            // --- alpha/beta
810            std::vector<float> x((size_t) T * n_embd);
811            for (auto& v : x) v = gauss(rng);
812            auto d_x = (float*) up(x.data(), x.size() * 4);
813            auto d_g = (float*) dev((size_t) T * h_v * 4), d_b = (float*) dev((size_t) T * h_v * 4);
814            auto d_gr = (float*) dev((size_t) T * h_v * 4), d_br = (float*) dev((size_t) T * h_v * 4);
815            strata::kernels::gdn_ab_multi(d_x, d_wa, d_wb, d_dt, d_sa, d_g, d_b, n_embd, h_v, T, nullptr);
816            for (int t = 0; t < T; ++t)
817                strata::kernels::fused_gdn_ab(d_x + (size_t) t * n_embd, d_wa, d_wb, d_dt, d_sa, d_gr + (size_t) t * h_v,
818                                              d_br + (size_t) t * h_v, n_embd, h_v, nullptr);
819            std::vector<float> g((size_t) T * h_v), b(g.size()), gr(g.size()), br(g.size());
820            down(g, d_g); down(b, d_b); down(gr, d_gr); down(br, d_br);
821            ++ab_n;
822            if (std::memcmp(g.data(), gr.data(), g.size() * 4) != 0 || std::memcmp(b.data(), br.data(), b.size() * 4) != 0) {
823                std::printf("    *** gdn_ab_multi T=%d differs from fused_gdn_ab (memcmp) ***\n", T);
824                ++ab_bad;
825            }
826            sycl::free(d_x, dpct::get_in_order_queue());
827                sycl::free(d_g, dpct::get_in_order_queue());
828                sycl::free(d_b, dpct::get_in_order_queue());
829                sycl::free(d_gr, dpct::get_in_order_queue());
830                sycl::free(d_br, dpct::get_in_order_queue());
831
832            // --- the recurrence + output norm
833            std::vector<float> h((size_t) T * C), gate((size_t) T * h_v), beta((size_t) T * h_v), z((size_t) T * vd);
834            for (auto& v : h) v = gauss(rng) * 0.1f;
835            for (auto& v : gate) v = -(0.5f + 3.0f * (float) (rng() % 100) / 100.0f);
836            for (auto& v : beta) v = (float) (rng() % 100) / 100.0f;
837            for (auto& v : z) v = gauss(rng);
838            auto d_h = (float*) up(h.data(), h.size() * 4);
839            auto d_gate = (float*) up(gate.data(), gate.size() * 4);
840            auto d_beta = (float*) up(beta.data(), beta.size() * 4);
841            auto d_z = (float*) up(z.data(), z.size() * 4);
842            auto d_y = (float*) dev((size_t) T * vd * 4);
843            auto d_yr = (float*) dev((size_t) T * vd * 4);
844            auto d_st = (float*) dev(st0.size() * 4);
845            auto d_sr = (float*) dev(st0.size() * 4);
846            int32_t* d_nk = (int32_t*) dev(4);
847            // the reference chain (the single-token kernel), n tokens, into d_sr / d_yr
848            auto run_ref = [&](int n) {
849                /*
850                DPCT1114: cudaMemcpy is migrated to asynchronization
851                memcpy, assuming in the original code the source host memory is
852                pageable memory. If the memory is not pageable, call wait() on
853                event return by memcpy API to ensure synchronization behavior.
854                */
855                try {
856            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
857                      d_sr, st0.data(), st0.size() * 4).wait()),
858                  "r0");
859                for (int t = 0; t < n; ++t)
860                    strata::kernels::fused_gdn_step_norm(d_sr, d_h + (size_t) t * C, d_h + (size_t) t * C + qk,
861                                                         d_h + (size_t) t * C + 2 * qk, d_gate + (size_t) t * h_v,
862                                                         d_beta + (size_t) t * h_v, d_z + (size_t) t * vd, d_gm, eps,
863                                                         d_yr + (size_t) t * vd, h_k, h_v, nullptr);
864            }
865            catch (sycl::exception const &exc) {
866              std::cerr << exc.what() << "Exception caught at file:" << __FILE__
867                        << ", line:" << __LINE__ << std::endl;
868              std::exit(1);
869            }
870            };
871            std::vector<float> y((size_t) T * vd), yr(y.size()), st(st0.size()), sr(st0.size());
872            // (name, n_keep tokens or -1 = verify half, t_out_begin)
873            struct Case { const char* name; int n_keep; int tb; };
874            std::vector<Case> cases = {{"verify", -1, 0}, {"verify tb", -1, T > 1 ? T / 2 : 0}, {"commit", T, 0},
875                                       {"commit tb", T, T / 2}, {"commit state only", T, T}};
876            if (T > 1) cases.push_back({"commit n-1", T - 1, T - 1});
877            for (const Case& c : cases) {
878                /*
879                DPCT1114: cudaMemcpy is migrated to asynchronization
880                memcpy, assuming in the original code the source host memory is
881                pageable memory. If the memory is not pageable, call wait() on
882                event return by memcpy API to ensure synchronization behavior.
883                */
884                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
885                          d_st, st0.data(), st0.size() * 4).wait()),
886                      "s0");
887                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
888                                           .memset(d_y, 0, (size_t)T * vd * 4)
889                                           .wait()),
890                      "y0");
891                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
892                                           .memset(d_yr, 0, (size_t)T * vd * 4)
893                                           .wait()),
894                      "yr0");
895                const int n = c.n_keep < 0 ? T : c.n_keep;
896                if (c.n_keep >= 0)
897                    check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
898                                               .memcpy(d_nk, &c.n_keep, 4)
899                                               .wait()),
900                          "nk");
901                strata::kernels::gdn_step_norm_multi(d_st, d_h, C, d_gate, d_beta, d_z, d_gm, eps, d_y, h_k, h_v, T,
902                                                     c.n_keep >= 0 ? d_nk : nullptr, nullptr, c.tb);
903                run_ref(n);
904                down(y, d_y); down(yr, d_yr); down(st, d_st); down(sr, d_sr);
905                bool ok = true;
906                size_t y_bad = 0, y_all = 0;
907                for (int t = c.tb; t < n; ++t) {
908                    for (int i = 0; i < vd; ++i, ++y_all)
909                        if (std::memcmp(&y[(size_t) t * vd + i], &yr[(size_t) t * vd + i], 4) != 0) ++y_bad;
910                }
911                if (y_bad) ok = false;
912                // the verify half leaves the state untouched; the commit half writes the state after n tokens
913                const std::vector<float>& want_st = c.n_keep < 0 ? st0 : sr;
914                if (std::memcmp(st.data(), want_st.data(), st.size() * 4) != 0) ok = false;
915                ++sn_n;
916                if (!ok) {
917                    std::printf("    *** gdn_step_norm_multi T=%d '%s' differs from fused_gdn_step_norm (memcmp): %zu of %zu y words%s ***\n",
918                                T, c.name, y_bad, y_all,
919                                std::memcmp(st.data(), (c.n_keep < 0 ? st0 : sr).data(), st.size() * 4) != 0 ? ", state too" : "");
920                    ++sn_bad;
921                }
922                if (std::getenv("STRATA_GDN_VERIFY_BENCH")) {
923                    auto hash = [](const std::vector<float>& values) {
924                        uint64_t h = 1469598103934665603ull;
925                        for (float v : values) {
926                            uint32_t u;
927                            std::memcpy(&u, &v, sizeof(u));
928                            h = (h ^ u) * 1099511628211ull;
929                        }
930                        return h;
931                    };
932                    std::printf("GDNSIGNATURE T=%d case=%s y=%016llx state=%016llx\n", T, c.name,
933                                (unsigned long long) hash(y), (unsigned long long) hash(st));
934                    if (c.n_keep < 0 && c.tb == 0) {
935                        auto* q = &dpct::get_in_order_queue();
936                        constexpr int calls = 32;
937                        dpct::experimental::command_graph_ptr graph;
938                        dpct::experimental::begin_recording(q);
939                        for (int i = 0; i < calls; ++i)
940                            strata::kernels::gdn_step_norm_multi(
941                                d_st, d_h, C, d_gate, d_beta, d_z, d_gm, eps,
942                                d_y, h_k, h_v, T, nullptr, q, 0);
943                        dpct::experimental::end_recording(q, &graph);
944                        auto executable = graph->finalize();
945                        delete graph;
946                        std::vector<double> times;
947                        for (int i = 0; i < 20; ++i) {
948                            auto begin = q->ext_oneapi_submit_barrier();
949                            q->ext_oneapi_graph(executable);
950                            auto end = q->ext_oneapi_submit_barrier();
951                            end.wait_and_throw();
952                            if (i >= 5)
953                                times.push_back(double(
954                                    end.get_profiling_info<sycl::info::event_profiling::command_end>() -
955                                    begin.get_profiling_info<sycl::info::event_profiling::command_start>()) / 1000 / calls);
956                        }
957                        std::sort(times.begin(), times.end());
958                        std::printf("GDNVERIFYBENCH T=%d us=%.3f\n", T, times[times.size() / 2]);
959                    }
960                }
961            }
962            sycl::free(d_h, dpct::get_in_order_queue());
963                sycl::free(d_gate, dpct::get_in_order_queue());
964                sycl::free(d_beta, dpct::get_in_order_queue());
965                sycl::free(d_z, dpct::get_in_order_queue());
966                sycl::free(d_y, dpct::get_in_order_queue());
967                sycl::free(d_yr, dpct::get_in_order_queue());
968                sycl::free(d_st, dpct::get_in_order_queue());
969            sycl::free(d_sr, dpct::get_in_order_queue());
970                sycl::free(d_nk, dpct::get_in_order_queue());
971        }
972        sycl::free(d_wa, dpct::get_in_order_queue());
973            sycl::free(d_wb, dpct::get_in_order_queue());
974            sycl::free(d_dt, dpct::get_in_order_queue());
975            sycl::free(d_sa, dpct::get_in_order_queue());
976            sycl::free(d_gm, dpct::get_in_order_queue());
977        std::printf("\n  %-42s %s (%d cases)\n", "gdn_ab_multi T=1..8 == fused_gdn_ab", ab_bad ? "*** NO ***" : "bitwise", ab_n);
978        std::printf("  %-42s %s (%d cases)\n", "gdn_step_norm_multi T=1..8 == single-token", sn_bad ? "*** NO ***" : "bitwise", sn_n);
979        bad += ab_bad + sn_bad;
980    }
981
982    std::printf("\ngdn: %d failures\n", bad);
983    if (bad) return 1;
984    if (selftest) std::printf("gdn_parity OK\n");
985    return 0;
986}