okami.mom/strata

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

Guillaume PUTIERgr_parity, ple_parity: wait for the default-stream setup before launching on the test stream832b2e4f3

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