okami.mom/strata

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

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

main
87.3 KiB1569 linesraw
1// src/kernels/ple_parity.cpp - P2.S4's test: the n-gram hash, the IQ4_NL table read, and the PLE block.
2//
3// THREE PARTS, THREE DIFFERENT ORACLES, and none of them is this project's own code:
4//
5//   A. THE HASH against `ref/ngram.py::ngram_rows`, via `ple_oracle_vectors.inc` (generated).  The properties
6//      are asserted OBSERVABLE first - XOR vs sum, `%` vs `&`, the cut DIRECTION, the NULL sentinel - because
7//      each rival reading produces a perfectly valid index in range.
8//   B. THE TABLE against numpy reading the ORIGINAL GGUF at the offset the validated `gguf_reader` reports.
9//   C. THE BLOCK against ggml's own graph, captured in `bench/micro/ple_in.bin` / `ple_out.bin` by
10//      `ple_layer_xcheck.cpp`.  That file records EVERY intermediate (key, value, gate, gated, normalized,
11//      conv_out, result), so a mismatch can be attributed to a stage instead of guessed at - and the weights
12//      in it were checked to be the artifact's real ones before this test was written.
13#define DPCT_PROFILING_ENABLED
14#include <sycl/sycl.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/kernels/ple.hpp"
17#include "strata/kernels/ngram.hpp"
18#include "strata/kernels/f16_bits.hpp"
19#include "strata/kernels/native_mmvq.hpp"
20#include "ple_oracle_vectors.inc"
21
22#include <algorithm>
23#include <cmath>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <string>
28#include <stdexcept>
29#include <vector>
30
31namespace k = strata::kernels;
32namespace o = strata::kernels::ple_oracle;
33
34namespace {
35
36void ck(dpct::err0 e, const char *what) {
37}
38
39/// TOLERANCE CHECKS MUST BE NaN-SAFE, and `x <= t` is not.
40///
41/// `x <= t` AND `x > t` are BOTH false for NaN, so a check written either way can silently pass - round 197
42/// found `shared_expert_parity` printing a perfect score for an entirely-NaN fixture because the accumulator
43/// was `if (rel > worst) worst = rel;` and NaN is never greater.  Every comparison in this file goes through
44/// `le`/`gt`, which require the value to be FINITE first, and every compared pair is counted for non-finite
45/// entries and the count printed.  A NaN fixture is then a loud failure rather than a green line.
46bool le(double x, double t) { return std::isfinite(x) && x <= t; }
47bool gt(double x, double t) { return std::isfinite(x) && x > t; }
48
49/// How many entries of `a` are not finite.  Printed next to every comparison.
50long long nonfinite(const float* a, size_t n) {
51    long long k = 0;
52    for (size_t i = 0; i < n; ++i)
53        if (!std::isfinite(a[i])) ++k;
54    return k;
55}
56
57/// Normalised L1 with the reference magnitude returned.  For the STAGE comparisons a plain |ref| denominator
58/// is right: these are dense vectors of O(1) values with no cancellation between them.
59///
60/// Returns NaN if EITHER side has a non-finite entry, so a caller that forgets `le`/`gt` still cannot read a
61/// finite-looking number out of a broken fixture.
62double rel_l1(const float* a, const float* b, size_t n, double* mag_out = nullptr,
63              long long* nf_out = nullptr) {
64    double d = 0, m = 0;
65    long long nf = 0;
66    for (size_t i = 0; i < n; ++i) {
67        if (!std::isfinite(a[i]) || !std::isfinite(b[i])) { ++nf; continue; }
68        d += std::fabs((double) a[i] - (double) b[i]);
69        m += std::fabs((double) a[i]);
70    }
71    if (mag_out) *mag_out = m / (double) (n ? n : 1);
72    if (nf_out) *nf_out = nf;
73    if (nf) return std::nan("");
74    return d / (m > 1e-30 ? m : 1e-30);
75}
76
77/// The file's size, WITHOUT reading it.
78///
79/// The first version of this test called `read_file(gguf)` - which reads the WHOLE file into a vector - three
80/// times, on a 28.8 GB GGUF.  That is 27 GB of RSS, three full passes over the file, and a 132-second ctest
81/// entry in a suite where every other test is under a second.  A test that slow stops being run, which is how
82/// a gate stops being a gate.  Everything below now reads only the bytes it actually compares.
83long long file_size(const char* path) {
84    std::FILE* f = std::fopen(path, "rb");
85    if (!f) return -1;
86#if defined(_MSC_VER)
87    _fseeki64(f, 0, SEEK_END);
88    const long long n = _ftelli64(f);
89#else
90    std::fseek(f, 0, SEEK_END);
91    const long long n = std::ftell(f);
92#endif
93    std::fclose(f);
94    return n;
95}
96
97/// `n` bytes at `off`, or an empty vector.
98std::vector<uint8_t> read_at(const char* path, long long off, size_t n) {
99    std::vector<uint8_t> v(n);
100    std::FILE* f = std::fopen(path, "rb");
101    if (!f) return {};
102#if defined(_MSC_VER)
103    if (_fseeki64(f, off, SEEK_SET) != 0) { std::fclose(f); return {}; }
104#else
105    if (std::fseek(f, (long) off, SEEK_SET) != 0) { std::fclose(f); return {}; }
106#endif
107    const size_t got = std::fread(v.data(), 1, n, f);
108    std::fclose(f);
109    if (got != n) return {};
110    return v;
111}
112
113/// Only used for the pack, which is 5.4 GB rather than 28.8 GB - and even then the caller says which region.
114std::vector<uint8_t> read_path(const char* path) {
115    const long long n = file_size(path);
116    if (n <= 0) return {};
117    return read_at(path, 0, (size_t) n);
118}
119
120/// Dequantize one IQ4_NL row with an INTERLEAVED nibble order, to show the correct split-half order is
121/// observable.  Deliberately shares nothing with the kernel's decoder.
122void deq_interleaved(const uint8_t* row, float* out160) {
123    for (int b = 0; b < k::PLE_HEAD_DIM / 32; ++b) {
124        const uint8_t* blk = row + (size_t) b * 18;
125        uint16_t db;
126        std::memcpy(&db, blk, 2);
127        const float d = k::f32_from_f16(db);
128        for (int j = 0; j < 16; ++j) {
129            out160[b * 32 + 2 * j] = d * (float) k::iq4nl_code(blk[2 + j] & 0x0F);
130            out160[b * 32 + 2 * j + 1] = d * (float) k::iq4nl_code(blk[2 + j] >> 4);
131        }
132    }
133}
134
135struct PleCapture {
136    int n_embd = 0, hc = 0, nt = 0, kern = 0, dil = 0;
137    float eps = 0.0f;
138    std::vector<float> emb, hidden, w_key, w_value, w_nk, w_nq, w_nc, w_conv, hist;
139    // oracle outputs
140    std::vector<float> key, value, gate, gated, normalized, conv_out, result;
141};
142
143bool load_capture(const char* in_path, const char* out_path, PleCapture& c) {
144    std::FILE* fi = std::fopen(in_path, "rb");
145    if (!fi) return false;
146    int32_t h[5] = {0};
147    if (std::fread(h, 4, 5, fi) != 5) { std::fclose(fi); return false; }
148    c.n_embd = h[0]; c.hc = h[1]; c.nt = h[2]; c.kern = h[3]; c.dil = h[4];
149    if (std::fread(&c.eps, 4, 1, fi) != 1) { std::fclose(fi); return false; }
150    // Validate before deriving sizes or allocating. This bounded diagnostic
151    // format is for this model's geometry and at most 64 captured tokens.
152    if (c.n_embd != k::NG_N_EMBD || c.hc != k::NG_HC || c.nt <= 0 || c.nt > 64 ||
153        c.kern != k::PLE_CONV_KERNEL || c.dil != k::NGRAM_SIZE || c.eps != k::NG_RMS_EPS) {
154        std::fclose(fi); return false;
155    }
156    const long long nd = c.n_embd, hcd = (long long) c.hc * c.n_embd, nt = c.nt,
157                    hist = (long long) (c.kern - 1) * c.dil;
158    const long long in_bytes = 24 + 4 * (nt * nd + nt * hcd + hcd * nd + nd * nd +
159                                        3 * hcd + hcd * c.kern + hist * hcd);
160    const long long out_bytes = 12 + 4 * nt * (5 * hcd + nd + c.hc);
161    if (file_size(in_path) != in_bytes || file_size(out_path) != out_bytes) {
162        std::fclose(fi); return false;
163    }
164    auto rd = [](std::FILE* file, std::vector<float>& v, long long n) {
165        v.resize((size_t) n);
166        return n == 0 || std::fread(v.data(), 4, (size_t) n, file) == (size_t) n;
167    };
168    bool ok = rd(fi, c.emb, nt * nd) && rd(fi, c.hidden, nt * hcd) && rd(fi, c.w_key, hcd * nd) &&
169              rd(fi, c.w_value, nd * nd) && rd(fi, c.w_nk, hcd) && rd(fi, c.w_nq, hcd) && rd(fi, c.w_nc, hcd) &&
170              rd(fi, c.w_conv, hcd * c.kern) && rd(fi, c.hist, hist * hcd);
171    std::fclose(fi);
172    if (!ok) return false;
173
174    std::FILE* fo = std::fopen(out_path, "rb");
175    if (!fo) return false;
176    int32_t oh[3] = {0};
177    if (std::fread(oh, 4, 3, fo) != 3) { std::fclose(fo); return false; }
178    if (oh[0] != c.n_embd || oh[1] != hcd || oh[2] != c.nt) { std::fclose(fo); return false; }
179    ok = rd(fo, c.key, nt * hcd) && rd(fo, c.value, nt * nd) && rd(fo, c.gate, nt * c.hc) && rd(fo, c.gated, nt * hcd) &&
180         rd(fo, c.normalized, nt * hcd) && rd(fo, c.conv_out, nt * hcd) && rd(fo, c.result, nt * hcd);
181    std::fclose(fo);
182    return ok;
183}
184
185int history_advance_regression() {
186    const size_t channels = (size_t) k::NG_HC_DIM, rows = (size_t) k::NG_HIST, guard = 16;
187    const size_t count = channels * rows;
188    std::vector<float> expected(count), normalized(channels), actual(count);
189    for (size_t c = 0; c < channels; ++c)
190        for (size_t r = 0; r < rows; ++r) expected[c * rows + r] = -float(c * 16 + r + 1);
191    float *history_storage = nullptr, *norm_storage = nullptr;
192    ck(DPCT_CHECK_ERROR(history_storage = sycl::malloc_device<float>(
193                            (count + 2 * guard), dpct::get_in_order_queue())),
194       "history regression allocation");
195    ck(DPCT_CHECK_ERROR(
196           norm_storage = sycl::malloc_device<float>(
197               (channels + 2 * guard), dpct::get_in_order_queue())),
198       "history norm allocation");
199    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
200                            .memset(history_storage, 0xa5,
201                                    (count + 2 * guard) * sizeof(float))
202                            .wait()),
203       "history guard init");
204    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
205                            .memset(norm_storage, 0xa5,
206                                    (channels + 2 * guard) * sizeof(float))
207                            .wait()),
208       "history norm guard init");
209    float* history = history_storage + guard;
210    float* norm = norm_storage + guard;
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    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
218           history, expected.data(), count * sizeof(float)).wait()),
219       "history initial values");
220    dpct::queue_ptr stream;
221    dpct::experimental::command_graph_ptr graph;
222    dpct::experimental::command_graph_exec_ptr executable;
223    /*
224    DPCT1025: The SYCL queue is created ignoring the flag and priority
225    options.
226    */
227    ck(DPCT_CHECK_ERROR(stream = dpct::get_current_device().create_queue(true)),
228       "history regression stream");
229    ck(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(stream)),
230       "history regression capture");
231    k::ple_history_advance(history, norm, stream);
232    ck(DPCT_CHECK_ERROR(dpct::experimental::end_recording(stream, &graph)),
233       "history regression capture end");
234    ck(DPCT_CHECK_ERROR(
235           executable = new sycl::ext::oneapi::experimental::command_graph<
236               sycl::ext::oneapi::experimental::graph_state::executable>(
237               graph->finalize())),
238       "history regression instantiate");
239    int bad = 0;
240    for (int token = 0; token < 12; ++token) {
241        for (size_t c = 0; c < channels; ++c) {
242            normalized[c] = float((token + 1) * 1000000 + c); // distinct exactly represented integers
243            for (size_t r = 0; r + 1 < rows; ++r) expected[c * rows + r] = expected[c * rows + r + 1];
244            expected[c * rows + rows - 1] = normalized[c];
245        }
246        /*
247        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
248        While the origin API might be synchronous, it depends on the type of
249        operand memory, so you may need to call wait() on event return by memcpy
250        API to ensure synchronization behavior.
251        */
252        ck(DPCT_CHECK_ERROR(stream->memcpy(norm, normalized.data(),
253                                           channels * sizeof(float))),
254           "history new normalized row");
255        ck(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*executable)),
256           "history captured advance");
257        ck(DPCT_CHECK_ERROR(stream->wait()), "history captured advance sync");
258        ck(DPCT_CHECK_ERROR(
259               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
260                   .memcpy(actual.data(), history, count * sizeof(float))
261                   .wait()),
262           "history readback");
263        if (std::memcmp(actual.data(), expected.data(), count * sizeof(float)) != 0) {
264            std::printf("  history advance mismatch after token %d\n", token);
265            ++bad;
266        }
267    }
268    bool overlap_refused = false, null_refused = false;
269    try { k::ple_history_advance(history, history + 1, stream); }
270    catch (const std::invalid_argument&) { overlap_refused = true; }
271    try { k::ple_history_advance(history, nullptr, stream); }
272    catch (const std::invalid_argument&) { null_refused = true; }
273    if (!overlap_refused || !null_refused) ++bad;
274    auto guard_ok = [&](float* storage, size_t payload) {
275        uint8_t before[64], after[64];
276        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
277                                .memcpy(before, storage, sizeof(before))
278                                .wait()),
279           "history prefix guard");
280        ck(DPCT_CHECK_ERROR(
281               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
282                   .memcpy(after, storage + guard + payload, sizeof(after))
283                   .wait()),
284           "history suffix guard");
285        return std::all_of(before, before + 64, [](uint8_t b) { return b == 0xa5; }) &&
286               std::all_of(after, after + 64, [](uint8_t b) { return b == 0xa5; });
287    };
288    if (!guard_ok(history_storage, count) || !guard_ok(norm_storage, channels)) ++bad;
289    std::printf("  PLE history 12 captured steps, row-fastest state and guards: %s\n", bad == 0 ? "pass" : "FAIL");
290    ck(DPCT_CHECK_ERROR(delete (executable)), "history graph exec destroy");
291    ck(DPCT_CHECK_ERROR(delete (graph)), "history graph destroy");
292    ck(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(stream)),
293       "history stream destroy");
294    sycl::free(history_storage, dpct::get_in_order_queue());
295        sycl::free(norm_storage, dpct::get_in_order_queue());
296    return bad;
297}
298
299}  // namespace
300
301int main(int argc, char** argv) {
302    bool selftest = false;
303    bool check_fixtures = false;
304    std::string pack = "pack/full";
305    // --gguf, else $STRATA_PLE_GGUF, else the development layout (run from the engine root)
306    std::string gguf = std::getenv("STRATA_PLE_GGUF") ? std::getenv("STRATA_PLE_GGUF")
307                                                      : "../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf";
308    std::string in_bin = "bench/micro/ple_in.bin", out_bin = "bench/micro/ple_out.bin";
309    for (int i = 1; i < argc; ++i) {
310        const std::string a = argv[i];
311        if (a == "--selftest") selftest = true;
312        else if (a == "--check-fixtures") check_fixtures = true;
313        else if (a == "--pack" && i + 1 < argc) pack = argv[++i];
314        else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i];
315        else if (a == "--in" && i + 1 < argc) in_bin = argv[++i];
316        else if (a == "--out" && i + 1 < argc) out_bin = argv[++i];
317        else { std::fprintf(stderr, "usage: ple_parity [--selftest] [--check-fixtures] [--pack D] [--gguf F] [--in F] [--out F]\n");
318               return 2; }
319    }
320    if (selftest && check_fixtures) {
321        std::fprintf(stderr, "ple_parity: --check-fixtures is CPU-only; use it separately from --selftest\n");
322        return 2;
323    }
324    // Required self-test fixtures are checked before the first CUDA call, so
325    // missing files cannot become an apparent pass or a misleading GPU error.
326    k::PleTable table;
327    std::string err;
328    PleCapture cap;
329    bool preflight_done = false;
330    if (selftest || check_fixtures) {
331        if (!table.open(gguf, err) || table.rows() != o::kTableRows ||
332            file_size(gguf.c_str()) != (long long) o::kTableDataStart + (long long) o::kTableRows * k::PLE_ROW_BYTES) {
333            std::fprintf(stderr, "ple_parity: required PLE table is missing or incompatible: %s (%s)\n", gguf.c_str(), err.c_str());
334            return 2;
335        }
336        const uint64_t pack_needed = std::max({o::kKeyCodesOffset + o::kKeyCodesBytes,
337            o::kKeyScalesOffset + o::kKeyScalesBytes, o::kValueOffset + o::kValueBytes});
338        const long long pack_size = file_size((pack + "/dense.bin").c_str());
339        if (pack_size < 0 || (uint64_t) pack_size < pack_needed) {
340            std::fprintf(stderr, "ple_parity: required dense pack is missing or truncated: %s/dense.bin\n", pack.c_str());
341            return 2;
342        }
343        if (!load_capture(in_bin.c_str(), out_bin.c_str(), cap)) {
344            std::fprintf(stderr, "ple_parity: required block fixtures are missing, truncated or incompatible: %s / %s\n", in_bin.c_str(), out_bin.c_str());
345            return 2;
346        }
347        preflight_done = true;
348        if (check_fixtures) {
349            std::puts("PASS required PLE fixture structure on CPU; no GPU numerical checks were run");
350            return 0;
351        }
352        if (!k::ple_block_available()) {
353            std::fprintf(stderr, "ple_parity: --selftest requires a CUDA device for block checks\n");
354            return 2;
355        }
356    }
357    int bad = history_advance_regression();
358    const k::PleConsts C = k::ple_artifact_consts();
359
360    // ============================ A. THE HASH ============================
361    std::printf("A. the n-gram hash, against ref/ngram.py with the artifact's own constants\n");
362
363    // ---- the constants must be internally consistent BEFORE they are used: `head_offsets` is its own array
364    //      in the metadata, so deriving it from `vocab_sizes` would hide a disagreement between them.
365    {
366        uint64_t run = 0;
367        bool ok = true;
368        for (int h = 0; h < k::PLE_N_HEADS; ++h) {
369            if (C.offset[h] != run) ok = false;
370            run += C.vocab[h];
371        }
372        const uint64_t total = run;
373        const bool fits = total <= k::PLE_TABLE_ROWS;
374        std::printf("  %-46s %s (sum %llu <= %llu rows; %llu spare)\n",
375                    "head_offsets == the running sum of vocab_sizes", ok && fits ? "yes" : "*** NO ***",
376                    (unsigned long long) total, (unsigned long long) k::PLE_TABLE_ROWS,
377                    (unsigned long long) (k::PLE_TABLE_ROWS - total));
378        if (!ok || !fits) ++bad;
379    }
380
381    for (int ci = 0; ci < o::kHashCaseCount; ++ci) {
382        const o::HashCase& hc = o::kHashCases[ci];
383        std::vector<uint32_t> got((size_t) hc.n_tokens * k::PLE_N_HEADS);
384        k::ngram_rows(hc.tokens, hc.prev, hc.n_tokens, C, got.data());
385        long long diff = 0;
386        for (size_t i = 0; i < got.size(); ++i)
387            if (got[i] != hc.rows[i]) ++diff;
388        std::printf("  %-46s %s (%lld of %zu differ)\n", hc.name, diff ? "*** WRONG ***" : "matches", diff,
389                    got.size());
390        if (diff) {
391            for (int t = 0; t < hc.n_tokens && diff; ++t) {
392                for (int h = 0; h < k::PLE_N_HEADS; ++h) {
393                    const uint32_t g = got[(size_t) t * 16 + h], w = hc.rows[(size_t) t * 16 + h];
394                    if (g != w) {
395                        std::printf("      first: t=%d h=%d got %u want %u\n", t, h, g, w);
396                        t = hc.n_tokens;
397                        break;
398                    }
399                }
400            }
401            ++bad;
402        }
403    }
404
405    // ---- the rival readings, each computed and required to DIFFER from the oracle -------------------
406    //
407    // Every one of these produces a 16-element vector of valid indices.  That is the whole reason the hash is
408    // transcribed property by property: no range check, no shape check and no summing test can see any of
409    // them, only an oracle can - and only a DELIBERATELY-WRONG fixture can show that the oracle comparison
410    // has the power to catch them.
411    {
412        const o::HashCase& hc = o::kHashCases[0];   // the window-direction case, 4 tokens
413        const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS;
414        std::vector<uint32_t> xor_v((size_t) T * n_heads), sum_v((size_t) T * n_heads),
415            mask_v((size_t) T * n_heads), back_v((size_t) T * n_heads), zero_v((size_t) T * n_heads);
416        for (int i = 0; i < T; ++i) {
417            int64_t ctx[k::NGRAM_SIZE];
418            ctx[0] = hc.tokens[i];
419            for (int s = 1; s < k::NGRAM_SIZE; ++s) ctx[s] = hc.prev[i * np + (np - s)];
420            for (int n = 2; n <= k::NGRAM_SIZE; ++n) {
421                // (1) SUM instead of XOR
422                uint64_t sum = 0;
423                for (int j = 0; j < n; ++j) sum += (uint64_t) ctx[j] * C.mult[j];
424                // (2) mask instead of modulo: the vocab sizes are NOT powers of two
425                uint64_t xr = k::ngram_mixed(ctx, C.mult, n);
426                // (4) token 0 treated as "missing" the way -1 is
427                int64_t ctx0[k::NGRAM_SIZE];
428                for (int j = 0; j < k::NGRAM_SIZE; ++j)
429                    ctx0[j] = (ctx[j] == k::TOKEN_NULL || ctx[j] == 0) ? k::PLE_EOS_TOKEN_ID : ctx[j];
430                uint64_t xr0 = k::ngram_mixed(ctx0, C.mult, n);
431                // (3) the window read NEWEST-first instead of oldest-first: prev index (s-1)
432                int64_t ctxb[k::NGRAM_SIZE];
433                ctxb[0] = hc.tokens[i];
434                for (int s = 1; s < k::NGRAM_SIZE; ++s) ctxb[s] = hc.prev[i * np + (s - 1)];
435                uint64_t xrb = k::ngram_mixed(ctxb, C.mult, n);
436                const int base = (n - 2) * k::HEADS_PER_NGRAM;
437                for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) {
438                    const int h = base + g;
439                    xor_v[(size_t) i * n_heads + h] = (uint32_t) (xr % C.vocab[h] + C.offset[h]);
440                    sum_v[(size_t) i * n_heads + h] = (uint32_t) (sum % C.vocab[h] + C.offset[h]);
441                    mask_v[(size_t) i * n_heads + h] =
442                        (uint32_t) ((xr & (C.vocab[h] - 1)) + C.offset[h]);
443                    back_v[(size_t) i * n_heads + h] = (uint32_t) (xrb % C.vocab[h] + C.offset[h]);
444                    zero_v[(size_t) i * n_heads + h] = (uint32_t) (xr0 % C.vocab[h] + C.offset[h]);
445                }
446            }
447        }
448        struct Rival { const char* name; const std::vector<uint32_t>* v; };
449        const Rival rivals[] = {{"XOR vs SUM", &sum_v},
450                                {"% vs & (vocab sizes are not powers of two)", &mask_v},
451                                {"window read newest-first, not oldest-first", &back_v},
452                                {"token id 0 treated as the NULL sentinel", &zero_v}};
453        for (const Rival& r : rivals) {
454            // A rival is observable if it disagrees with the ORACLE, which is what the test above compares.
455            long long d = 0;
456            for (size_t i = 0; i < r.v->size(); ++i)
457                if ((*r.v)[i] != hc.rows[i]) ++d;
458            const bool visible = d > 0;
459            std::printf("  %-46s %s (%lld of %zu rows differ from the oracle)\n", r.name,
460                        visible ? "yes" : "*** NO - the fixture cannot see this ***", d, r.v->size());
461            if (!visible) ++bad;
462        }
463        (void) xor_v;
464    }
465
466    // ---- the EOS cut DIRECTION, which needs a case where the two directions disagree ----------------
467    {
468        const o::HashCase& hc = o::kHashCases[1];   // [[N,N],[7,EOS],[EOS,7]]
469        const int T = hc.n_tokens, np = k::NGRAM_SIZE - 1, n_heads = k::PLE_N_HEADS;
470        std::vector<uint32_t> fwd((size_t) T * n_heads), bwd((size_t) T * n_heads);
471        for (int i = 0; i < T; ++i) {
472            int64_t f[k::NGRAM_SIZE], b[k::NGRAM_SIZE];
473            f[0] = b[0] = hc.tokens[i];
474            bool cf = false, cb = false;
475            for (int s = 1; s < k::NGRAM_SIZE; ++s) {
476                const int32_t fv = hc.prev[i * np + (np - s)];
477                cf = cf || fv < 0 || fv == k::PLE_EOS_TOKEN_ID;
478                f[s] = cf ? k::PLE_EOS_TOKEN_ID : fv;
479                // the BACKWARD reading: only the position that IS EOS becomes EOS
480                const int32_t bv = hc.prev[i * np + (np - s)];
481                b[s] = (bv < 0 || bv == k::PLE_EOS_TOKEN_ID) ? k::PLE_EOS_TOKEN_ID : bv;
482                (void) cb;
483            }
484            for (int n = 2; n <= k::NGRAM_SIZE; ++n) {
485                const uint64_t mf = k::ngram_mixed(f, C.mult, n), mb = k::ngram_mixed(b, C.mult, n);
486                const int base = (n - 2) * k::HEADS_PER_NGRAM;
487                for (int g = 0; g < k::HEADS_PER_NGRAM; ++g) {
488                    const int h = base + g;
489                    fwd[(size_t) i * n_heads + h] = (uint32_t) (mf % C.vocab[h] + C.offset[h]);
490                    bwd[(size_t) i * n_heads + h] = (uint32_t) (mb % C.vocab[h] + C.offset[h]);
491                }
492            }
493        }
494        long long d = 0;
495        for (size_t i = 0; i < fwd.size(); ++i)
496            if (fwd[i] != bwd[i]) ++d;
497        std::printf("  %-46s %s (%lld of %zu rows differ)\n",
498                    "cut propagates FORWARD vs only at the EOS position",
499                    d > 0 ? "yes" : "*** NO ***", d, fwd.size());
500        if (!d) ++bad;
501    }
502
503    // ============================ B. THE TABLE ============================
504    std::printf("\nB. the IQ4_NL table, against numpy reading the original GGUF\n");
505    if (!preflight_done && !table.open(gguf, err)) {
506        std::printf("  cannot open the PLE table: %s\n", err.c_str());
507        std::printf("\nple_parity: %d failures, TABLE AND BLOCK SKIPPED; partial diagnostic only\n", bad);
508        return selftest || bad ? 1 : 0;
509    }
510    std::printf("  %-46s %llu (expected %llu)\n", "rows", (unsigned long long) table.rows(),
511                (unsigned long long) o::kTableRows);
512    if (table.rows() != o::kTableRows) ++bad;
513
514    // The size identity is what makes the data offset FALSIFIABLE: the tensor must exactly fill the file from
515    // data_start.  Deriving the row count from the file size instead gives 320001538 rows and data_start 12,
516    // which is self-consistent and wrong.
517    {
518        const long long sz = file_size(gguf.c_str());
519        const long long need = (long long) o::kTableDataStart + (long long) table.rows() * k::PLE_ROW_BYTES;
520        const bool ok = sz == need;
521        std::printf("  %-46s %s (%lld vs %lld; data_start %llu)\n",
522                    "data_start + rows*90 == file size", ok ? "yes" : "*** NO ***", sz, need,
523                    (unsigned long long) o::kTableDataStart);
524        if (!ok) ++bad;
525    }
526
527    // Read the raw bytes through the mapped table by comparing against numpy's decode of the SAME offsets.
528    // 90 BYTES AT A TIME, not the whole file - see `file_size`'s note.
529    {
530        int probe_bad = 0;
531        for (int p = 0; p < o::kProbeCount; ++p) {
532            const uint32_t row = o::kProbeRows[p];
533            std::vector<float> got(k::PLE_HEAD_DIM);
534            table.read_row(row, got.data());
535            const std::vector<uint8_t> raw =
536                read_at(gguf.c_str(), (long long) o::kTableDataStart + (long long) row * k::PLE_ROW_BYTES,
537                        (size_t) k::PLE_ROW_BYTES);
538            if (raw.size() != (size_t) k::PLE_ROW_BYTES) { std::printf("  short read at row %u\n", row); ++probe_bad; continue; }
539            std::vector<float> ref(k::PLE_HEAD_DIM);
540            k::iq4nl_dequant_row(raw.data(), ref.data());
541            // the sampled values from the generator (numpy), which is the oracle proper.
542            // NOT `fmax`: it DISCARDS NaN, so a NaN element would leave these at 0 and the row would report
543            // a perfect match.  A plain comparison propagates the NaN into `ok`.
544            double head = 0, tail = 0, sum = 0;
545            for (int i = 0; i < 8; ++i) {
546                const double dh = std::fabs((double) got[i] - (double) o::kProbeHead[p][i]);
547                const double dt = std::fabs((double) got[k::PLE_HEAD_DIM - 8 + i] -
548                                            (double) o::kProbeTail[p][i]);
549                if (p == 0 && i == 0) { head = dh; tail = dt; }
550                else { head = (dh > head) ? dh : head; tail = (dt > tail) ? dt : tail; }
551            }
552            for (int i = 0; i < k::PLE_HEAD_DIM; ++i) sum += std::fabs((double) got[i]);
553            const long long nfg = nonfinite(got.data(), k::PLE_HEAD_DIM);
554            const bool ok = le(head, 0.0) && le(tail, 0.0) && le(std::fabs(sum - o::kProbeSum[p]), 1e-9) &&
555                            nfg == 0;
556            std::printf("  %-46s %s (row %u: head %.3e tail %.3e sum d %.3e, non-finite %lld)\n",
557                        p == 0 ? "row matches numpy's decode of the same bytes" : "  (same, another row)",
558                        ok ? "yes" : "*** NO ***", row, head, tail, std::fabs(sum - o::kProbeSum[p]), nfg);
559            if (!ok) ++probe_bad;
560            // and the two decoders must agree with each other bit for bit
561            for (int i = 0; i < k::PLE_HEAD_DIM; ++i)
562                if (got[i] != ref[i]) { std::printf("      byte-level decode differs at %d\n", i); ++probe_bad; break; }
563        }
564        bad += probe_bad;
565    }
566
567    // ---- the split-half nibble order must be observable ---------------------------------------------
568    {
569        const std::vector<uint8_t> raw =
570            read_at(gguf.c_str(), (long long) o::kTableDataStart +
571                                      (long long) o::kProbeRows[0] * k::PLE_ROW_BYTES,
572                    (size_t) k::PLE_ROW_BYTES);
573        std::vector<float> want(k::PLE_HEAD_DIM), inter(k::PLE_HEAD_DIM);
574        k::iq4nl_dequant_row(raw.data(), want.data());
575        deq_interleaved(raw.data(), inter.data());
576        const double rel = rel_l1(want.data(), inter.data(), k::PLE_HEAD_DIM);
577        const bool visible = gt(rel, 0.05);
578        std::printf("  %-46s %s (%.2f%% apart; generator says %.4f)\n",
579                    "split-half vs INTERLEAVED nibbles observable",
580                    visible ? "yes" : "*** NO ***", rel * 100, (double) o::kInterleavedSeparation);
581        if (!visible) ++bad;
582    }
583
584    // ---- and reading at file offset 0 instead of data_start must be observable ----------------------
585    {
586        const std::vector<uint8_t> at_ds = read_at(gguf.c_str(), (long long) o::kTableDataStart,
587                                                   (size_t) k::PLE_ROW_BYTES);
588        const std::vector<uint8_t> at_0 = read_at(gguf.c_str(), 0, (size_t) k::PLE_ROW_BYTES);
589        std::vector<float> ok_v(k::PLE_HEAD_DIM), at0(k::PLE_HEAD_DIM);
590        k::iq4nl_dequant_row(at_ds.data(), ok_v.data());
591        k::iq4nl_dequant_row(at_0.data(), at0.data());
592        const double rel = rel_l1(ok_v.data(), at0.data(), k::PLE_HEAD_DIM);
593        const bool visible = gt(rel, 0.05);
594        std::printf("  %-46s %s (%.2f%% apart)\n",
595                    "data_start 192 vs file offset 0 observable", visible ? "yes" : "*** NO ***", rel * 100);
596        if (!visible) ++bad;
597    }
598
599    // ---- head-slowest flatten ----------------------------------------------------------------------
600    {
601        const uint32_t rows16[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
602        std::vector<float> emb(k::NG_N_EMBD), one(k::PLE_HEAD_DIM);
603        table.gather(rows16, emb.data());
604        bool blockwise = true;
605        for (int h = 0; h < k::PLE_N_HEADS && blockwise; ++h) {
606            table.read_row((uint32_t) h, one.data());
607            for (int d = 0; d < k::PLE_HEAD_DIM; ++d)
608                if (emb[h * k::PLE_HEAD_DIM + d] != one[d]) { blockwise = false; break; }
609        }
610        // the rival: head-fastest, element (d,h) at d*16+h - a real transpose, not a reshape
611        std::vector<float> fast(k::NG_N_EMBD);
612        for (int d = 0; d < k::PLE_HEAD_DIM; ++d)
613            for (int h = 0; h < k::PLE_N_HEADS; ++h) fast[d * k::PLE_N_HEADS + h] = emb[h * k::PLE_HEAD_DIM + d];
614        long long diff = 0;
615        for (int i = 0; i < k::NG_N_EMBD; ++i)
616            if (fast[i] != emb[i]) ++diff;
617        std::printf("  %-46s %s (head h occupies [h*160,(h+1)*160))\n", "gather is head-slowest",
618                    blockwise ? "yes" : "*** NO ***");
619        std::printf("  %-46s %s (%lld of %d elements differ)\n", "head-fastest would differ",
620                    diff > 0 ? "yes" : "*** NO ***", diff, k::NG_N_EMBD);
621        if (!blockwise || !diff) ++bad;
622    }
623
624    // ============================ C. THE BLOCK ============================
625    std::printf("\nC. the PLE block, against ggml's own graph (ple_in.bin / ple_out.bin)\n");
626    if (!preflight_done && !load_capture(in_bin.c_str(), out_bin.c_str(), cap)) {
627        std::printf("  cannot load %s / %s\n", in_bin.c_str(), out_bin.c_str());
628        std::printf("\nple_parity: %d failures, BLOCK SKIPPED; partial diagnostic only\n", bad);
629        return selftest || bad ? 1 : 0;
630    }
631    std::printf("  capture: n_embd %d, hc %d, nt %d, kern %d, dil %d, eps %g\n", cap.n_embd, cap.hc, cap.nt,
632                cap.kern, cap.dil, (double) cap.eps);
633    if (cap.n_embd != k::NG_N_EMBD || cap.hc != k::NG_HC || cap.kern != k::PLE_CONV_KERNEL ||
634        cap.dil != k::NGRAM_SIZE) {
635        std::printf("  *** the capture's geometry is not the artifact's ***\n");
636        return 1;
637    }
638
639    if (!k::ple_block_available()) {
640        std::printf("  no CUDA device; the block SKIPPED, not passed.\n");
641        std::printf("\nple_parity: %d failures, BLOCK SKIPPED\n", bad);
642        return selftest || bad ? 1 : 0;
643    }
644
645    // ---- the two quantized weights, from the PACK, not from the capture.
646    //      The capture holds `w_key` already dequantized to f32; the kernel needs the CODES AND SCALES, and
647    //      re-quantizing the f32 would be a different tensor.  Reading the pack is right and it was checked:
648    //      the pack's decode of row 0 reproduces the capture's w_key row 0 exactly (see the round entry).
649    //      Only the two regions are read, not all 5.4 GB of `dense.bin`.
650    std::vector<uint8_t> key_codes =
651        read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyCodesOffset, (size_t) o::kKeyCodesBytes);
652    const std::vector<uint8_t> raw_scales =
653        read_at((pack + "/dense.bin").c_str(), (long long) o::kKeyScalesOffset, (size_t) o::kKeyScalesBytes);
654    const std::vector<uint8_t> raw_value =
655        read_at((pack + "/dense.bin").c_str(), (long long) o::kValueOffset, (size_t) o::kValueBytes);
656    if (key_codes.empty() || raw_scales.empty() || raw_value.empty()) {
657        std::printf("  cannot read the ple_key/ple_value regions from %s/dense.bin\n", pack.c_str());
658        return 2;
659    }
660    // fp16 -> f32 for the scales, which is what every S-form kernel in this project expects
661    const size_t n_scales = raw_scales.size() / 2;
662    std::vector<float> key_scales(n_scales);
663    for (size_t i = 0; i < n_scales; ++i) {
664        uint16_t h;
665        std::memcpy(&h, raw_scales.data() + i * 2, 2);
666        key_scales[i] = k::f32_from_f16(h);
667    }
668    // ple_value is BF16 promoted to 32 bits in the pack; take the high half, which is exact
669    std::vector<uint16_t> value_bf16(raw_value.size() / 4);
670    for (size_t i = 0; i < value_bf16.size(); ++i) {
671        uint32_t u;
672        std::memcpy(&u, raw_value.data() + i * 4, 4);
673        value_bf16[i] = (uint16_t) (u >> 16);
674    }
675    // ple_conv1d is F16 in the pack; the capture holds it as f32 in ggml order, and the kernel wants F16
676    std::vector<uint16_t> conv1d_f16(cap.w_conv.size());
677    for (size_t i = 0; i < conv1d_f16.size(); ++i) conv1d_f16[i] = k::f16_from_f32(cap.w_conv[i]);
678
679    // ---- the check that the two sources describe the SAME weights ---------------------------------
680    {
681        // dequantize key row 0 with the canonical rule and compare to the capture's w_key row 0.
682        // NOT `fmax`, for the reason above: it discards NaN, so a NaN would leave `worst` at 0 and report a
683        // perfect match.
684        double worst = 0;
685        bool first = true;
686        long long nf = 0;
687        for (int d = 0; d < k::NG_N_EMBD; ++d) {
688            const uint8_t byte = key_codes[d / 4];
689            const int code = (byte >> ((d % 4) * 2)) & 3;
690            const float v = (float) (code + (-1)) * key_scales[d / 64];
691            if (!std::isfinite(v) || !std::isfinite(cap.w_key[d])) { ++nf; continue; }
692            const double diff = std::fabs((double) v - (double) cap.w_key[d]);
693            if (first) { worst = diff; first = false; }
694            else worst = (diff > worst) ? diff : worst;
695        }
696        std::printf("  %-46s %s (worst |d| %.3e, non-finite %lld)\n",
697                    "pack ple_key row 0 == the capture's w_key row 0",
698                    (le(worst, 0.0) && nf == 0) ? "yes" : "*** NO ***", worst, nf);
699        if (!le(worst, 0.0) || nf) ++bad;
700    }
701
702    // ---- run the block for both tokens of the capture ---------------------------------------------
703    const size_t hcd = (size_t) k::NG_HC_DIM, nd = (size_t) k::NG_N_EMBD;
704    std::vector<float> dev_key(hcd), dev_value(nd), dev_gate(k::NG_HC), dev_gated(hcd), dev_norm(hcd),
705        dev_conv(hcd), dev_res(hcd);
706    float *d_emb = nullptr, *d_hid = nullptr, *d_hist = nullptr, *d_nk = nullptr, *d_nq = nullptr,
707          *d_nc = nullptr, *d_ck = nullptr, *d_cv = nullptr, *d_cn = nullptr, *d_cr = nullptr;
708    uint8_t* d_kc = nullptr;
709    uint16_t *d_vb = nullptr, *d_c1 = nullptr;
710    float *d_g = nullptr, *d_v = nullptr, *d_gd = nullptr, *d_nm = nullptr, *d_co = nullptr;
711    ck(DPCT_CHECK_ERROR(d_emb = (float *)sycl::malloc_device(
712                            nd * 4, dpct::get_in_order_queue())),
713       "emb");
714    ck(DPCT_CHECK_ERROR(d_hid = (float *)sycl::malloc_device(
715                            hcd * 4, dpct::get_in_order_queue())),
716       "hid");
717    ck(DPCT_CHECK_ERROR(
718           d_hist = (float *)sycl::malloc_device((size_t)k::NG_HIST * hcd * 4,
719                                                 dpct::get_in_order_queue())),
720       "hist");
721    ck(DPCT_CHECK_ERROR(d_nk = (float *)sycl::malloc_device(
722                            hcd * 4, dpct::get_in_order_queue())),
723       "nk");
724    ck(DPCT_CHECK_ERROR(d_nq = (float *)sycl::malloc_device(
725                            hcd * 4, dpct::get_in_order_queue())),
726       "nq");
727    ck(DPCT_CHECK_ERROR(d_nc = (float *)sycl::malloc_device(
728                            hcd * 4, dpct::get_in_order_queue())),
729       "nc");
730    ck(DPCT_CHECK_ERROR(d_kc = (uint8_t *)sycl::malloc_device(
731                            key_codes.size(), dpct::get_in_order_queue())),
732       "kc");
733    ck(DPCT_CHECK_ERROR(d_vb = (uint16_t *)sycl::malloc_device(
734                            value_bf16.size() * 2, dpct::get_in_order_queue())),
735       "vb");
736    ck(DPCT_CHECK_ERROR(d_c1 = (uint16_t *)sycl::malloc_device(
737                            conv1d_f16.size() * 2, dpct::get_in_order_queue())),
738       "c1");
739    ck(DPCT_CHECK_ERROR(d_g = (float *)sycl::malloc_device(
740                            k::NG_HC * 4, dpct::get_in_order_queue())),
741       "g");
742    ck(DPCT_CHECK_ERROR(d_v = (float *)sycl::malloc_device(
743                            nd * 4, dpct::get_in_order_queue())),
744       "v");
745    ck(DPCT_CHECK_ERROR(d_gd = (float *)sycl::malloc_device(
746                            hcd * 4, dpct::get_in_order_queue())),
747       "gd");
748    ck(DPCT_CHECK_ERROR(d_nm = (float *)sycl::malloc_device(
749                            hcd * 4, dpct::get_in_order_queue())),
750       "nm");
751    ck(DPCT_CHECK_ERROR(d_co = (float *)sycl::malloc_device(
752                            hcd * 4, dpct::get_in_order_queue())),
753       "co");
754    ck(DPCT_CHECK_ERROR(d_ck = (float *)sycl::malloc_device(
755                            hcd * 4, dpct::get_in_order_queue())),
756       "ck");
757    ck(DPCT_CHECK_ERROR(d_cv = (float *)sycl::malloc_device(
758                            nd * 4, dpct::get_in_order_queue())),
759       "cv");
760    ck(DPCT_CHECK_ERROR(d_cn = (float *)sycl::malloc_device(
761                            hcd * 4, dpct::get_in_order_queue())),
762       "cn");
763    ck(DPCT_CHECK_ERROR(d_cr = (float *)sycl::malloc_device(
764                            hcd * 4, dpct::get_in_order_queue())),
765       "cr");
766    /*
767    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
768    the original code the source host memory is pageable memory. If the memory
769    is not pageable, call wait() on event return by memcpy API to ensure
770    synchronization behavior.
771    */
772    ck(DPCT_CHECK_ERROR(
773           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_nk, cap.w_nk.data(), hcd * 4).wait()),
774       "cnk");
775    /*
776    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
777    the original code the source host memory is pageable memory. If the memory
778    is not pageable, call wait() on event return by memcpy API to ensure
779    synchronization behavior.
780    */
781    ck(DPCT_CHECK_ERROR(
782           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_nq, cap.w_nq.data(), hcd * 4).wait()),
783       "cnq");
784    /*
785    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
786    the original code the source host memory is pageable memory. If the memory
787    is not pageable, call wait() on event return by memcpy API to ensure
788    synchronization behavior.
789    */
790    ck(DPCT_CHECK_ERROR(
791           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_nc, cap.w_nc.data(), hcd * 4).wait()),
792       "cnc");
793    /*
794    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
795    the original code the source host memory is pageable memory. If the memory
796    is not pageable, call wait() on event return by memcpy API to ensure
797    synchronization behavior.
798    */
799    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
800           d_kc, key_codes.data(), key_codes.size()).wait()),
801       "ckc");
802    /*
803    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
804    the original code the source host memory is pageable memory. If the memory
805    is not pageable, call wait() on event return by memcpy API to ensure
806    synchronization behavior.
807    */
808    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
809           d_vb, value_bf16.data(), value_bf16.size() * 2).wait()),
810       "cvb");
811    /*
812    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
813    the original code the source host memory is pageable memory. If the memory
814    is not pageable, call wait() on event return by memcpy API to ensure
815    synchronization behavior.
816    */
817    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
818           d_c1, conv1d_f16.data(), conv1d_f16.size() * 2).wait()),
819       "cc1");
820
821    k::PleWeights w{};
822    w.key_codes = d_kc;
823    w.key_scales = key_scales.data();   // uploaded per call below so the pointer is a device one
824    w.value_bf16 = d_vb;
825    w.norm_key = d_nk;
826    w.norm_query = d_nq;
827    w.norm_conv = d_nc;
828    w.conv1d_f16 = d_c1;
829    float* d_ks = nullptr;
830    ck(DPCT_CHECK_ERROR(d_ks = (float *)sycl::malloc_device(
831                            key_scales.size() * 4, dpct::get_in_order_queue())),
832       "ks");
833    /*
834    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
835    the original code the source host memory is pageable memory. If the memory
836    is not pageable, call wait() on event return by memcpy API to ensure
837    synchronization behavior.
838    */
839    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
840           d_ks, key_scales.data(), key_scales.size() * 4).wait()),
841       "cks");
842    w.key_scales = d_ks;
843
844    // Per-stage comparison.  Each stage the oracle records is a separate line, so a mismatch says WHICH part
845    // of the block is wrong rather than only that the sum is.  The oracle writes each array token-major, so
846    // every slice is an explicit (offset, count) pair - deriving the offset from the stage's NAME, which the
847    // first version of this did, is a fixture that breaks the moment a name changes.
848    struct Stage { const char* name; const std::vector<float>* got; const std::vector<float>* all;
849                   size_t offset; size_t n; };
850    double worst_all = 0;
851
852    // THE CONV HISTORY ADVANCES BETWEEN TOKENS, and getting this wrong is why token 1 compared badly at
853    // first.  The capture is a TWO-TOKEN ubatch: ggml pads `[hist(9) | normalized(0..nt-1)]` ONCE and the conv
854    // reads rows `t+0, t+3, t+6, t+9` for output position t.  So token 1's window is rows 1,4,7 of the SAME
855    // history plus row 10 - which is token 1's own normalized - i.e. the state slides by one NORMALIZED row
856    // per token.  Feeding both tokens the original history compares my block's t=0 against ggml's t=1, and
857    // both my kernel and my host reference made the same mistake, so they agreed with each other and only the
858    // oracle could see it.
859    //
860    // ggml layout for the state is `ne=(hist, hc_dim)`: flat = row + NG_HIST*channel.
861    std::vector<float> hist_state = cap.hist;
862    for (int t = 0; t < cap.nt; ++t) {
863        /*
864        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
865        assuming in the original code the source host memory is pageable memory.
866        If the memory is not pageable, call wait() on event return by memcpy API
867        to ensure synchronization behavior.
868        */
869        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
870               d_emb, cap.emb.data() + (size_t)t * nd, nd * 4).wait()),
871           "cemb");
872        /*
873        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
874        assuming in the original code the source host memory is pageable memory.
875        If the memory is not pageable, call wait() on event return by memcpy API
876        to ensure synchronization behavior.
877        */
878        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
879               d_hid, cap.hidden.data() + (size_t)t * hcd, hcd * 4).wait()),
880           "chid");
881        /*
882        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
883        assuming in the original code the source host memory is pageable memory.
884        If the memory is not pageable, call wait() on event return by memcpy API
885        to ensure synchronization behavior.
886        */
887        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
888               d_hist, hist_state.data(), (size_t)k::NG_HIST * hcd * 4).wait()),
889           "chist");
890        k::PleOut out{};
891        out.key = d_ck; out.value = d_cv; out.gate = d_g; out.gated = d_gd;
892        out.normalized = d_nm; out.conv = d_co; out.result = d_cr;
893        // the workspace is the caller's, and the sync the block used to do is now the caller's too
894    void* ple_ws = nullptr;
895    ck(DPCT_CHECK_ERROR(
896           ple_ws = (void *)sycl::malloc_device(k::ple_block_scratch_bytes(),
897                                                dpct::get_in_order_queue())),
898       "ple_block scratch");
899    if (t == 0) {
900        const size_t bytes = (size_t) k::ple_block_scratch_bytes();
901        ck(DPCT_CHECK_ERROR(
902               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(ple_ws, 0xa5, bytes).wait()),
903           "PLE prelaunch guard sentinel");
904        const struct AliasCase { float* k::PleOut::* field; size_t offset; } cases[] = {
905            {&k::PleOut::key, 0}, {&k::PleOut::value, hcd}, {&k::PleOut::gate, hcd + nd},
906            {&k::PleOut::gated, hcd + nd + (size_t) k::NG_HC},
907            {&k::PleOut::normalized, 2 * hcd + nd + (size_t) k::NG_HC},
908            {&k::PleOut::conv, 3 * hcd + nd + (size_t) k::NG_HC}, {&k::PleOut::result, 0}
909        };
910        int refused = 0;
911        for (const auto& item : cases) {
912            k::PleOut invalid = out;
913            invalid.*(item.field) = static_cast<float*>(ple_ws) + item.offset;
914            try { k::ple_block(d_emb, d_hid, d_hist, w, invalid, ple_ws, nullptr); }
915            catch (const std::invalid_argument&) { ++refused; }
916        }
917        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
918           "PLE guard no-launch sync");
919        std::vector<uint8_t> sentinel(bytes);
920        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
921                                .memcpy(sentinel.data(), ple_ws, bytes)
922                                .wait()),
923           "PLE guard sentinel readback");
924        const bool unchanged = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t b) { return b == 0xa5; });
925        const bool rejected = refused == 7 && unchanged;
926        std::printf("  PLE old caller output offsets rejected before launch: %s (%d/7, scratch %s)\n",
927                    rejected ? "pass" : "FAIL", refused, unchanged ? "unchanged" : "CORRUPTED");
928        if (!rejected) ++bad;
929    }
930    k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr);
931    ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
932       "ple_block sync");
933        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
934                                .memcpy(dev_key.data(), d_ck, hcd * 4)
935                                .wait()),
936           "rck");
937        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
938                                .memcpy(dev_value.data(), d_cv, nd * 4)
939                                .wait()),
940           "rcv");
941        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
942                                .memcpy(dev_gate.data(), d_g, k::NG_HC * 4)
943                                .wait()),
944           "rg");
945        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
946                                .memcpy(dev_gated.data(), d_gd, hcd * 4)
947                                .wait()),
948           "rgd");
949        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
950                                .memcpy(dev_norm.data(), d_nm, hcd * 4)
951                                .wait()),
952           "rnm");
953        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
954                                .memcpy(dev_conv.data(), d_co, hcd * 4)
955                                .wait()),
956           "rco");
957        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
958                                .memcpy(dev_res.data(), d_cr, hcd * 4)
959                                .wait()),
960           "rcr");
961
962        const size_t ok_ = (size_t) t * hcd, ov = (size_t) t * nd, og = (size_t) t * (size_t) k::NG_HC;
963        const Stage stages[] = {
964            {"key        (grouped_norm of ple_key @ emb)", &dev_key, &cap.key, ok_, hcd},
965            {"value      (ple_value @ emb, BF16)", &dev_value, &cap.value, ov, nd},
966            {"gate       (signed sqrt, sigmoid)", &dev_gate, &cap.gate, og, (size_t) k::NG_HC},
967            {"gated      (value broadcast * gate)", &dev_gated, &cap.gated, ok_, hcd},
968            {"normalized (grouped_norm(gated, ple_norm_conv))", &dev_norm, &cap.normalized, ok_, hcd},
969            {"conv_out   (dilated conv, then SiLU)", &dev_conv, &cap.conv_out, ok_, hcd},
970            {"result     (hidden + gated + conv)", &dev_res, &cap.result, ok_, hcd},
971        };
972        for (const Stage& s : stages) {
973            std::vector<float> want(s.all->begin() + (long long) s.offset,
974                                    s.all->begin() + (long long) (s.offset + s.n));
975            double mag = 0;
976            long long nf = 0;
977            const double rel = rel_l1(want.data(), s.got->data(), s.n, &mag, &nf);
978            // NaN-SAFE: `rel > worst_all` is false for NaN, so `fmax` here would silently report a perfect
979            // score for a fixture full of NaNs - round 197's exact failure.
980            worst_all = (rel > worst_all) ? rel : worst_all;
981            if (nf) worst_all = std::nan("");
982            const bool last = (std::strncmp(s.name, "result", 6) == 0);
983            std::printf("  token %d %-46s rel %.3e   (mean |ref| %.4f, non-finite %lld)%s\n", t, s.name, rel,
984                        mag, nf, last && !le(rel, 1e-2) ? "   *** over 1e-2 ***" : "");
985            // TOLERANCE, and what sets it: this comparison is the GPU against a capture whose weights are
986            // F32, so ggml performed NO activation conversion while the kernel applies the CONTRACT (Q8_0
987            // for the Q2_0 weight, BF16 for the BF16 one).  The contract's per-element cost is 2^-9 = 1.95e-3
988            // for BF16 and ~0.4% for Q8_0, so the OUTPUT difference is ~2e-3 wherever there is no
989            // cancellation and larger where there is - `conv_out` cancels by ~77x and is the one stage that
990            // exceeds it.  `result` is the quantity that matters and 1e-2 is five times the contract's own
991            // per-element size, so it is a bound on "the contract and nothing else", not a judgement call.
992            // The HOST reference below uses the capture's own F32 weights and is asserted at 1e-4, which is
993            // what proves the difference here IS the contract.
994            if (last && !le(rel, 1e-2)) ++bad;
995        }
996
997        if (t == 0) {
998            // Deliberate BF16 halfway values make the value projection's activation precision visible.
999            // The scalar reference uses the actual packed BF16 weight bits and unrounded F32 inputs.
1000            std::vector<float> witness(nd), reference_value(nd), native_value(nd), native_result(hcd), replay(hcd);
1001            for (size_t i = 0; i < nd; ++i) witness[i] = i % 7 == 0 ? 1.00390625f : -0.501953125f;
1002            for (size_t row = 0; row < nd; ++row) {
1003                double sum = 0.0;
1004                for (size_t col = 0; col < nd; ++col) {
1005                    const uint32_t bits = uint32_t(value_bf16[row * nd + col]) << 16;
1006                    float weight;
1007                    std::memcpy(&weight, &bits, sizeof(weight));
1008                    sum += double(weight) * witness[col];
1009                }
1010                reference_value[row] = float(sum);
1011            }
1012            /*
1013            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1014            assuming in the original code the source host memory is pageable
1015            memory. If the memory is not pageable, call wait() on event return
1016            by memcpy API to ensure synchronization behavior.
1017            */
1018            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1019                   d_emb, witness.data(), nd * sizeof(float)).wait()),
1020               "native PLE witness");
1021            k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr);
1022            ck(DPCT_CHECK_ERROR(
1023                   dpct::get_current_device().queues_wait_and_throw()),
1024               "legacy PLE witness sync");
1025            std::vector<float> legacy_value(nd);
1026            ck(DPCT_CHECK_ERROR(
1027                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1028                       .memcpy(legacy_value.data(), d_cv, nd * sizeof(float))
1029                       .wait()),
1030               "legacy PLE witness value");
1031            dpct::queue_ptr stream;
1032            /*
1033            DPCT1025: The SYCL queue is created ignoring the flag and
1034            priority options.
1035            */
1036            ck(DPCT_CHECK_ERROR(
1037                   stream = dpct::get_current_device().create_queue(true)),
1038               "native PLE stream");
1039            k::ple_set_native_bf16(true);
1040            k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream);
1041            ck(DPCT_CHECK_ERROR(stream->wait()), "native PLE sync");
1042            ck(DPCT_CHECK_ERROR(
1043                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1044                       .memcpy(native_value.data(), d_cv, nd * sizeof(float))
1045                       .wait()),
1046               "native PLE value");
1047            ck(DPCT_CHECK_ERROR(
1048                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1049                       .memcpy(native_result.data(), d_cr, hcd * sizeof(float))
1050                       .wait()),
1051               "native PLE result");
1052            long long nf = 0;
1053            const double rel = rel_l1(reference_value.data(), native_value.data(), nd, nullptr, &nf);
1054            const double separation = rel_l1(native_value.data(), legacy_value.data(), nd);
1055            const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5);
1056            std::printf("  native PLE value: %s (ref rel %.3e, BF16 separation %.3e)\n",
1057                        correct ? "pass" : "FAIL", rel, separation);
1058            if (!correct) ++bad;
1059            dpct::experimental::command_graph_ptr graph;
1060            dpct::experimental::command_graph_exec_ptr executable;
1061            ck(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(stream)),
1062               "native PLE capture");
1063            k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, stream);
1064            ck(DPCT_CHECK_ERROR(
1065                   dpct::experimental::end_recording(stream, &graph)),
1066               "native PLE capture end");
1067            ck(DPCT_CHECK_ERROR(
1068                   executable =
1069                       new sycl::ext::oneapi::experimental::command_graph<
1070                           sycl::ext::oneapi::experimental::graph_state::
1071                               executable>(graph->finalize())),
1072               "native PLE instantiate");
1073            k::ple_set_native_bf16(false);
1074            ck(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*executable)),
1075               "native PLE replay");
1076            ck(DPCT_CHECK_ERROR(stream->wait()), "native PLE replay sync");
1077            ck(DPCT_CHECK_ERROR(
1078                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1079                       .memcpy(replay.data(), d_cr, hcd * sizeof(float))
1080                       .wait()),
1081               "native PLE replay result");
1082            const bool captured = std::memcmp(native_result.data(), replay.data(), hcd * sizeof(float)) == 0;
1083            std::printf("  native PLE captured selection: %s\n", captured ? "byte-identical" : "FAIL");
1084            if (!captured) ++bad;
1085            ck(DPCT_CHECK_ERROR(delete (executable)),
1086               "native PLE graph exec destroy");
1087            ck(DPCT_CHECK_ERROR(delete (graph)), "native PLE graph destroy");
1088            ck(DPCT_CHECK_ERROR(
1089                   dpct::get_current_device().destroy_queue(stream)),
1090               "native PLE stream destroy");
1091            /*
1092            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1093            assuming in the original code the source host memory is pageable
1094            memory. If the memory is not pageable, call wait() on event return
1095            by memcpy API to ensure synchronization behavior.
1096            */
1097            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1098                   d_emb, cap.emb.data(), nd * sizeof(float)).wait()),
1099               "restore PLE embedding");
1100            k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr);
1101            ck(DPCT_CHECK_ERROR(
1102                   dpct::get_current_device().queues_wait_and_throw()),
1103               "restored PLE sync");
1104            ck(DPCT_CHECK_ERROR(
1105                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1106                       .memcpy(replay.data(), d_cr, hcd * sizeof(float))
1107                       .wait()),
1108               "restored PLE result");
1109            const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * sizeof(float)) == 0;
1110            std::printf("  restored PLE default: %s\n", restored ? "byte-identical" : "FAIL");
1111            if (!restored) ++bad;
1112        }
1113
1114        if (t == 0) {
1115            // This checks native-projection wiring and graph lifetime, independently
1116            // of the legacy CPU/F32 structural capture. Actual Q2_0 arithmetic is
1117            // checked separately by native_mmvq_parity against the pinned CUDA DLL.
1118            const size_t blocks = n_scales, native_bytes = blocks * 18, guard = 64;
1119            const size_t qbytes = k::native_q8_1_bytes(k::NG_N_EMBD);
1120            std::vector<uint8_t> native_key(native_bytes);
1121            for (size_t b = 0; b < blocks; ++b) {
1122                std::memcpy(native_key.data() + b * 18, raw_scales.data() + b * 2, 2);
1123                std::memcpy(native_key.data() + b * 18 + 2, key_codes.data() + b * 16, 16);
1124            }
1125            void *native_storage = nullptr, *q_storage = nullptr;
1126            float* raw_projection = nullptr;
1127            ck(DPCT_CHECK_ERROR(
1128                   native_storage = (void *)sycl::malloc_device(
1129                       native_bytes + 2 * guard, dpct::get_in_order_queue())),
1130               "native PLE weights");
1131            ck(DPCT_CHECK_ERROR(
1132                   q_storage = (void *)sycl::malloc_device(
1133                       qbytes + 2 * guard, dpct::get_in_order_queue())),
1134               "native PLE q8 scratch");
1135            ck(DPCT_CHECK_ERROR(raw_projection = (float *)sycl::malloc_device(
1136                                    hcd * 4, dpct::get_in_order_queue())),
1137               "native PLE raw projection");
1138            ck(DPCT_CHECK_ERROR(
1139                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1140                       .memset(native_storage, 0xa5, native_bytes + 2 * guard)
1141                       .wait()),
1142               "native PLE weight guards");
1143            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1144                                    .memset(q_storage, 0xa5, qbytes + 2 * guard)
1145                                    .wait()),
1146               "native PLE q8 guards");
1147            void* native_data = static_cast<uint8_t*>(native_storage) + guard;
1148            void* native_q = static_cast<uint8_t*>(q_storage) + guard;
1149            /*
1150            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1151            assuming in the original code the source host memory is pageable
1152            memory. If the memory is not pageable, call wait() on event return
1153            by memcpy API to ensure synchronization behavior.
1154            */
1155            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1156                   native_data, native_key.data(), native_bytes).wait()),
1157               "native PLE weights upload");
1158            k::PleWeights nw = w;
1159            nw.key_native_data = native_data; nw.key_native_type = 42; nw.key_native_q8_1 = native_q;
1160            dpct::queue_ptr stream;
1161            /*
1162            DPCT1025: The SYCL queue is created ignoring the flag and
1163            priority options.
1164            */
1165            ck(DPCT_CHECK_ERROR(
1166                   stream = dpct::get_current_device().create_queue(true)),
1167               "native PLE key stream");
1168            const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes();
1169            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1170                                    .memset(ple_ws, 0xa5, workspace_bytes)
1171                                    .wait()),
1172               "native PLE no-launch sentinel");
1173            int refused = 0;
1174            for (int c = 0; c < 9; ++c) {
1175                auto invalid = nw;
1176                if (c == 0) invalid.key_native_type = 11;
1177                if (c == 1) invalid.key_native_q8_1 = nullptr;
1178                if (c == 3) invalid.key_native_q8_1 = ple_ws;
1179                if (c == 4) invalid.key_native_q8_1 = d_emb;
1180                if (c == 5) invalid.key_native_q8_1 = out.key;
1181                if (c == 6) invalid.key_native_q8_1 = static_cast<uint8_t*>(native_q) + 1;
1182                if (c == 7) invalid.key_native_data = static_cast<uint8_t*>(native_data) + 1;
1183                if (c == 8) invalid.key_native_q8_1 = native_data;
1184                try {
1185                    k::ple_block(d_emb, d_hid, d_hist, invalid, out, ple_ws,
1186                                 c == 2 ? &dpct::get_in_order_queue() : stream);
1187                }
1188                catch (const std::invalid_argument&) { ++refused; }
1189            }
1190            ck(DPCT_CHECK_ERROR(stream->wait()), "native PLE refusal sync");
1191            std::vector<uint8_t> sentinel(workspace_bytes);
1192            ck(DPCT_CHECK_ERROR(
1193                   (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1194                       .memcpy(sentinel.data(), ple_ws, workspace_bytes)
1195                       .wait()),
1196               "native PLE refusal sentinel");
1197            const bool untouched = std::all_of(sentinel.begin(), sentinel.end(), [](uint8_t x) { return x == 0xa5; });
1198            std::printf("  native PLE key prelaunch guards: %s (%d/9, workspace %s)\n",
1199                        refused == 9 && untouched ? "pass" : "FAIL", refused, untouched ? "unchanged" : "changed");
1200            if (refused != 9 || !untouched) ++bad;
1201            dpct::experimental::command_graph_ptr graph = nullptr;
1202                dpct::experimental::command_graph_exec_ptr executable = nullptr;
1203            std::vector<float> projected(hcd), normalized(hcd), actual_key(hcd), actual_result(hcd), replay(hcd);
1204            for (int p = 0; p < std::min(cap.nt, 2); ++p) {
1205                /*
1206                DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1207                assuming in the original code the source host memory is pageable
1208                memory. If the memory is not pageable, call wait() on event
1209                return by memcpy API to ensure synchronization behavior.
1210                */
1211                ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1212                       d_emb, cap.emb.data() + (size_t)p * nd, nd * 4).wait()),
1213                   "native PLE key input");
1214                k::native_q2_0_f32(native_data, d_emb, native_q, raw_projection, k::NG_N_EMBD, k::NG_HC_DIM, 1, stream);
1215                ck(DPCT_CHECK_ERROR(stream->wait()), "native PLE raw key sync");
1216                ck(DPCT_CHECK_ERROR(
1217                       (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1218                           .memcpy(projected.data(), raw_projection, hcd * 4)
1219                           .wait()),
1220                   "native PLE raw key read");
1221                for (int c = 0; c < k::NG_HC; ++c) {
1222                    double sum = 0;
1223                    for (size_t j = 0; j < nd; ++j) { const float v = projected[(size_t) c * nd + j]; sum += double(v * v); }
1224                    const float scale = 1.0f / std::sqrt(float(sum / double(nd)) + k::NG_RMS_EPS);
1225                    for (size_t j = 0; j < nd; ++j) { const size_t i = (size_t) c * nd + j; normalized[i] = projected[i] * scale * cap.w_nk[i]; }
1226                }
1227                k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream);
1228                ck(DPCT_CHECK_ERROR(stream->wait()),
1229                   "native PLE key direct sync");
1230                ck(DPCT_CHECK_ERROR(
1231                       (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1232                           .memcpy(actual_key.data(), d_ck, hcd * 4)
1233                           .wait()),
1234                   "native PLE key read");
1235                ck(DPCT_CHECK_ERROR(
1236                       (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1237                           .memcpy(actual_result.data(), d_cr, hcd * 4)
1238                           .wait()),
1239                   "native PLE result read");
1240                const double rel = rel_l1(normalized.data(), actual_key.data(), hcd);
1241                const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;
1242                std::printf("  native PLE key projection->existing norm input %d: %s (rel %.3e)\n", p, wired ? "pass" : "FAIL", rel);
1243                if (!wired) ++bad;
1244                if (p == 0) {
1245                    ck(DPCT_CHECK_ERROR(
1246                           dpct::experimental::begin_recording(stream)),
1247                       "native PLE key capture");
1248                    k::ple_block(d_emb, d_hid, d_hist, nw, out, ple_ws, stream);
1249                    ck(DPCT_CHECK_ERROR(
1250                           dpct::experimental::end_recording(stream, &graph)),
1251                       "native PLE key capture end");
1252                    ck(DPCT_CHECK_ERROR(
1253                           executable = new sycl::ext::oneapi::experimental::
1254                               command_graph<sycl::ext::oneapi::experimental::
1255                                                 graph_state::executable>(
1256                                   graph->finalize())),
1257                       "native PLE key instantiate");
1258                }
1259                nw.key_native_data = nullptr; // graph selection must survive descriptor changes
1260                for (int repeat = 0; repeat < 2; ++repeat) {
1261                    ck(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*executable)),
1262                       "native PLE key replay");
1263                    ck(DPCT_CHECK_ERROR(stream->wait()),
1264                       "native PLE key replay sync");
1265                    ck(DPCT_CHECK_ERROR(
1266                           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1267                               .memcpy(replay.data(), d_cr, hcd * 4)
1268                               .wait()),
1269                       "native PLE key replay read");
1270                    if (std::memcmp(actual_result.data(), replay.data(), hcd * 4) != 0) ++bad;
1271                }
1272                nw.key_native_data = native_data;
1273            }
1274            ck(DPCT_CHECK_ERROR(delete (executable)),
1275               "native PLE key executable destroy");
1276            ck(DPCT_CHECK_ERROR(delete (graph)),
1277               "native PLE key graph destroy");
1278            for (int b = 0; b < 2; ++b) {
1279                const void* storage = b == 0 ? native_storage : q_storage;
1280                const size_t payload = b == 0 ? native_bytes : qbytes;
1281                std::vector<uint8_t> ends(2 * guard);
1282                ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1283                                        .memcpy(ends.data(), storage, guard)
1284                                        .wait()),
1285                   "native PLE prefix guard");
1286                ck(DPCT_CHECK_ERROR(
1287                       (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1288                           .memcpy(ends.data() + guard,
1289                                   static_cast<const uint8_t *>(storage) +
1290                                       guard + payload,
1291                                   guard)
1292                           .wait()),
1293                   "native PLE suffix guard");
1294                if (!std::all_of(ends.begin(), ends.end(), [](uint8_t x) { return x == 0xa5; })) ++bad;
1295            }
1296            ck(DPCT_CHECK_ERROR(
1297                   dpct::get_current_device().destroy_queue(stream)),
1298               "native PLE key stream destroy");
1299            sycl::free(raw_projection, dpct::get_in_order_queue());
1300                sycl::free(q_storage, dpct::get_in_order_queue());
1301                sycl::free(native_storage, dpct::get_in_order_queue());
1302            /*
1303            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1304            assuming in the original code the source host memory is pageable
1305            memory. If the memory is not pageable, call wait() on event return
1306            by memcpy API to ensure synchronization behavior.
1307            */
1308            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1309                   d_emb, cap.emb.data(), nd * 4).wait()),
1310               "native PLE restore input");
1311            k::ple_block(d_emb, d_hid, d_hist, w, out, ple_ws, nullptr);
1312            ck(DPCT_CHECK_ERROR(
1313                   dpct::get_current_device().queues_wait_and_throw()),
1314               "native PLE default restore sync");
1315            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1316                                    .memcpy(replay.data(), d_cr, hcd * 4)
1317                                    .wait()),
1318               "native PLE default restore read");
1319            const bool restored = std::memcmp(dev_res.data(), replay.data(), hcd * 4) == 0;
1320            std::printf("  native PLE key graph/repeat/buffer guards checked; restored default: %s\n", restored ? "byte-identical" : "FAIL");
1321            if (!restored) ++bad;
1322        }
1323
1324        if (t == 0) {
1325            // The engine only needs result and normalized. Export normalized after the complete private
1326            // workspace; result may overwrite hidden once its original values are no longer needed.
1327            const size_t workspace_bytes = (size_t) k::ple_block_scratch_bytes();
1328            void* compact_workspace = nullptr;
1329            ck(DPCT_CHECK_ERROR(compact_workspace = (void *)sycl::malloc_device(
1330                                    workspace_bytes + hcd * sizeof(float),
1331                                    dpct::get_in_order_queue())),
1332               "compact PLE workspace");
1333            k::PleOut compact{};
1334            compact.normalized = reinterpret_cast<float*>(static_cast<uint8_t*>(compact_workspace) + workspace_bytes);
1335            compact.result = d_hid;
1336            k::ple_block(d_emb, d_hid, d_hist, w, compact, compact_workspace, nullptr);
1337            ck(DPCT_CHECK_ERROR(
1338                   dpct::get_current_device().queues_wait_and_throw()),
1339               "compact PLE sync");
1340            std::vector<float> compact_norm(hcd), compact_result(hcd);
1341            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1342                                    .memcpy(compact_norm.data(),
1343                                            compact.normalized,
1344                                            hcd * sizeof(float))
1345                                    .wait()),
1346               "compact PLE normalized");
1347            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1348                                    .memcpy(compact_result.data(), d_hid,
1349                                            hcd * sizeof(float))
1350                                    .wait()),
1351               "compact PLE result");
1352            const bool equal = std::memcmp(compact_norm.data(), dev_norm.data(), hcd * sizeof(float)) == 0 &&
1353                               std::memcmp(compact_result.data(), dev_res.data(), hcd * sizeof(float)) == 0;
1354            std::printf("  PLE separate exports and in-place hidden result: %s\n", equal ? "byte-identical" : "FAIL");
1355            if (!equal) ++bad;
1356            /*
1357            DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
1358            assuming in the original code the source host memory is pageable
1359            memory. If the memory is not pageable, call wait() on event return
1360            by memcpy API to ensure synchronization behavior.
1361            */
1362            ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1363                   d_hid, cap.hidden.data(), hcd * sizeof(float)).wait()),
1364               "restore PLE hidden input");
1365            sycl::free(compact_workspace, dpct::get_in_order_queue());
1366        }
1367
1368        // slide the conv state by one NORMALIZED row, which is what the next token's window needs
1369        for (size_t c = 0; c < hcd; ++c)
1370            for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r)
1371                hist_state[r + (size_t) k::NG_HIST * c] = hist_state[(r + 1) + (size_t) k::NG_HIST * c];
1372        for (size_t c = 0; c < hcd; ++c)
1373            hist_state[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = dev_norm[c];
1374        sycl::free(ple_ws, dpct::get_in_order_queue());
1375    }
1376
1377    // ---- the trap that matters most: gated vs normalized as the conv input --------------------------
1378    // `ref/ngram.py`'s docstring calls `terms` "the padded gated values"; the source pads `normalized`.
1379    // Feeding the conv the gated values instead is a one-word change with every shape intact, so it is
1380    // computed here and required to differ.
1381    {
1382        const double rel_norm_gated = rel_l1(cap.gated.data(), cap.normalized.data(), hcd);
1383        std::printf("  %-52s %s (%.2f%% apart)\n", "normalized vs gated as the conv input is observable",
1384                    rel_norm_gated > 0.05 ? "yes" : "*** NO ***", rel_norm_gated * 100);
1385        if (!(rel_norm_gated > 0.05)) ++bad;
1386    }
1387
1388    // ---- the conv TAP ORDER: tap 0 reads the furthest back, not the current row ---------------------
1389    {
1390        // Recompute the conv on the host with the taps reversed, from the ORACLE's own `normalized`, and
1391        // require the result to differ from the oracle's conv_out.
1392        const size_t hcd2 = hcd;
1393        std::vector<float> rev(hcd2, 0.0f);
1394        for (size_t c = 0; c < hcd2; ++c) {
1395            float acc = 0;
1396            for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) {
1397                // THE RIVAL READING OF THE TAP CONVENTION.  ggml's is `t - (K-1-k)*d`, i.e. tap 0 reads the
1398                // FURTHEST back; the natural misreading is `t - k*d`, i.e. tap 0 reads the CURRENT row.
1399                //
1400                // The first version of this trap wrote `row = kk*dil` for the rival - which is ALGEBRAICALLY
1401                // THE SAME as the correct `hist - (K-1-kk)*dil` whenever `hist == (K-1)*dil`, because
1402                // `9-(3-kk)*3 == 3kk` identically.  It reported "0.00% apart" and was measuring nothing.
1403                // The rival has to REVERSE the row order: `(K-1-kk)*dil` gives 9,6,3,0 against the correct
1404                // 0,3,6,9, so tap 0 pairs the kernel's first weight with the NEWEST row instead of the oldest.
1405                const int row = (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE;
1406                // ROW-FASTEST: the capture's history is ggml's `ne=(hist, hc_dim)`, flat = row + hist*channel
1407                const float v = (row == k::NG_HIST) ? cap.normalized[c]
1408                                                    : cap.hist[(size_t) row + (size_t) k::NG_HIST * c];
1409                // GGML-NATIVE: `w_conv[k + kern*c]`, because the capture's tensor is ne=(kern, hc_dim) with
1410                // ne0 = kern fast.  `w_conv[kk*hc_dim + c]` is the TRANSPOSE and is what this reference had
1411                // first - it reported 115% on conv_out while the GPU kernel, which carries the layout note,
1412                // was within 4.6e-02.  The oracle caught the reference, not the kernel, which is the whole
1413                // reason for having one.
1414                acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * v;
1415            }
1416            rev[c] = acc / (1.0f + std::exp(-acc));
1417        }
1418        const double rel = rel_l1(cap.conv_out.data(), rev.data(), hcd2);
1419        std::printf("  %-52s %s (%.2f%% apart)\n", "reversed conv tap order is observable",
1420                    gt(rel, 0.05) ? "yes" : "*** NO ***", rel * 100);
1421        if (!gt(rel, 0.05)) ++bad;
1422    }
1423
1424    // ---- THE HOST f32 REFERENCE, which is what makes the gaps above ATTRIBUTABLE rather than mysterious.
1425    //
1426    // `ple_layer_xcheck.cpp` builds ggml's graph with the weights as **F32 tensors** (`ggml_new_tensor_2d(...,
1427    // GGML_TYPE_F32, ...)`).  `ggml_mul_mat` converts src1 to src0's `vec_dot_type`, so with an F32 weight
1428    // ggml performs NO activation conversion at all - while the real `ple_key` is Q2_0 (contract Q8_0) and the
1429    // real `ple_value` is BF16 (contract BF16).
1430    //
1431    // **The capture is therefore a valid oracle for the STRUCTURE and not for the ACTIVATION CONTRACT.**  This
1432    // reference reproduces it exactly, in f32, using the capture's own weights - which proves every LAYOUT in
1433    // the block (the conv kernel's `k + kern*c`, the row-fastest history, per-stream grouped norms, the
1434    // head-slowest gather) independently of the GPU.  Whatever gap remains between the GPU and the capture is
1435    // then exactly the contract, and nothing else.
1436    // Hoisted out of the reference block below: the term-magnitude metric needs the state the LAST token
1437    // used, and that block has already closed by the time it runs.
1438    std::vector<float> hist_last;
1439    {
1440        const size_t H = hcd, N = nd;
1441        std::vector<float> k_ref(H), q_ref(H), v_ref(N), gt_ref(k::NG_HC), gd_ref(H), nm_ref(H), cv_ref(H),
1442            rs_ref(H);
1443        auto gnorm = [&](const float* x, const float* w, float* y, int n) {
1444            for (int c = 0; c < k::NG_HC; ++c) {
1445                double sum = 0.0;
1446                for (int d = 0; d < k::NG_N_EMBD; ++d) {
1447                    const float xv = x[c * k::NG_N_EMBD + d];
1448                    sum += (double) (xv * xv);                 // f32 product, widened - as ggml does
1449                }
1450                const float mean = (float) (sum / k::NG_N_EMBD);
1451                const float scale = 1.0f / std::sqrt(mean + cap.eps);
1452                for (int d = 0; d < k::NG_N_EMBD; ++d)
1453                    y[c * k::NG_N_EMBD + d] = x[c * k::NG_N_EMBD + d] * scale * w[c * k::NG_N_EMBD + d];
1454            }
1455            (void) n;
1456        };
1457        // The SAME history advance as the GPU loop, so the two are compared on identical inputs.
1458        std::vector<float> hist_ref = cap.hist;
1459        for (int t = 0; t < cap.nt; ++t) {
1460            const float* emb = cap.emb.data() + (size_t) t * N;
1461            const float* hid = cap.hidden.data() + (size_t) t * H;
1462            // key = w_key @ emb, with the capture's F32 weight and NO activation conversion
1463            for (size_t o = 0; o < H; ++o) {
1464                double a = 0;
1465                for (size_t i = 0; i < N; ++i) a += (double) cap.w_key[o * N + i] * (double) emb[i];
1466                k_ref[o] = (float) a;
1467            }
1468            gnorm(k_ref.data(), cap.w_nk.data(), k_ref.data(), k::NG_N_EMBD);
1469            gnorm(hid, cap.w_nq.data(), q_ref.data(), k::NG_N_EMBD);
1470            for (size_t o = 0; o < N; ++o) {
1471                double a = 0;
1472                for (size_t i = 0; i < N; ++i) a += (double) cap.w_value[o * N + i] * (double) emb[i];
1473                v_ref[o] = (float) a;
1474            }
1475            for (int c = 0; c < k::NG_HC; ++c) {
1476                double a = 0;
1477                for (int d = 0; d < k::NG_N_EMBD; ++d)
1478                    a += (double) k_ref[c * k::NG_N_EMBD + d] * (double) q_ref[c * k::NG_N_EMBD + d];
1479                const float s = (float) (a / (double) 1.0) / std::sqrt((float) k::NG_N_EMBD);
1480                const float mag = std::sqrt(std::fmax(std::fabs(s), 1e-6f));
1481                const float sgn = (s > 0) ? 1.0f : ((s < 0) ? -1.0f : 0.0f);
1482                gt_ref[c] = 1.0f / (1.0f + std::exp(-(sgn * mag)));
1483            }
1484            for (size_t i = 0; i < H; ++i)
1485                gd_ref[i] = v_ref[i % N] * gt_ref[i / N];
1486            gnorm(gd_ref.data(), cap.w_nc.data(), nm_ref.data(), k::NG_N_EMBD);
1487            for (size_t c = 0; c < H; ++c) {
1488                float acc = 0;
1489                for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) {
1490                    const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE;
1491                    // capture history is ggml `ne=(hist, hc_dim)`: flat = row + hist*channel.  `hist_ref` is
1492                    // the ADVANCED state, so this reference sees exactly what the GPU call saw.
1493                    const float vv = (row == k::NG_HIST) ? nm_ref[c]
1494                                                        : hist_ref[(size_t) row + (size_t) k::NG_HIST * c];
1495                    acc += cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] * vv;
1496                }
1497                cv_ref[c] = acc / (1.0f + std::exp(-acc));
1498            }
1499            for (size_t i = 0; i < H; ++i) rs_ref[i] = hid[i] + gd_ref[i] + cv_ref[i];
1500
1501            const size_t ok_ = (size_t) t * H, ov = (size_t) t * N, og = (size_t) t * (size_t) k::NG_HC;
1502            struct HCmp { const char* name; const std::vector<float>* got; const std::vector<float>* all;
1503                          size_t off; size_t n; };
1504            const HCmp cmps[] = {
1505                {"key", &k_ref, &cap.key, ok_, H},          {"value", &v_ref, &cap.value, ov, N},
1506                {"gate", &gt_ref, &cap.gate, og, (size_t) k::NG_HC},
1507                {"gated", &gd_ref, &cap.gated, ok_, H},     {"normalized", &nm_ref, &cap.normalized, ok_, H},
1508                {"conv_out", &cv_ref, &cap.conv_out, ok_, H},
1509                {"result", &rs_ref, &cap.result, ok_, H},
1510            };
1511            for (const HCmp& s : cmps) {
1512                std::vector<float> want(s.all->begin() + (long long) s.off,
1513                                        s.all->begin() + (long long) (s.off + s.n));
1514                long long nf = 0;
1515                const double rel = rel_l1(want.data(), s.got->data(), s.n, nullptr, &nf);
1516                const bool ok = le(rel, 1e-4) && nf == 0;
1517                std::printf("  host f32 reference, token %d %-12s rel %.3e (non-finite %lld)%s\n", t, s.name,
1518                            rel, nf, ok ? "" : "   *** FAIL ***");
1519                if (!ok) ++bad;
1520            }
1521
1522            // save the state this token used, then slide it - identical to the GPU-side advance
1523            if (t == cap.nt - 1) hist_last = hist_ref;
1524            for (size_t c = 0; c < hcd; ++c)
1525                for (size_t r = 0; r + 1 < (size_t) k::NG_HIST; ++r)
1526                    hist_ref[r + (size_t) k::NG_HIST * c] = hist_ref[(r + 1) + (size_t) k::NG_HIST * c];
1527            for (size_t c = 0; c < hcd; ++c)
1528                hist_ref[((size_t) k::NG_HIST - 1) + (size_t) k::NG_HIST * c] = nm_ref[c];
1529        }
1530        // TOLERANCE: 1e-4.  Both sides are f32 (or f64-accumulated) sums of 2560 products, so the only
1531        // difference is summation ORDER, which is ~n*eps = 2560*6e-8 = 1.5e-4 worst case and far less in
1532        // practice.  A STRUCTURAL error - a transposed conv kernel, a channel-slow history, a head-fastest
1533        // gather - is O(1), so the two are three orders apart and the bound is not a judgement call.
1534    }
1535
1536    // ---- `conv_out`'s error must be measured against the TERMS, not the result ----------------------
1537    //
1538    // The dilated conv sums four terms and the sum CANCELS: `normalized` has mean |.| around 0.70 and the
1539    // result's is around 0.009, a factor of ~77.  Dividing by the result therefore reports the CONDITION
1540    // NUMBER and not the arithmetic - the same metric mistake this project has made four times (rounds 169,
1541    // 189, 194, 196), and it is what made `conv_out` look like the worst stage at 4.55e-02.
1542    {
1543        // `dev_conv` holds the LAST token after the loop above, and the capture is token-major.
1544        const float* oc = cap.conv_out.data() + (size_t) (cap.nt - 1) * hcd;
1545        double num = 0, terms = 0, res = 0;
1546        for (size_t c = 0; c < hcd; ++c) {
1547            double t_sum = 0;
1548            for (int kk = 0; kk < k::PLE_CONV_KERNEL; ++kk) {
1549                const int row = k::NG_HIST - (k::PLE_CONV_KERNEL - 1 - kk) * k::NGRAM_SIZE;
1550                const float v = (row == k::NG_HIST)
1551                                    ? cap.normalized[(size_t) (cap.nt - 1) * hcd + c]
1552                                    : hist_last[(size_t) row + (size_t) k::NG_HIST * c];
1553                t_sum += std::fabs((double) cap.w_conv[(size_t) kk + (size_t) k::PLE_CONV_KERNEL * c] *
1554                                   (double) v);
1555            }
1556            terms += t_sum;
1557            res += std::fabs((double) oc[c]);
1558            num += std::fabs((double) oc[c] - (double) dev_conv[c]);
1559        }
1560        std::printf("\n  conv_out (token %d) against the TERM magnitude, not the result: rel %.3e"
1561                    "   (|result|/|terms| = %.4f)\n",
1562                    cap.nt - 1, num / terms, res / terms);
1563    }
1564
1565    std::printf("\nple_parity: %d failures (worst stage rel %.3e)\n", bad, worst_all);
1566    if (bad) return 1;
1567    if (selftest) std::printf("ple_parity OK\n");
1568    return 0;
1569}