okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
97.7 KiB1731 linesraw
1// src/kernels/qsa_parity.cpp - P2.S2's test for the QSA cache, indexer, selection and attention.
2//
3// `ref/qsa.py` carries eleven PROPERTY checks and `ref/model.py::_qsa` is the layer as the model runs it.  The
4// readings a prose transcription gets WRONG, each of which produces a well-formed result of the right shape,
5// are computed here the wrong way round AND required to differ MATERIALLY before the kernel is judged against
6// the right one - a test that only does the second half passes against either reading:
7//
8//   1. `pooled[b]` is rotated at the block's FIRST cell.  The reference's PROPERTY 4 pins it against the
9//      block's LAST cell; both give a unit-norm vector and the same downstream shape.
10//   2. Pool THEN norm (`rms_norm(mean(x))`) and not norm THEN pool (`mean(rms_norm(x))`).  `ref/model.py` L358
11//      is explicit, and the two differ whenever the four cells have different magnitudes.
12//   3. The spare slot's key is `rms_norm(raw[0])` - cell ZERO - and not the last raw key, and the tail cells
13//      map to THAT slot and not to the last complete block.  A three-row raw tail cannot produce it unless
14//      cell 0's key is kept, which is what makes this a real design constraint rather than a detail.
15//   4. The indexer's Relu is PER HEAD, summed afterwards.  `relu(sum_h dot_h)` is the rival reading and
16//      differs whenever any head's dot is negative.
17//   5. The q -> kv head map is `q / 12` (integer division), NOT `q % 2`.  `ref/qsa.py` PROPERTY 7 tests the
18//      same thing; with 24 and 2 the two give [0 x12, 1 x12] and [0,1,0,1,...].
19//   6. The attention reads ONLY the selected cells.  The source writes -inf into the mask and zeros at the
20//      top-k indices, so an unselected cell has weight exactly zero even when it would score highest -
21//      PROPERTY 8's fixture, reproduced here with its own numbers.
22//   7. `attn *= sigmoid(gate)` with the gate taken from the SECOND half of each head's 2*head_dim block, and
23//      the rounding to fp16 happening AFTER the multiply (one rounding, not two).
24//   8. The KV cache is PAGED and the page table is not assumed to be the identity: the pool is written and
25//      read back at page_size 1, 4 and 512 with a REVERSED table, and the kernel's own reading of the layout
26//      is compared against two rivals (linear, i.e. the table ignored; and cell-major inside the page).
27//
28// THE METRIC.  Both sums here - the indexer's sum of four relu'd dots and the attention's weighted sum of
29// value rows - cancel, so a plain |want-got|/|want| reports the condition number instead of the arithmetic.
30// The project has made that mistake four times (rounds 169, 189, 194, 196); where a sum is compared below, the
31// denominator is the magnitude of the TERMS.
32//
33// WHAT SETS EACH TOLERANCE, because a tolerance nobody can explain is one nobody can tighten:
34//   * the fp16 converter, the pool contents, the gathered scratch and the spare indexer key: EXACT.  The only
35//     arithmetic is a conversion, and section 0 checks that conversion against numpy's float16 over 395
36//     vectors covering ties in both directions, subnormals and overflow - an oracle sharing no code with it -
37//     plus all 65,536 fp16 patterns in the reverse direction.
38//   * the pooled block keys: 1e-6.  The pooling and the norm are double on both sides and are bit-exact
39//     BEFORE the rotation; the residual is `rope_neox_apply` (f32, reused rather than re-implemented) against
40//     the reference's float64 rotation, the class round 189 measured at ~1e-7.
41//   * the indexer scores: 1e-6 against Sum|dot_h| + |bias|, set by the fp32 storage of the pooled keys -
42//     2^-24 per element over a 128-term dot.
43//   * the selected ids: EXACT.  `docs/capture-format.md` L127 gives `indexer_ids` no tolerance.
44//   * the attention against a reference reading the SAME fp16 cache: 1e-5, set by f32 accumulation over
45//     256-term dots plus `expf`'s 2 ulp.  This is the KERNEL's number.
46//   * the attention against a reference reading the f32 keys: REPORTED and then checked against the phase's
47//     1e-3 for FP16 paths.  That difference is the FP16 CACHE's cost, not the kernel's, and it is kept
48//     separate so a kernel bug cannot hide inside it.
49#define DPCT_PROFILING_ENABLED
50#include <sycl/sycl.hpp>
51#include <dpct/dpct.hpp>
52#include "strata/kernels/qsa.hpp"
53#include "strata/kernels/native_qsa_indexer.hpp"
54
55#include "strata/kernels/f16_bits.hpp"
56#include "strata/kernels/rope.hpp"
57
58#include <algorithm>
59#include <cmath>
60#include <cstdio>
61#include <cstdlib>
62#include <cstring>
63#include <functional>
64#include <random>
65#include <string>
66#include <vector>
67
68namespace {
69
70using strata::kernels::f16_from_f32;
71using strata::kernels::f32_from_f16;
72
73void check(dpct::err0 e, const char *what) {
74}
75
76/// A device buffer with the boilerplate folded in.  A test that allocates twenty buffers by hand spends its
77/// attention on memcpy arguments instead of on the kernel.
78template <typename T>
79struct Dev {
80    T* p = nullptr;
81    Dev() = default;
82    explicit Dev(size_t n) { alloc(n); }
83    ~Dev() { if (p) sycl::free(p, dpct::get_in_order_queue()); }
84    Dev(const Dev&) = delete;
85    Dev& operator=(const Dev&) = delete;
86    void alloc(size_t n) {
87        if (p) { sycl::free(p, dpct::get_in_order_queue()); p = nullptr; }
88        if (n) check(
89            DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
90                                 n * sizeof(T), dpct::get_in_order_queue())),
91            "cudaMalloc");
92    }
93    void put(const std::vector<T>& v) {
94        if (!p) alloc(v.size());
95        /*
96        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
97        assuming in the original code the source host memory is pageable memory.
98        If the memory is not pageable, call wait() on event return by memcpy API
99        to ensure synchronization behavior.
100        */
101        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
102                  p, v.data(), v.size() * sizeof(T)).wait()),
103              "H2D");
104    }
105    std::vector<T> get(size_t n) const {
106        std::vector<T> v(n);
107        check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
108                                   .memcpy(v.data(), p, n * sizeof(T))
109                                   .wait()),
110              "D2H");
111        return v;
112    }
113};
114
115std::vector<double> as_d(const std::vector<float>& v) { return std::vector<double>(v.begin(), v.end()); }
116std::vector<float> as_f(const std::vector<double>& v) {
117    std::vector<float> o(v.size());
118    for (size_t i = 0; i < v.size(); ++i) o[i] = (float) v[i];
119    return o;
120}
121
122/// Relative error against the magnitude of the TERMS.  See the header comment.
123double rel_terms(double want, double got, double terms) {
124    return std::fabs(want - got) / (terms > 1e-30 ? terms : 1e-30);
125}
126
127double rel_l1(const std::vector<double>& a, const std::vector<double>& b) {
128    double d = 0, m = 0;
129    for (size_t i = 0; i < a.size(); ++i) {
130        d += std::fabs(a[i] - b[i]);
131        m += std::fabs(a[i]);
132    }
133    return d / (m > 1e-30 ? m : 1e-30);
134}
135
136int g_bad = 0;
137std::string pct(double rel) {
138    char b[32];
139    std::snprintf(b, sizeof b, "%.2f%% apart", rel * 100.0);
140    return b;
141}
142void verdict(const std::string& name, bool ok, const std::string& detail = "") {
143    std::printf("  %-48s %-6s %s\n", name.c_str(), ok ? "yes" : "*** NO ***", detail.c_str());
144    if (!ok) ++g_bad;
145}
146void report(const std::string& name, double v, const char* unit) {
147    std::printf("  %-48s %s %.3e\n", name.c_str(), unit, v);
148}
149void require(const std::string& name, bool ok, const std::string& detail = "") {
150    std::printf("  %-48s %-6s %s\n", name.c_str(), ok ? "ok" : "*** BAD ***", detail.c_str());
151    if (!ok) ++g_bad;
152}
153
154// ================= the reference: ref/qsa.py + ref/model.py, in double =================
155
156/// Which of the rival readings to compute.  The defaults are the SOURCE's reading.
157struct Alt {
158    bool rotate_at_block_start = true;  ///< false: rotate at the block's LAST cell         (WRONG)
159    bool pool_then_norm = true;         ///< false: mean of the per-cell norms              (WRONG)
160    bool dead_from_first = true;        ///< false: the spare key from the LAST raw key     (WRONG)
161    bool rope_raw = false;              ///< true:  rotate the raw keys before pooling      (WRONG)
162    bool relu_per_head = true;          ///< false: relu(sum of the head dots)              (WRONG)
163    bool use_relu = true;               ///< false: no relu at all                          (WRONG)
164    bool use_bias = true;               ///< false: drop the per-block bias                 (WRONG)
165    bool kv_divide = true;              ///< false: q % n_head_kv instead of q / 12          (WRONG)
166    bool apply_scale = true;            ///< false: no 1/sqrt(head_dim)                      (WRONG)
167    bool gate_second_half = true;       ///< false: the gate from the FIRST half             (WRONG)
168    bool gate_sigmoid = true;           ///< false: silu instead of sigmoid                  (WRONG)
169};
170
171/// `x*y + z` with the product ROUNDED first, i.e. no FMA contraction.
172///
173/// MSVC contracts `ss += v*v` into an FMA even under /fp:precise, so the reference was MORE accurate than
174/// the kernel's explicit `__fadd_rn(__fmul_rn(v, v))` and the spare key came out one bit different in 7 of
175/// 128 components.  The kernel's arithmetic is what is under test, so the reference REPRODUCES it instead of
176/// beating it; `volatile` is what stops the compiler re-fusing the two operations.
177double mul_add_plain(double x, double y, double z) {
178    const volatile double p = x * y;
179    return z + p;
180}
181
182/// `ref/qsa.py::rms_norm` in double, in place.  `w` may be empty (w = None).
183void ref_rms_norm(std::vector<double>& x, const std::vector<float>& w, float eps) {
184    double ss = 0;
185    for (double v : x) ss = mul_add_plain(v, v, ss);
186    const double inv = 1.0 / std::sqrt(ss / (double) x.size() + (double) eps);
187    for (size_t i = 0; i < x.size(); ++i) x[i] = x[i] * inv * (w.empty() ? 1.0 : (double) w[i]);
188}
189
190/// `ref/qsa.py::rope_neox` in double: NEOX pairs (i, i + n_rot/2), partial over the first n_rot dims.
191///
192/// `terms`, when given, receives the magnitude of each component's TERMS - `|a c| + |b s|` where the
193/// rotation subtracts - so a comparison can divide by that instead of by the result, which cancels.
194void ref_rope_neox(std::vector<double>& x, double pos, int n_rot, double theta,
195                   std::vector<double>* terms = nullptr) {
196    const int half = n_rot / 2;
197    std::vector<double> a(x.begin(), x.begin() + half), b(x.begin() + half, x.begin() + n_rot);
198    if (terms) {
199        terms->assign(x.size(), 0.0);
200        for (size_t i = (size_t) n_rot; i < x.size(); ++i) (*terms)[i] = std::fabs(x[i]);
201    }
202    for (int i = 0; i < half; ++i) {
203        const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot);
204        const double ang = pos * inv, c = std::cos(ang), s = std::sin(ang);
205        x[i] = a[i] * c - b[i] * s;
206        x[half + i] = a[i] * s + b[i] * c;
207        if (terms) {
208            (*terms)[i] = std::fabs(a[i] * c) + std::fabs(b[i] * s);
209            (*terms)[half + i] = std::fabs(a[i] * s) + std::fabs(b[i] * c);
210        }
211    }
212}
213
214const int64_t REF_R = 4;    ///< IDX_BLOCK, checked against the shapes at the top of main
215
216/// `QsaCache`, holding f64 rows - the reference never sees an fp16 key.
217struct RefCache {
218    std::vector<std::vector<double>> k, v, raw;
219    std::vector<double> pos;
220    int64_t size() const { return (int64_t) pos.size(); }
221    void append(std::vector<double> kk, std::vector<double> vv, std::vector<double> rr, double p) {
222        k.push_back(std::move(kk));
223        v.push_back(std::move(vv));
224        raw.push_back(std::move(rr));
225        pos.push_back(p);
226    }
227};
228
229/// `QsaCache.pooled_raw(r)` - BEFORE the norm, which is the only place the 1/r divisor is observable.
230std::vector<double> ref_pooled_raw(const RefCache& c) {
231    const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size();
232    std::vector<double> out((size_t) n_bid * dim, 0.0);
233    for (int64_t b = 0; b < n_bid; ++b)
234        for (int64_t i = 0; i < REF_R; ++i)
235            for (int64_t d = 0; d < dim; ++d) out[(size_t) b * dim + d] += c.raw[(size_t) (b * REF_R + i)][(size_t) d];
236    for (auto& x : out) x /= (double) REF_R;
237    return out;
238}
239
240/// `pooled_keys` + `dead_pooled_key`, in the readback order `indexer_scores` uses: (n_bid + 1, idx_dim).
241std::vector<double> ref_pooled(const RefCache& c, const std::vector<float>& w_kn, float eps, int n_rot,
242                               double theta, const Alt& o,
243                               std::vector<double>* terms_out = nullptr) {
244    const int64_t n_bid = c.size() / REF_R, dim = (int64_t) c.raw[0].size();
245    std::vector<double> pooled((size_t) (n_bid + 1) * dim, 0.0);
246    std::vector<std::vector<double>> rows(c.raw);
247    if (o.rope_raw)
248        for (size_t j = 0; j < rows.size(); ++j) ref_rope_neox(rows[j], c.pos[j], n_rot, theta);
249
250    for (int64_t b = 0; b < n_bid; ++b) {
251        std::vector<double> m((size_t) dim, 0.0);
252        if (o.pool_then_norm) {
253            for (int64_t i = 0; i < REF_R; ++i)
254                for (int64_t d = 0; d < dim; ++d)
255                    m[(size_t) d] += rows[(size_t) (b * REF_R + i)][(size_t) d] / (double) REF_R;
256            ref_rms_norm(m, w_kn, eps);
257        } else {
258            for (int64_t i = 0; i < REF_R; ++i) {
259                std::vector<double> one = rows[(size_t) (b * REF_R + i)];
260                ref_rms_norm(one, w_kn, eps);
261                for (int64_t d = 0; d < dim; ++d) m[(size_t) d] += one[(size_t) d] / (double) REF_R;
262            }
263        }
264        std::vector<double> terms;
265        ref_rope_neox(m, o.rotate_at_block_start ? c.pos[(size_t) (b * REF_R)]
266                                                 : c.pos[(size_t) (b * REF_R + REF_R - 1)],
267                      n_rot, theta, terms_out ? &terms : nullptr);
268        for (int64_t d = 0; d < dim; ++d) pooled[(size_t) b * dim + d] = m[(size_t) d];
269        if (terms_out) {
270            if (b == 0) terms_out->assign((size_t) (n_bid + 1) * dim, 0.0);
271            for (int64_t d = 0; d < dim; ++d) (*terms_out)[(size_t) b * dim + d] = terms[(size_t) d];
272        }
273    }
274    std::vector<double> dead = rows[o.dead_from_first ? 0 : rows.size() - 1];
275    ref_rms_norm(dead, w_kn, eps);
276    ref_rope_neox(dead, 0.0, n_rot, theta);      // the identity, but computed the reference's way
277    for (int64_t d = 0; d < dim; ++d) pooled[(size_t) n_bid * dim + d] = dead[(size_t) d];
278    return pooled;
279}
280
281/// `ref/qsa.py::indexer_scores` - per CELL, after the `cell_block` mapping.
282std::vector<double> ref_indexer_scores(const std::vector<double>& pooled, int64_t n_bid,
283                                       const std::vector<double>& q_idx, int64_t idx_n_head, int64_t idx_dim,
284                                       const std::vector<float>& bias, int64_t n_kv, const Alt& o) {
285    std::vector<double> per_block((size_t) n_bid + 1, 0.0);
286    for (int64_t b = 0; b <= n_bid; ++b) {
287        double s = 0;
288        for (int64_t h = 0; h < idx_n_head; ++h) {
289            double dot = 0;
290            for (int64_t d = 0; d < idx_dim; ++d)
291                dot += pooled[(size_t) b * idx_dim + d] * q_idx[(size_t) h * idx_dim + d];
292            if (!o.use_relu) s += dot;
293            else if (o.relu_per_head) s += dot > 0 ? dot : 0.0;
294            else s += dot;
295        }
296        if (o.use_relu && !o.relu_per_head) s = s > 0 ? s : 0.0;
297        if (o.use_bias && !bias.empty()) s += (double) bias[(size_t) b];
298        if (b == n_bid && n_kv % REF_R != 0) s = (float) s + 1e9f;
299        per_block[(size_t) b] = s;
300    }
301    std::vector<double> cell((size_t) n_kv, 0.0);
302    for (int64_t j = 0; j < n_kv; ++j) cell[(size_t) j] = per_block[(size_t) (j / REF_R < n_bid ? j / REF_R : n_bid)];
303    return cell;
304}
305
306/// `ref/qsa.py::select_cells`, spelled with a stable sort rather than the kernel's threshold search, so the
307/// two are independent implementations of one rule: score DESCENDING, ties by ASCENDING index.
308std::vector<int32_t> ref_select(const std::vector<double>& scores, int64_t n_kv, int64_t top_k, bool dense) {
309    std::vector<int32_t> idx((size_t) n_kv);
310    for (int64_t j = 0; j < n_kv; ++j) idx[(size_t) j] = (int32_t) j;
311    if (dense) return idx;
312    const int64_t width = std::min<int64_t>(n_kv, top_k + REF_R - 1);
313    std::stable_sort(idx.begin(), idx.end(), [&](int32_t a, int32_t b) {
314        const double sa = scores[(size_t) a], sb = scores[(size_t) b];
315        if (sa != sb) return sa > sb;
316        return a < b;
317    });
318    idx.resize((size_t) width);
319    std::sort(idx.begin(), idx.end());
320    return idx;
321}
322
323/// `ref/qsa.py::qsa_attend` over an EXPLICIT selected set, reading K/V from whichever table the caller passes
324/// so that one piece of code runs on the f64 keys and on the fp16 cache's exact f32 values.
325std::vector<double> ref_attend(const std::vector<double>& q, int64_t n_head, int64_t n_head_kv, int64_t head_dim,
326                               const std::vector<int32_t>& ids, const std::vector<std::vector<double>>& k,
327                               const std::vector<std::vector<double>>& v, const Alt& o,
328                               std::vector<double>* weights_out) {
329    const double scale = o.apply_scale ? 1.0 / std::sqrt((double) head_dim) : 1.0;
330    std::vector<double> out((size_t) n_head * head_dim, 0.0);
331    if (weights_out) weights_out->assign((size_t) n_head * ids.size(), 0.0);
332    for (int64_t h = 0; h < n_head; ++h) {
333        const int64_t kv = o.kv_divide ? h / (n_head / n_head_kv) : h % n_head_kv;
334        std::vector<double> sc(ids.size());
335        for (size_t j = 0; j < ids.size(); ++j) {
336            double dot = 0;
337            for (int64_t d = 0; d < head_dim; ++d)
338                dot += k[(size_t) ids[j]][(size_t) (kv * head_dim + d)] * q[(size_t) (h * head_dim + d)];
339            sc[j] = dot * scale;
340        }
341        const double mx = *std::max_element(sc.begin(), sc.end());
342        double sum = 0;
343        for (auto& s : sc) { s = std::exp(s - mx); sum += s; }
344        for (auto& s : sc) s /= sum;
345        if (weights_out)
346            for (size_t j = 0; j < ids.size(); ++j) (*weights_out)[(size_t) h * ids.size() + j] = sc[j];
347        for (int64_t d = 0; d < head_dim; ++d) {
348            double acc = 0;
349            for (size_t j = 0; j < ids.size(); ++j) acc += sc[j] * v[(size_t) ids[j]][(size_t) (kv * head_dim + d)];
350            out[(size_t) (h * head_dim + d)] = acc;
351        }
352    }
353    return out;
354}
355
356/// `ref/model.py::_qsa`'s last two lines.
357std::vector<double> ref_gate(const std::vector<double>& attn, const std::vector<double>& q_full, int64_t n_head,
358                             int64_t head_dim, const Alt& o) {
359    std::vector<double> out((size_t) n_head * head_dim, 0.0);
360    for (int64_t h = 0; h < n_head; ++h)
361        for (int64_t d = 0; d < head_dim; ++d) {
362            const int64_t gi = o.gate_second_half ? h * 2 * head_dim + head_dim + d : h * 2 * head_dim + d;
363            const double g = q_full[(size_t) gi];
364            const double s = o.gate_sigmoid ? 1.0 / (1.0 + std::exp(-g)) : g / (1.0 + std::exp(-g));
365            out[(size_t) (h * head_dim + d)] = attn[(size_t) (h * head_dim + d)] * s;
366        }
367    return out;
368}
369
370/// {f32 bits, the fp16 bits numpy produces for it} interleaved.  Generated by
371/// `scripts/_gen_f16_oracle.py` from `np.float16(np.float32(x))`: an oracle that shares no code with
372/// f16_bits.hpp, which is the whole point of the table.
373const uint32_t kOracle[] = {
374#include "qsa_oracle_vectors.inc"
375};
376constexpr int kOracleN = (int) (sizeof(kOracle) / sizeof(kOracle[0])) / 2;
377
378}  // namespace
379
380int main(int argc, char** argv) {
381    std::setvbuf(stdout, nullptr, _IONBF, 0);   // a crash must not swallow what was printed already
382    bool selftest = false, dense = false, bench = false;
383    for (int i = 1; i < argc; ++i) {
384        const std::string a = argv[i];
385        if (a == "--selftest") selftest = true;
386        else if (a == "--qsa-dense") dense = true;
387        else if (a == "--bench") bench = true;
388        else {
389            std::fprintf(stderr, "usage: qsa_parity [--selftest] [--qsa-dense] [--bench]\n"
390                                 "  --qsa-dense  attend to EVERY cell instead of the indexer's selection\n"
391                                 "               (P1.S4's isolation switch; the sparse selection is still run\n"
392                                 "                and checked, against the reference's dense/sparse property)\n"
393                                 "  --bench      time the kernels at 32K of context\n");
394            return 2;
395        }
396    }
397
398    const strata::kernels::QsaShapes S = strata::kernels::qsa_real_shapes();
399    const int64_t NH = S.n_head, NKV = S.n_head_kv, HD = S.head_dim, IDXN = S.idx_n_head, IDXD = S.idx_dim,
400                  R = S.idx_block, TOPK = S.idx_top_k;
401    const int64_t MAXC = strata::kernels::kTopkMaxCells;
402    const float EPS = strata::kernels::qsa_rms_eps();
403    const double THETA = strata::kernels::qsa_freq_base();
404    std::mt19937 rng(20260916u);
405    std::normal_distribution<double> gauss(0.0, 1.0);
406    auto rnd = [&](double s) { return (float) (gauss(rng) * s); };
407
408    std::printf("qsa_parity: n_head %lld  n_head_kv %lld  head_dim %lld  indexer %lldx%lld r=%lld "
409                "top_k %lld  page (from the shapes) %lld   [%s]\n\n",
410                (long long) NH, (long long) NKV, (long long) HD, (long long) IDXN, (long long) IDXD,
411                (long long) R, (long long) TOPK, (long long) S.page_size, dense ? "DENSE" : "sparse");
412    require("the fixture's r is the artifact's IDX_BLOCK", R == REF_R, "r = " + std::to_string(R));
413
414    // ================= 0. the fp16 converter, against numpy =================
415    {
416        int mism = 0, subnormal = 0;
417        for (int i = 0; i < kOracleN; ++i) {
418            float f;
419            const uint32_t fb = kOracle[2 * i];
420            std::memcpy(&f, &fb, 4);
421            const uint16_t want = (uint16_t) kOracle[2 * i + 1];
422            const uint16_t got = f16_from_f32(f);
423            if (got != want) {
424                if (mism < 5) std::printf("    f32 0x%08X -> got 0x%04X, numpy says 0x%04X\n", fb, got, want);
425                ++mism;
426            }
427            if ((want & 0x7C00u) == 0u && (want & 0x3FFu) != 0u) ++subnormal;
428        }
429        require("f32->f16 matches numpy's float16 on every vector", mism == 0,
430                std::to_string(kOracleN) + " vectors, " + std::to_string(subnormal) + " subnormal");
431        int bad_rev = 0;
432        for (int h = 0; h < 65536; ++h) {
433            const int ex = (h >> 10) & 0x1F, man = h & 0x3FF;
434            if (ex == 31) continue;                    // inf/NaN come from the vector table above
435            const double mag = ex == 0 ? (double) man * std::ldexp(1.0, -24)
436                                       : (double) (1024 + man) * std::ldexp(1.0, ex - 25);
437            const double want = (h & 0x8000) ? -mag : mag;
438            if ((double) f32_from_f16((uint16_t) h) != want) {
439                if (bad_rev < 5) std::printf("    f16 0x%04X -> %.9g, want %.9g\n", h, (double) f32_from_f16((uint16_t) h), want);
440                ++bad_rev;
441            }
442        }
443        require("f16->f32 is exact on all 65,536 bit patterns", bad_rev == 0,
444                std::to_string(bad_rev) + " wrong");
445    }
446
447    // ================= 1. kv_append: the paged pool, three page granules =================
448    const int64_t TCELLS = 1100;                     // 275 indexer blocks, and 3 pages at page_size 512
449    std::vector<float> kcur_all((size_t) TCELLS * NKV * HD), vcur_all((size_t) TCELLS * NKV * HD);
450    for (auto& x : kcur_all) x = rnd(1.0);
451    for (auto& x : vcur_all) x = rnd(1.0);
452    // EVERY pointer this kernel set takes is a DEVICE pointer - the append sources, the indexer weights
453    // and the rope tables alike.  The first draft passed `&kcur_all[...]`, `w_kn.data()` and
454    // `cos_tab.data()` straight through, and every kernel that dereferenced one took an illegal access.
455    Dev<float> dkcur_all, dvcur_all;
456    dkcur_all.put(kcur_all);
457    dvcur_all.put(vcur_all);
458
459    struct PageCase {
460        int64_t page_size = 0, n_pages = 0;
461        std::vector<int32_t> table;
462    };
463    std::vector<PageCase> pages;
464    for (int64_t ps : {(int64_t) 1, (int64_t) 4, (int64_t) 512}) {
465        PageCase c;
466        c.page_size = ps;
467        c.n_pages = (TCELLS + ps - 1) / ps;
468        c.table.resize((size_t) c.n_pages);
469        for (int64_t i = 0; i < c.n_pages; ++i) c.table[(size_t) i] = (int32_t) (c.n_pages - 1 - i);   // REVERSED
470        pages.push_back(std::move(c));
471    }
472    const std::vector<int32_t> ids = {0, 1, 2, 3, 5, 8, 13, 21, 34, 39, 1099, 700};
473
474    for (PageCase& c : pages) {
475        // THE PAGE GRANULE IS A PROPERTY OF THE SHAPES, and the kernel takes it from there rather than from an
476        // argument.  The first version of this fixture left it at 512 while the table described 1-cell pages,
477        // so the kernel indexed a 1100-page table as if it had 3 pages and ran off the pool - which is what an
478        // illegal memory access reported.  A test that feeds one geometry and expects another is measuring
479        // itself; the fix is to build the shapes per case.
480        strata::kernels::QsaShapes Sc = S;
481        Sc.page_size = c.page_size;
482        const size_t pool_n = (size_t) c.n_pages * NKV * c.page_size * HD;
483        Dev<uint16_t> dk(pool_n), dv(pool_n);
484        Dev<int32_t> dtab;
485        dtab.put(c.table);
486        for (int64_t t = 0; t < TCELLS; ++t)
487            strata::kernels::kv_append(dk.p, dv.p, dtab.p, t, dkcur_all.p + (size_t) t * NKV * HD,
488                                       dvcur_all.p + (size_t) t * NKV * HD, Sc, nullptr);
489        const std::vector<uint16_t> hk = dk.get(pool_n), hv = dv.get(pool_n);
490
491        int mism = 0, mism_linear = 0, mism_head_major = 0;
492        const int64_t rows_avail = (int64_t) (pool_n / (size_t) HD);
493        // A rival layout's address is HYPOTHETICAL: where it would put the value may be outside the pool,
494        // and reading there is a host access violation rather than a mismatch.  Off the end counts as
495        // "the value is not where the rival would put it", which is the claim being tested.
496        auto elsewhere = [&](int64_t r) { return r < 0 || r >= rows_avail; };
497        for (int64_t cell = 0; cell < TCELLS; ++cell)
498            for (int64_t h = 0; h < NKV; ++h)
499                for (int64_t d = 0; d < HD; ++d) {
500                    const size_t src = (size_t) (cell * NKV + h) * HD + d;
501                    const uint16_t wk = f16_from_f32(kcur_all[src]), wv = f16_from_f32(vcur_all[src]);
502                    // the DECLARED layout: [page][kv_head][page_size][head_dim]
503                    const int64_t row = ((int64_t) c.table[(size_t) (cell / c.page_size)] * NKV + h) * c.page_size +
504                                        (cell % c.page_size);
505                    if (hk[(size_t) row * HD + d] != wk || hv[(size_t) row * HD + d] != wv) ++mism;
506                    // rival (a): the page table ignored, i.e. written at the logical address
507                    const int64_t rl = (cell * NKV + h) * c.page_size + (cell % c.page_size);
508                    if (elsewhere(rl) || hk[(size_t) rl * HD + d] != wk) ++mism_linear;
509                    // rival (b): cell-major inside the page instead of head-major
510                    const int64_t rh = ((int64_t) c.table[(size_t) (cell / c.page_size)] * c.page_size +
511                                        (cell % c.page_size)) * NKV + h;
512                    if (elsewhere(rh) || hk[(size_t) rh * HD + d] != wk) ++mism_head_major;
513                }
514        const double n_tot = (double) (TCELLS * NKV * HD);
515        require("kv_append at page_size " + std::to_string(c.page_size) + ": the pool is BIT-EXACT",
516                mism == 0, std::to_string(mism) + " of " + std::to_string((long long) n_tot) + " bits wrong");
517        verdict("  the page table is observable at page_size " + std::to_string(c.page_size),
518                (double) mism_linear / n_tot > 0.5,
519                pct((double) mism_linear / n_tot) + " (linear vs declared)");
520        // The head-major rival is IDENTICAL to the declared layout when page_size == 1 (both reduce to
521        // `cell * n_head_kv + h`), so the separation is only asserted where the layouts actually differ.
522        if (c.page_size >= 4) {
523            verdict("  head-major-in-page is observable at page_size " + std::to_string(c.page_size),
524                    (double) mism_head_major / n_tot > 0.5,
525                    pct((double) mism_head_major / n_tot) + " (cell-major vs head-major)");
526        }
527
528        Dev<int32_t> dids;
529        dids.put(ids);
530        const size_t scr_n = ids.size() * NKV * HD;
531        Dev<uint16_t> dks(scr_n), dvs(scr_n);
532        strata::kernels::kv_gather(dk.p, dv.p, dtab.p, dids.p, (int64_t) ids.size(), Sc, dks.p, dvs.p, nullptr);
533        const std::vector<uint16_t> gk = dks.get(scr_n), gv = dvs.get(scr_n);
534        int gm = 0;
535        for (size_t j = 0; j < ids.size(); ++j)
536            for (int64_t h = 0; h < NKV; ++h)
537                for (int64_t d = 0; d < HD; ++d) {
538                    const size_t src = (size_t) (ids[j] * NKV + h) * HD + d;
539                    if (gk[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(kcur_all[src])) ++gm;
540                    if (gv[(size_t) (j * NKV + h) * HD + d] != f16_from_f32(vcur_all[src])) ++gm;
541                }
542        require("  kv_gather is BIT-EXACT at page_size " + std::to_string(c.page_size), gm == 0,
543                std::to_string(gm) + " wrong bits");
544    }
545
546    // ================= 2. indexer_key_append =================
547    const int64_t NT = 10;                           // 2 complete blocks + a 2-cell tail
548    // The cells sit at POSITIONS 100..109, not at 0..9: `QsaCache.pos` is what the reference rotates by,
549    // and a kernel that assumes position == cell index is wrong for any sequence that does not start at 0
550    // (prefix reuse, phase 5).  With base 100 the two readings are 514% apart, which is asserted below.
551    const int32_t POS_BASE = 100;
552    RefCache rc;
553    std::vector<float> raw_flat;
554    for (int64_t t = 0; t < NT; ++t) {
555        std::vector<double> kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD);
556        for (int64_t i = 0; i < NKV * HD; ++i) { kk[(size_t) i] = gauss(rng); vv[(size_t) i] = gauss(rng); }
557        // cell MAGNITUDES 1, 4, 16, 64 - for the same reason round 196 gave its residual streams different
558        // scales: four i.i.d. rows of normal noise have nearly the same norm by accident, so "pool then norm"
559        // and "norm then pool" would agree to within the noise and the fixture could not see its own trap.
560        for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = gauss(rng) * std::pow(4.0, (double) (t % 4));
561        for (int64_t d = 0; d < IDXD; ++d) raw_flat.push_back((float) rr[(size_t) d]);
562        // The reference gets the f32 PROMOTION of what the device gets, not the f64 original.  Feeding it
563        // the f64 values left a 6e-8 relative difference, which is invisible in a score but crosses an f32
564        // rounding boundary in one value in four - and the spare key is asserted BIT-EXACT.
565        for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) raw_flat[(size_t) t * IDXD + d];
566        rc.append(kk, vv, rr, (double) (100 + t));
567    }
568    std::vector<float> w_kn((size_t) IDXD);
569    for (auto& x : w_kn) x = 1.0f + 0.1f * rnd(1.0);
570    std::vector<float> cos_tab((size_t) (2000 * S.n_rot / 2)), sin_tab(cos_tab.size());
571    strata::kernels::build_rope_table((int) S.n_rot, THETA, 2000, cos_tab.data(), sin_tab.data());
572    Dev<float> dw_kn, dcos, dsin;
573    dw_kn.put(w_kn);
574    dcos.put(cos_tab);
575    dsin.put(sin_tab);
576
577    const int64_t n_bid = NT / R;
578    const size_t pooled_n = (size_t) (n_bid + 1) * IDXD;
579    Dev<float> dpooled(pooled_n), ddead((size_t) IDXD), dtail((size_t) (R - 1) * IDXD);
580    Dev<int32_t> dblockpos(1);      // the rotation position, which only the DEVICE may read
581    // The POSITION is a device value now, because a host scalar would be baked into a captured graph.  One
582    // `cudaMemcpy` per cell here; the layer keeps this buffer and updates it per token.
583    Dev<int32_t> dpos(1);
584    {
585        strata::kernels::QsaIndexerBuffers bufs{dtail.p, ddead.p, dpooled.p, dblockpos.p};
586        Dev<float> draw((size_t) IDXD);
587        for (int64_t t = 0; t < NT; ++t) {      // one cell at a time: the tail is a ring and the spare row MOVES
588            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
589                                       .memcpy(draw.p,
590                                               &raw_flat[(size_t)t * IDXD],
591                                               (size_t)IDXD * 4)
592                                       .wait()),
593                  "raw");
594            const int32_t tpos = (int32_t) t;
595            check(
596                DPCT_CHECK_ERROR(
597                    (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dpos.p, &tpos, 4).wait()),
598                "pos");
599            strata::kernels::indexer_key_append(draw.p, dpos.p, POS_BASE, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p,
600                                                nullptr);
601        }
602        const std::vector<float> got = dpooled.get(pooled_n), got_dead = ddead.get((size_t) IDXD);
603        std::vector<double> terms;
604        const std::vector<double> want = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, Alt{}, &terms);
605        const std::vector<double> want_raw = ref_pooled_raw(rc);
606
607        // (a) the spare slot: BIT-EXACT, because rope at position 0 is the identity in both (cos = 1, sin = 0
608        //     exactly), so the residual the pooled rows carry from the f32 rope cannot appear here.
609        int dead_bad = 0;
610        for (int64_t d = 0; d < IDXD; ++d)
611            if (got_dead[(size_t) d] != (float) want[(size_t) n_bid * IDXD + d]) ++dead_bad;
612        require("the spare slot's key (rms_norm of cell 0) is BIT-EXACT", dead_bad == 0,
613                std::to_string(dead_bad) + " of " + std::to_string(IDXD) + " wrong");
614        require("the spare slot is at row n_bid and nowhere else", n_bid == 2,
615                "10 cells / r=4 -> 2 complete blocks");
616
617        // (b) the pooled blocks against the reference
618        // THE DENOMINATOR IS THE ROPE'S TERMS, not the result: `a*cos - b*sin` cancels, and the kernel's
619        // rotation runs in f32 over an f32 table (6e-8 per term) while the reference's runs in f64.  Dividing
620        // by the result reports the cancellation, which is what made this read 1.067e-06 against a 1e-6 bar.
621        double worst = 0;
622        for (int64_t b = 0; b < n_bid; ++b)
623            for (int64_t d = 0; d < IDXD; ++d) {
624                const double wv = want[(size_t) b * IDXD + d];
625                const double tm = terms[(size_t) b * IDXD + d];
626                worst = std::max(worst, rel_terms(wv, (double) got[(size_t) b * IDXD + d], tm));
627            }
628        report("pooled block keys vs the reference", worst, "rel/|rope terms|");
629        if (!(worst <= 1e-6)) { std::printf("    *** over 1e-6 ***\n"); ++g_bad; }
630
631        // (c) THE INCOMPLETE TAIL IS NOT POOLED: the two tail cells take the SPARE slot's score, which is cell
632        //     0's key - not their own mean.  A rival reading that pools them would still fill every row.
633        {
634            std::vector<double> tm((size_t) IDXD, 0.0);
635            for (int64_t i = n_bid * R; i < NT; ++i)
636                for (int64_t d = 0; d < IDXD; ++d) tm[(size_t) d] += rc.raw[(size_t) i][(size_t) d] / 2.0;
637            ref_rms_norm(tm, w_kn, EPS);
638            double num = 0, den = 0;
639            for (int64_t d = 0; d < IDXD; ++d) {
640                num += std::fabs(tm[(size_t) d] - (double) got_dead[(size_t) d]);
641                den += std::fabs(tm[(size_t) d]);
642            }
643            verdict("the incomplete tail is NOT pooled into the spare slot", num / den > 0.5, pct(num / den));
644        }
645
646        auto sep = [&](const std::string& name, const Alt& a) {
647            const std::vector<double> alt = ref_pooled(rc, w_kn, EPS, (int) S.n_rot, THETA, a);
648            double num = 0, den = 0;
649            // Rows 0..n_bid INCLUSIVE: the spare slot is row n_bid and three of the four rivals change
650            // nothing else, so leaving it out made "the spare key from the LAST raw key" separate 0.00%.
651            for (int64_t b = 0; b <= n_bid; ++b)
652                for (int64_t d = 0; d < IDXD; ++d) {
653                    num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]);
654                    den += std::fabs(want[(size_t) b * IDXD + d]);
655                }
656            verdict(name, num / den > 0.05, pct(num / den));
657        };
658        Alt a1; a1.rotate_at_block_start = false;
659        sep("rotating at the block's LAST cell is observable", a1);
660        Alt a2; a2.pool_then_norm = false;
661        sep("norm-then-pool vs pool-then-norm is observable", a2);
662        Alt a3; a3.dead_from_first = false;
663        sep("the spare key from the LAST raw key is observable", a3);
664        Alt a4; a4.rope_raw = true;
665        sep("rotating the RAW indexer keys is observable", a4);
666        {   // THE POSITION BASE.  The same reference with the cells at 0..9 instead of 100..109 - i.e.
667            // what a kernel that equates a cell's position with its index would compute.
668            RefCache flat = rc;
669            for (int64_t j = 0; j < NT; ++j) flat.pos[(size_t) j] = (double) j;
670            const std::vector<double> alt = ref_pooled(flat, w_kn, EPS, (int) S.n_rot, THETA, Alt{});
671            double num = 0, den = 0;
672            for (int64_t b = 0; b <= n_bid; ++b)
673                for (int64_t d = 0; d < IDXD; ++d) {
674                    num += std::fabs(alt[(size_t) b * IDXD + d] - want[(size_t) b * IDXD + d]);
675                    den += std::fabs(want[(size_t) b * IDXD + d]);
676                }
677            verdict("the rotation's POSITION BASE (pos_base) is observable", num / den > 0.05,
678                    pct(num / den));
679        }
680
681        // (d) THE TRAP THIS FIXTURE CANNOT SEE, measured and reported rather than hidden.  `rms_norm` divides
682        //     by sqrt(mean(x^2) + eps), so the 1/r in the mean cancels EXCEPT through eps: mean and sum differ
683        //     by ~eps/(2*mean(x^2)) relative.  `ref/qsa.py` L463-465 makes the same point about its own test.
684        {
685            std::vector<double> psum = want_raw;
686            for (auto& x : psum) x *= (double) R;
687            std::vector<double> nm = want_raw, ns = psum;
688            for (int64_t b = 0; b < n_bid; ++b) {
689                std::vector<double> m(nm.begin() + (size_t) b * IDXD, nm.begin() + (size_t) (b + 1) * IDXD);
690                std::vector<double> s(ns.begin() + (size_t) b * IDXD, ns.begin() + (size_t) (b + 1) * IDXD);
691                ref_rms_norm(m, w_kn, EPS);
692                ref_rms_norm(s, w_kn, EPS);
693                for (int64_t d = 0; d < IDXD; ++d) {
694                    nm[(size_t) b * IDXD + d] = m[(size_t) d];
695                    ns[(size_t) b * IDXD + d] = s[(size_t) d];
696                }
697            }
698            double num = 0, den = 0;
699            for (size_t i = 0; i < want_raw.size(); ++i) {
700                num += std::fabs(psum[i] - want_raw[i]);
701                den += std::fabs(want_raw[i]);
702            }
703            verdict("the 1/r divisor IS observable in the RAW pooled value", num / den > 0.5,
704                    pct(num / den) + " (sum vs mean, before any norm)");
705            std::printf("  %-48s      %.3e  <-- below EVERY score tolerance; the divisor cannot be\n",
706                        "the same divisor AFTER the norm", rel_l1(ns, nm));
707            std::printf("  %-48s      %s\n", "", "checked downstream at all, which is why the raw value is the");
708            std::printf("  %-48s      %s\n", "", "only place the mean/sum question is answerable.");
709        }
710    }
711
712    // ================= 3. qsa_index =================
713    std::vector<float> q_idx((size_t) (IDXN * IDXD));
714    for (auto& x : q_idx) x = rnd(1.0);
715    // A bias of ~0.4 against scores of ~20 separates "applies the bias" from "drops it" by 3.4%, which
716    // is not a fixture that can see its own trap. This is a guard for the kernel's optional additional
717    // bias, separate from the mandatory incomplete-tail bias; it is sized to
718    // be comparable with the scores so that dropping it is material.
719    std::vector<float> bias((size_t) (n_bid + 1));
720    for (auto& x : bias) x = rnd(8.0f);
721    {
722        const std::vector<float> got_pooled = dpooled.get(pooled_n);
723        const std::vector<double> p64 = as_d(got_pooled);
724        const std::vector<double> q_idx64 = as_d(q_idx);
725        const int64_t n_kv = NT;
726        Dev<float> dp, dqi, dbias, dsc;
727        dp.put(got_pooled);
728        dqi.put(q_idx);
729        dbias.put(bias);
730        dsc.alloc((size_t) n_kv);
731        strata::kernels::qsa_index(dp.p, n_bid, dqi.p, dbias.p, S, n_kv, dsc.p, nullptr);
732        const std::vector<float> got = dsc.get((size_t) n_kv);
733        const std::vector<double> want =
734            ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, Alt{});
735
736        // The score is a SUM of four relu'd dots plus the bias, so the denominator is the magnitude of the
737        // TERMS - |dot| bounds a relu'd dot from above and is what is used here.
738        double worst = 0;
739        for (int64_t j = 0; j < n_kv; ++j) {
740            const int64_t cb = std::min(j / R, n_bid);
741            double terms = std::fabs((double) bias[(size_t) cb]);
742            if (cb == n_bid && n_kv % R != 0) terms += 1e9;
743            for (int64_t h = 0; h < IDXN; ++h) {
744                double dot = 0;
745                for (int64_t d = 0; d < IDXD; ++d) dot += p64[(size_t) cb * IDXD + d] * q_idx64[(size_t) h * IDXD + d];
746                terms += std::fabs(dot);
747            }
748            worst = std::max(worst, rel_terms(want[(size_t) j], (double) got[(size_t) j], terms));
749        }
750        report("indexer cell scores vs the reference", worst, "rel/Sum|terms|");
751        if (!(worst <= 1e-6)) { std::printf("    *** over 1e-6 ***\n"); ++g_bad; }
752
753        require("cells of one block share its score (0..3)",
754                got[0] == got[1] && got[1] == got[2] && got[2] == got[3] && got[0] != got[4]);
755        require("cells 8,9 (the tail) take the SPARE slot's score, not block 1's",
756                got[8] == got[9] && got[9] != got[7], "got[8] == got[9] != got[7]");
757
758        auto sep_scores = [&](const std::string& name, const Alt& a) {
759            const std::vector<double> alt = ref_indexer_scores(p64, n_bid, q_idx64, IDXN, IDXD, bias, n_kv, a);
760            double num = 0, den = 0;
761            // The mandatory tail bias must not swamp the score-arithmetic fixture.
762            for (int64_t j = 0; j < n_bid * R; ++j) {
763                num += std::fabs(alt[(size_t) j] - want[(size_t) j]);
764                den += std::fabs(want[(size_t) j]);
765            }
766            verdict(name, num / den > 0.05, pct(num / den));
767        };
768        Alt a5; a5.relu_per_head = false;
769        sep_scores("relu PER HEAD vs relu(sum of heads) is observable", a5);
770        Alt a6; a6.use_relu = false;
771        sep_scores("dropping the relu is observable", a6);
772        Alt a7; a7.use_bias = false;
773        sep_scores("dropping the per-block bias is observable", a7);
774    }
775
776    // Causal decode's incomplete tail must survive even when its dot-product score
777    // ties every completed block. The oracle supplies +1e9 in set_input_qsa;
778    // without it, ascending-index top-k drops every tail after the sparse switch.
779    // Replay one captured graph across block/page boundaries to catch stale bias.
780    {
781        const int64_t max_n = 20480;
782        const int64_t max_blocks = max_n / R + 1;
783        const int64_t cap = strata::kernels::qsa_selection_width(max_n, S);
784        Dev<float> pooled, query, scores((size_t) max_n);
785        Dev<int32_t> ids((size_t) cap), step(strata::kernels::kStepCount);
786        pooled.put(std::vector<float>((size_t) max_blocks * IDXD, 0.0f));
787        query.put(std::vector<float>((size_t) IDXN * IDXD, 0.0f));
788
789        dpct::queue_ptr stream;
790        dpct::experimental::command_graph_ptr graph;
791        dpct::experimental::command_graph_exec_ptr exec;
792        check(DPCT_CHECK_ERROR(
793                  stream = dpct::get_current_device().create_queue(true)),
794              "tail stream");
795        check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(stream)),
796              "tail capture begin");
797        strata::kernels::qsa_index_step(pooled.p, query.p, nullptr, S, step.p, max_blocks, scores.p, stream);
798        strata::kernels::topk_512_step(scores.p, S, cap, step.p, ids.p, stream);
799        check(
800            DPCT_CHECK_ERROR(dpct::experimental::end_recording(stream, &graph)),
801            "tail capture end");
802        check(DPCT_CHECK_ERROR(
803                  exec = new sycl::ext::oneapi::experimental::command_graph<
804                      sycl::ext::oneapi::experimental::graph_state::executable>(
805                      graph->finalize())),
806              "tail instantiate");
807
808        const std::vector<int64_t> counts = {
809            1, 2, 3, 4, 511, 512, 513, 2046, 2047, 2048, 2049, 2050, 2051,
810            2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060,
811            4095, 4096, 4097, 8191, 8192, 8193, 20477, 20478, 20479, 20480};
812        for (const int64_t n : counts) {
813            const int64_t width = strata::kernels::qsa_selection_width(n, S);
814            const int64_t tail = n % R;
815            std::vector<int32_t> want;
816            for (int64_t j = 0; j < width - tail; ++j) want.push_back((int32_t) j);
817            for (int64_t j = n - tail; j < n; ++j) want.push_back((int32_t) j);
818
819            strata::kernels::qsa_index(pooled.p, n / R, query.p, nullptr, S, n, scores.p, nullptr);
820            strata::kernels::topk_512(scores.p, n, S, cap, ids.p, nullptr);
821            require("tail static n=" + std::to_string(n), ids.get((size_t) width) == want);
822
823            std::vector<int32_t> values(strata::kernels::kStepCount);
824            strata::kernels::qsa_step_fill(values.data(), n - 1, S);
825            step.put(values);
826            check(DPCT_CHECK_ERROR(stream->ext_oneapi_graph(*exec)),
827                  "tail replay");
828            check(DPCT_CHECK_ERROR(stream->wait()), "tail replay sync");
829            require("tail captured n=" + std::to_string(n), ids.get((size_t) width) == want);
830            const auto actual_scores = scores.get((size_t) n);
831            bool exact_scores = true;
832            for (int64_t j = 0; j < n; ++j) {
833                const float expected = j >= n - tail ? 1e9f : 0.0f;
834                exact_scores = exact_scores && actual_scores[(size_t) j] == expected;
835            }
836            require("  only incomplete cells receive the bias", exact_scores);
837        }
838        check(DPCT_CHECK_ERROR(delete (exec)), "tail exec destroy");
839        check(DPCT_CHECK_ERROR(delete (graph)), "tail graph destroy");
840        check(
841            DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(stream)),
842            "tail stream destroy");
843    }
844
845    // ================= 4. topk_512, against an independent sort =================
846    {
847        const int64_t CAP = strata::kernels::qsa_selection_width(MAXC, S);
848        Dev<float> dsc;
849        Dev<int32_t> dids;
850        dsc.alloc((size_t) MAXC);
851        dids.alloc((size_t) CAP);
852        std::vector<float> sc((size_t) MAXC);
853
854        auto one = [&](const std::string& name, int64_t n_kv) {
855            dsc.put(std::vector<float>(sc.begin(), sc.begin() + n_kv));
856            strata::kernels::topk_512(dsc.p, n_kv, S, CAP, dids.p, nullptr);
857            const int64_t width = strata::kernels::qsa_selection_width(n_kv, S);
858            const std::vector<int32_t> g = dids.get((size_t) width);
859            const std::vector<int32_t> want = ref_select(as_d(std::vector<float>(sc.begin(), sc.begin() + n_kv)),
860                                                         n_kv, TOPK, false);
861            const bool ok = g == want;
862            require(name, ok, std::to_string(width) + " ids, width = min(n_kv, top_k + r - 1)");
863            if (!ok) {
864                for (size_t i = 0; i < std::min(g.size(), want.size()); ++i)
865                    if (g[i] != want[i]) {
866                        std::printf("    first difference at %zu: got %d, want %d\n", i, g[i], want[i]);
867                        break;
868                    }
869            }
870            bool asc = true;
871            for (size_t i = 1; i < g.size(); ++i) if (g[i] <= g[i - 1]) asc = false;
872            require("  ...ascending and unique", asc);
873            return g;
874        };
875
876        for (auto& x : sc) x = rnd(1.0);
877        one("topk_512 n_kv = 1", 1);
878        one("topk_512 n_kv = 7 (random)", 7);
879        one("topk_512 n_kv = 2048 (the plan's threshold)", 2048);
880        one("topk_512 n_kv = 2051 (the reference's own bound)", 2051);
881        one("topk_512 n_kv = 2052 (two past the plan's number)", 2052);
882        one("topk_512 n_kv = 5000 (random)", 5000);
883        one("topk_512 n_kv = 32768 (= kTopkMaxCells)", MAXC);
884
885        // ALL-EQUAL scores: every cell ties, so the answer must be 0..width-1 and any other tie rule shows up
886        // on the first element.  ggml does not specify the rule; the reference and the kernel both say
887        // ascending index, and this is the case that distinguishes them.
888        std::fill(sc.begin(), sc.begin() + 2052, 0.25f);
889        one("topk_512 with 2052 EQUAL scores (every cell ties)", 2052);
890
891        // a tie BLOCK straddling the cut: 100 cells share the cut score and only some of them fit
892        for (int64_t j = 0; j < 5000; ++j) sc[(size_t) j] = (float) (-(double) j);
893        for (int64_t j = 2051 - 50; j < 2051 + 50; ++j) sc[(size_t) j] = -1000.0f;
894        one("topk_512 with a 100-cell tie straddling the cut", 5000);
895
896        // THE IDENTITY BELOW THE BOUND.  `select_cells` returns `arange` whenever width == n_kv, which is what
897        // "selection skipped when context <= 2,048" means - and it holds to 2,051, not 2,048.
898        for (int64_t n : {(int64_t) 2048, (int64_t) 2051}) {
899            for (int64_t j = 0; j < n; ++j) sc[(size_t) j] = rnd(1.0);
900            const std::vector<int32_t> g = one(std::string("topk_512 n_kv = ") + std::to_string(n) +
901                                                   " selects every cell (identity)",
902                                               n);
903            bool ident = (int64_t) g.size() == n;
904            for (int64_t j = 0; j < n && ident; ++j) if (g[(size_t) j] != j) ident = false;
905            require("  ...and it really is 0,1,2,...", ident);
906        }
907        {   // one past the bound the identity must FAIL, or the two checks above prove nothing
908            for (int64_t j = 0; j < 2052; ++j) sc[(size_t) j] = rnd(1.0);
909            const std::vector<int32_t> g = one("topk_512 n_kv = 2052 is NOT the identity", 2052);
910            std::vector<char> kept(2052, 0);
911            for (int32_t id : g) kept[(size_t) id] = 1;
912            int64_t missing = 0;
913            for (int64_t j = 0; j < 2052; ++j) if (!kept[(size_t) j]) ++missing;
914            int64_t argmin = 0;
915            for (int64_t j = 1; j < 2052; ++j) if (sc[(size_t) j] < sc[(size_t) argmin]) argmin = j;
916            require("  ...exactly one cell is dropped, and it is the smallest score",
917                    missing == 1 && !kept[(size_t) argmin], std::to_string(missing) + " dropped");
918        }
919    }
920
921    // ================= 5. qsa_attend on the loud-cell fixture =================
922    // `ref/qsa.py` PROPERTY 8's own numbers: a key with 100 in its first dim against zeros, a value of 10
923    // against 1, and q[:,0] = 1.  The logit gap is 100/sqrt(256) = 6.25, so the loud cell takes ~99% of its
924    // head's weight - and exactly zero when it is not in the selected set.
925    {
926        const int64_t N = 8;
927        std::vector<std::vector<double>> k2, v2;
928        std::vector<float> k2f, v2f;
929        for (int64_t j = 0; j < N; ++j) {
930            std::vector<double> kk((size_t) (NKV * HD), 0.0), vv((size_t) (NKV * HD), 0.0);
931            for (int64_t h = 0; h < NKV; ++h) vv[(size_t) (h * HD)] = 1.0;
932            kk[0] = j == N - 1 ? 100.0 : 0.0;
933            vv[0] = j == N - 1 ? 10.0 : 1.0;
934            for (int64_t i = 0; i < NKV * HD; ++i) { k2f.push_back((float) kk[(size_t) i]); v2f.push_back((float) vv[(size_t) i]); }
935            k2.push_back(kk);
936            v2.push_back(vv);
937        }
938        std::vector<double> q((size_t) (NH * HD), 0.0);
939        for (int64_t h = 0; h < NH; ++h) q[(size_t) (h * HD)] = 1.0;
940
941        Dev<float> dq;
942        dq.put(as_f(q));
943        const size_t scr = (size_t) N * NKV * HD;
944        std::vector<uint16_t> kbits(scr), vbits(scr);
945        for (size_t i = 0; i < scr; ++i) { kbits[i] = f16_from_f32(k2f[i]); vbits[i] = f16_from_f32(v2f[i]); }
946        Dev<uint16_t> dks(scr), dvs(scr);
947        dks.put(kbits);
948        dvs.put(vbits);
949        Dev<float> dattn((size_t) NH * HD), dwt((size_t) NH * N);
950
951        std::vector<int32_t> all(N), no_loud(N - 1);
952        for (int64_t j = 0; j < N; ++j) all[(size_t) j] = (int32_t) j;
953        for (int64_t j = 0; j < N - 1; ++j) no_loud[(size_t) j] = (int32_t) j;
954
955        // the scratch is written directly here (no pool), so this section is about the attention alone
956        strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N, S, dattn.p, dwt.p, nullptr);
957        const std::vector<double> out_all = as_d(dattn.get((size_t) NH * HD));
958        strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, N - 1, S, dattn.p, nullptr, nullptr);
959        const std::vector<double> out_sel = as_d(dattn.get((size_t) NH * HD));
960        const std::vector<double> wts = as_d(dwt.get((size_t) NH * N));
961
962        verdict("with every cell selected the loud cell dominates its head 0", out_all[0] > 5.0,
963                "out[0][0] = " + std::to_string(out_all[0]).substr(0, 6));
964        require("with the loud cell unselected it contributes EXACTLY nothing",
965                std::fabs(out_sel[0] - 1.0) < 1e-6, "out[0][0] = " + std::to_string(out_sel[0]).substr(0, 8));
966        double worst_sum = 0;
967        for (int64_t h = 0; h < NH; ++h) {
968            double s = 0;
969            for (int64_t j = 0; j < N; ++j) s += wts[(size_t) (h * N + j)];
970            worst_sum = std::max(worst_sum, std::fabs(s - 1.0));
971        }
972        report("the returned weights sum to 1 per head", worst_sum, "max |1 - sum|");
973
974        auto sep_attend = [&](const std::string& name, const Alt& a) {
975            const std::vector<double> alt = ref_attend(q, NH, NKV, HD, all, k2, v2, a, nullptr);
976            double num = 0, den = 0;
977            for (size_t i = 0; i < alt.size(); ++i) {
978                num += std::fabs(alt[i] - out_all[i]);
979                den += std::fabs(alt[i]);
980            }
981            verdict(name, num / den > 0.05, pct(num / den));
982        };
983        Alt a8; a8.kv_divide = false;
984        sep_attend("q % 2 vs q / 12 for the kv head is observable", a8);
985        // The scale trap is NOT asserted on this fixture: its softmax is saturated (the loud cell holds 99%
986        // of the weight, so removing a 16x logit scale moves it to 100% and the output by 1.09%).  It is
987        // asserted on the random 2100-cell fixture below, where the logits are O(10) and the temperature
988        // actually matters.  This is round 196's lesson about a fixture that cannot see its own trap.
989        std::printf("  %-48s %-6s %s\n", "  (the scale trap is measured on the random fixture)", "--",
990                    "this fixture's softmax is saturated");
991        {   // the mask: the same reference with and without the loud cell in the selected set
992            const std::vector<double> with_loud = ref_attend(q, NH, NKV, HD, all, k2, v2, Alt{}, nullptr);
993            const std::vector<double> without = ref_attend(q, NH, NKV, HD, no_loud, k2, v2, Alt{}, nullptr);
994            double num = 0, den = 0;
995            for (size_t i = 0; i < with_loud.size(); ++i) {
996                num += std::fabs(with_loud[i] - without[i]);
997                den += std::fabs(with_loud[i]);
998            }
999            verdict("attending to the unselected cell is observable", num / den > 0.05, pct(num / den));
1000        }
1001    }
1002
1003    // ================= 6. the whole layer at n_kv = 2100, so the selection is genuinely sparse =============
1004    int64_t width = 0;
1005    {
1006        const int64_t T = 2100;                      // > 2051, so `width` really truncates
1007        width = strata::kernels::qsa_selection_width(T, S);
1008        std::vector<float> pk((size_t) T * NKV * HD), pv((size_t) T * NKV * HD), praw((size_t) T * IDXD);
1009        std::vector<std::vector<double>> k16((size_t) T), v16((size_t) T);
1010        RefCache pc;
1011        std::vector<float> q((size_t) NH * HD);
1012        for (auto& x : q) x = rnd(1.0);
1013        for (int64_t t = 0; t < T; ++t) {
1014            std::vector<double> kk((size_t) (NKV * HD)), vv((size_t) (NKV * HD)), rr((size_t) IDXD);
1015            for (int64_t i = 0; i < NKV * HD; ++i) {
1016                kk[(size_t) i] = gauss(rng);
1017                vv[(size_t) i] = gauss(rng);
1018                pk[(size_t) t * NKV * HD + i] = (float) kk[(size_t) i];
1019                pv[(size_t) t * NKV * HD + i] = (float) vv[(size_t) i];
1020            }
1021            for (int64_t d = 0; d < IDXD; ++d) {
1022                rr[(size_t) d] = gauss(rng);
1023                praw[(size_t) t * IDXD + d] = (float) rr[(size_t) d];
1024            }
1025            for (int64_t i = 0; i < NKV * HD; ++i) {
1026                kk[(size_t) i] = (double) pk[(size_t) t * NKV * HD + i];       // the f32 the device got
1027                vv[(size_t) i] = (double) pv[(size_t) t * NKV * HD + i];
1028            }
1029            for (int64_t d = 0; d < IDXD; ++d) rr[(size_t) d] = (double) praw[(size_t) t * IDXD + d];
1030            pc.append(kk, vv, rr, (double) t);
1031            k16[(size_t) t].resize((size_t) (NKV * HD));
1032            v16[(size_t) t].resize((size_t) (NKV * HD));
1033            for (int64_t i = 0; i < NKV * HD; ++i) {
1034                k16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pk[(size_t) t * NKV * HD + i]));
1035                v16[(size_t) t][(size_t) i] = (double) f32_from_f16(f16_from_f32(pv[(size_t) t * NKV * HD + i]));
1036            }
1037        }
1038        const int64_t p_nbid = T / R;                // 525 complete blocks; the spare key sits at row 525
1039        const int64_t page_size = 64, n_pages = (T + page_size - 1) / page_size;
1040        strata::kernels::QsaShapes Sp = S;           // the granule lives in the shapes: see section 1
1041        Sp.page_size = page_size;
1042        std::vector<int32_t> table((size_t) n_pages);
1043        for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) (n_pages - 1 - i);   // REVERSED
1044
1045        Dev<int32_t> dtab;
1046        dtab.put(table);
1047        Dev<float> dpk_all, dpv_all;
1048        dpk_all.put(pk);
1049        dpv_all.put(pv);
1050        Dev<uint16_t> dpk((size_t) n_pages * NKV * page_size * HD), dpv((size_t) n_pages * NKV * page_size * HD);
1051        for (int64_t t = 0; t < T; ++t)
1052            strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, t, dpk_all.p + (size_t) t * NKV * HD,
1053                                       dpv_all.p + (size_t) t * NKV * HD, Sp, nullptr);
1054
1055        const size_t ppooled_n = (size_t) (p_nbid + 1) * IDXD;
1056        Dev<float> dpp((size_t) ppooled_n), dpdead((size_t) IDXD), dptail((size_t) (R - 1) * IDXD);
1057        Dev<int32_t> dblockpos2(1);
1058        Dev<int32_t> dpos2(1);
1059        Dev<float> draw((size_t) IDXD);
1060        strata::kernels::QsaIndexerBuffers bufs{dptail.p, dpdead.p, dpp.p, dblockpos2.p};
1061        for (int64_t t = 0; t < T; ++t) {
1062            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1063                                       .memcpy(draw.p, &praw[(size_t)t * IDXD],
1064                                               (size_t)IDXD * 4)
1065                                       .wait()),
1066                  "raw");
1067            const int32_t tpos = (int32_t) t;
1068            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1069                                       .memcpy(dpos2.p, &tpos, 4)
1070                                       .wait()),
1071                  "pos2");
1072            strata::kernels::indexer_key_append(draw.p, dpos2.p, 0, dw_kn.p, EPS, bufs, S, dcos.p, dsin.p,
1073                                                nullptr);
1074        }
1075        Dev<float> dqidx, dsc;
1076        dqidx.put(q_idx);
1077        dsc.alloc((size_t) T);
1078        strata::kernels::qsa_index(dpp.p, p_nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr);
1079
1080        Dev<int32_t> dsel((size_t) T);
1081        strata::kernels::topk_512(dsc.p, T, S, T, dsel.p, nullptr);
1082        const std::vector<int32_t> sel_sparse = dsel.get((size_t) width);
1083        const std::vector<float> pool32 = dpp.get(ppooled_n);
1084        const std::vector<double> pool64 = as_d(pool32);
1085        const std::vector<double> q_idx64 = as_d(q_idx);
1086        const std::vector<double> sc_want =
1087            ref_indexer_scores(pool64, p_nbid, q_idx64, IDXN, IDXD, {}, T, Alt{});
1088        const std::vector<int32_t> sel_want = ref_select(sc_want, T, TOPK, false);
1089        require("the selected set matches the reference (2100 cells, width 2051)", sel_sparse == sel_want,
1090                std::to_string(width) + " ids");
1091
1092        // HOW CLOSE IS THE CUT?  `indexer_ids` is an EXACT capture key, so a boundary gap of a few fp32 ulp
1093        // would make it sensitive to the accumulation order.  The gap is measured in ulp of the cut score.
1094        {
1095            std::vector<char> issel((size_t) T, 0);
1096            for (int32_t id : sel_sparse) issel[(size_t) id] = 1;
1097            double lo = 1e300, hi = -1e300;
1098            for (int32_t id : sel_sparse) lo = std::min(lo, sc_want[(size_t) id]);
1099            for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j]) hi = std::max(hi, sc_want[(size_t) j]);
1100            if (lo == hi) {
1101                // The cut sits inside a group of cells that all score exactly the same - here 0.0, a relu
1102                // signal with all four head dots negative - so nothing but the ascending-index rule decides
1103                // which of them survive.  A gap metric is undefined there; the tie is the finding.
1104                int64_t tied_in = 0, tied_out = 0;
1105                for (int32_t id : sel_sparse) if (sc_want[(size_t) id] == lo) ++tied_in;
1106                for (int64_t j = 0; j < T; ++j) if (!issel[(size_t) j] && sc_want[(size_t) j] == lo) ++tied_out;
1107                std::printf("  %-48s      THE CUT IS A TIE at %.6f: %lld selected, %lld rejected\n",
1108                            "the cut", lo, (long long) tied_in, (long long) tied_out);
1109                require("  ...and the kernel picks the same ones as the reference", sel_sparse == sel_want);
1110            } else {
1111                report("the selection boundary gap, in fp32 ulp of the cut",
1112                       (lo - hi) / (std::fabs(lo) * 1.2e-7), "gap/ulp");
1113                std::printf("  %-48s      last selected %.6f, first rejected %.6f\n", "the cut", lo, hi);
1114            }
1115        }
1116
1117        // the pipeline.  `--qsa-dense` swaps the SELECTION for every cell and keeps everything else; the sparse
1118        // selection above is still compared against the reference either way.
1119        std::vector<int32_t> sel = sel_sparse;
1120        if (dense) {
1121            sel.resize((size_t) T);
1122            for (int64_t j = 0; j < T; ++j) sel[(size_t) j] = (int32_t) j;
1123        }
1124        Dev<int32_t> dsel2;
1125        dsel2.put(sel);
1126        const int64_t nsel = (int64_t) sel.size();
1127        Dev<uint16_t> dks((size_t) nsel * NKV * HD), dvs((size_t) nsel * NKV * HD);
1128        strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel2.p, nsel, Sp, dks.p, dvs.p, nullptr);
1129        Dev<float> dqq, dattn((size_t) NH * HD), dwt((size_t) NH * nsel);
1130        dqq.put(q);
1131        strata::kernels::qsa_attend(dqq.p, dks.p, dvs.p, nsel, S, dattn.p, dwt.p, nullptr);
1132        const std::vector<double> attn = as_d(dattn.get((size_t) NH * HD));
1133        const std::vector<double> wts = as_d(dwt.get((size_t) NH * nsel));
1134
1135        const std::vector<double> q64 = as_d(q);
1136        const std::vector<double> attn_f64 = ref_attend(q64, NH, NKV, HD, sel, pc.k, pc.v, Alt{}, nullptr);
1137        const std::vector<double> attn_f16 = ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, nullptr);
1138        double num = 0, den = 0;
1139        for (size_t i = 0; i < attn.size(); ++i) {
1140            num += std::fabs(attn[i] - attn_f16[i]);
1141            den += std::fabs(attn_f16[i]);
1142        }
1143        report("qsa_attend vs the reference on the SAME fp16 cache", num / den, "rel");
1144        {   // the SCALE trap, on data whose softmax is not saturated
1145            Alt a; a.apply_scale = false;
1146            const std::vector<double> alt = ref_attend(q64, NH, NKV, HD, sel, k16, v16, a, nullptr);
1147            double n2 = 0, d2 = 0;
1148            for (size_t i = 0; i < alt.size(); ++i) {
1149                n2 += std::fabs(alt[i] - attn_f16[i]);
1150                d2 += std::fabs(attn_f16[i]);
1151            }
1152            verdict("omitting 1/sqrt(head_dim) is observable (random fixture)", n2 / d2 > 0.05, pct(n2 / d2));
1153        }
1154        if (!(num / den <= 1e-5)) { std::printf("    *** over 1e-5 ***\n"); ++g_bad; }
1155        const double fp16_cost = rel_l1(attn_f64, attn_f16);
1156        report("the fp16 KV cache's OWN cost (f32 keys vs fp16 keys)", fp16_cost, "rel");
1157        if (!(fp16_cost <= 1e-3)) {
1158            std::printf("    *** the phase's 1e-3 for FP16 paths is exceeded by the CACHE ***\n");
1159            ++g_bad;
1160        }
1161        {
1162            std::vector<double> w_ref;
1163            ref_attend(q64, NH, NKV, HD, sel, k16, v16, Alt{}, &w_ref);
1164            double wn = 0, wd = 0;
1165            for (int64_t j = 0; j < nsel; ++j) {
1166                wn += std::fabs(wts[(size_t) j] - w_ref[(size_t) j]);
1167                wd += std::fabs(w_ref[(size_t) j]);
1168            }
1169            report("the returned weights vs the reference (head 0)", wn / wd, "rel");
1170        }
1171
1172        // the gate
1173        std::vector<float> q_full((size_t) (NH * 2 * HD));
1174        for (auto& x : q_full) x = rnd(2.0);
1175        Dev<float> dqf, dattnf;
1176        dqf.put(q_full);
1177        dattnf.put(as_f(attn));
1178        Dev<uint16_t> dgate((size_t) NH * HD);
1179        strata::kernels::qsa_gate_apply(dattnf.p, dqf.p, S, dgate.p, nullptr);
1180        const std::vector<uint16_t> gate16 = dgate.get((size_t) NH * HD);
1181        const std::vector<double> qf64 = as_d(q_full);
1182        const std::vector<double> gwant = ref_gate(attn, qf64, NH, HD, Alt{});
1183        double gnum = 0, gden = 0;
1184        int gbits = 0;
1185        for (size_t i = 0; i < gwant.size(); ++i) {
1186            gnum += std::fabs((double) f32_from_f16(gate16[i]) - gwant[i]);
1187            gden += std::fabs(gwant[i]);
1188            if (gate16[i] != f16_from_f32((float) gwant[i])) ++gbits;
1189        }
1190        report("qsa_gate_apply vs the double reference", gnum / gden, "rel (f16 out quant ~2.4e-4)");
1191        if (!(gnum / gden <= 1e-3)) { std::printf("    *** over 1e-3 ***\n"); ++g_bad; }
1192        std::printf("  %-48s      %d of %lld (CUDA's double exp vs libm's, in the last bits)\n",
1193                    "fp16 gate bits differing from the reference", gbits, (long long) gwant.size());
1194
1195        auto sep_gate = [&](const std::string& name, const Alt& a) {
1196            const std::vector<double> alt = ref_gate(attn, qf64, NH, HD, a);
1197            double n2 = 0, d2 = 0;
1198            for (size_t i = 0; i < alt.size(); ++i) {
1199                n2 += std::fabs(alt[i] - gwant[i]);
1200                d2 += std::fabs(gwant[i]);
1201            }
1202            verdict(name, n2 / d2 > 0.05, pct(n2 / d2));
1203        };
1204        Alt a10; a10.gate_second_half = false;
1205        sep_gate("the gate from the FIRST half is observable", a10);
1206        Alt a11; a11.gate_sigmoid = false;
1207        sep_gate("silu instead of sigmoid on the QSA gate is observable", a11);
1208
1209        // DENSE vs SPARSE.  Below the bound the width IS n_kv, so the two paths must agree EXACTLY (P1.S4's
1210        // isolation property, `ref/qsa.py` PROPERTY 9b); above it they must differ, or the switch is a no-op.
1211        require("below the bound, dense and sparse are the SAME selection",
1212                ref_select(sc_want, 2000, TOPK, false) == ref_select(sc_want, 2000, TOPK, true));
1213        {
1214            // BOTH SIDES COMPUTED HERE, from their own id lists and independently of `--qsa-dense`.  The first
1215            // version compared against the pipeline's `attn`, which in dense mode IS the dense attention - so the
1216            // switch silently turned the check into a comparison of a thing with itself and reported 0.00%.
1217            const std::vector<int32_t> dense_all = ref_select(sc_want, T, TOPK, true);
1218            auto attend_ids = [&](const std::vector<int32_t>& ids) {
1219                Dev<int32_t> did;
1220                did.put(ids);
1221                Dev<uint16_t> dk2((size_t) ids.size() * NKV * HD), dv2((size_t) ids.size() * NKV * HD);
1222                strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, did.p, (int64_t) ids.size(), Sp, dk2.p, dv2.p,
1223                                           nullptr);
1224                Dev<float> da((size_t) NH * HD);
1225                strata::kernels::qsa_attend(dqq.p, dk2.p, dv2.p, (int64_t) ids.size(), S, da.p, nullptr, nullptr);
1226                return as_d(da.get((size_t) NH * HD));
1227            };
1228            const std::vector<double> dense_attn = attend_ids(dense_all);
1229            const std::vector<double> sparse_attn = attend_ids(sel_sparse);
1230            double dn = 0, dd = 0;
1231            for (size_t i = 0; i < sparse_attn.size(); ++i) {
1232                dn += std::fabs(dense_attn[i] - sparse_attn[i]);
1233                dd += std::fabs(sparse_attn[i]);
1234            }
1235            verdict("dense differs from sparse at n_kv = 2100 (> 2051)", dn / dd > 0.05, pct(dn / dd));
1236        }
1237    }
1238
1239    // ================= 7. the empty selection =================
1240    {
1241        Dev<float> dq((size_t) NH * HD), dattn((size_t) NH * HD);
1242        dq.put(std::vector<float>((size_t) NH * HD, 1.0f));
1243        dattn.put(std::vector<float>((size_t) NH * HD, 7.0f));
1244        strata::kernels::qsa_attend(dq.p, nullptr, nullptr, 0, S, dattn.p, nullptr, nullptr);
1245        const std::vector<float> got = dattn.get((size_t) NH * HD);
1246        bool allz = true;
1247        for (float x : got) if (x != 0.0f) allz = false;
1248        require("an EMPTY selection gives a zero attention, not a NaN", allz, "all 6144 elements zero");
1249    }
1250
1251    // ================= 8. --bench: what one QSA layer costs at 32K of context =================
1252    if (bench) {
1253        const int64_t T = MAXC;                      // 32,768 cells = 32K of context
1254        const int64_t nbid = T / R;
1255        const int64_t ps = S.page_size, n_pages = (T + ps - 1) / ps;
1256        const int64_t w = strata::kernels::qsa_selection_width(T, S);
1257        std::printf("\n  --bench at n_kv = %lld, page_size %lld, selection width %lld\n", (long long) T,
1258                    (long long) ps, (long long) w);
1259        std::vector<int32_t> table((size_t) n_pages);
1260        for (int64_t i = 0; i < n_pages; ++i) table[(size_t) i] = (int32_t) i;
1261        Dev<int32_t> dtab;
1262        dtab.put(table);
1263        Dev<uint16_t> dpk((size_t) n_pages * NKV * ps * HD), dpv((size_t) n_pages * NKV * ps * HD);
1264        std::vector<float> kz((size_t) NKV * HD), vz((size_t) NKV * HD);
1265        for (auto& x : kz) x = rnd(1.0);
1266        for (auto& x : vz) x = rnd(1.0);
1267        Dev<float> dkz, dvz;
1268        dkz.put(kz);
1269        dvz.put(vz);
1270        strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr);
1271
1272        const size_t ppooled_n = (size_t) (nbid + 1) * IDXD;
1273        Dev<float> dpp((size_t) ppooled_n), dsc((size_t) T);
1274        std::vector<float> pz(ppooled_n), sz((size_t) T);
1275        for (auto& x : pz) x = rnd(0.1f);
1276        for (auto& x : sz) x = std::fabs(rnd(1.0f));
1277        dpp.put(pz);
1278        dsc.put(sz);
1279        Dev<float> dqidx;
1280        dqidx.put(q_idx);
1281        Dev<int32_t> dsel((size_t) w);
1282        Dev<uint16_t> dks((size_t) w * NKV * HD), dvs((size_t) w * NKV * HD);
1283        Dev<float> dq((size_t) NH * HD), dattn((size_t) NH * HD), dwt((size_t) NH * w);
1284        std::vector<float> qv((size_t) NH * HD);
1285        for (auto& x : qv) x = rnd(1.0);
1286        dq.put(qv);
1287
1288        auto timeit = [&](const std::string &name, int reps,
1289                          const std::function<void()> &fn) {
1290            try {
1291        dpct::event_ptr a, b;
1292            a = new sycl::event();
1293            b = new sycl::event();
1294            fn();
1295            dpct::get_current_device().queues_wait_and_throw();
1296            dpct::sync_barrier(a);
1297            for (int i = 0; i < reps; ++i) fn();
1298            dpct::sync_barrier(b);
1299            b->wait_and_throw();
1300            float ms = 0;
1301            ms = (b->get_profiling_info<
1302                      sycl::info::event_profiling::command_end>() -
1303                  a->get_profiling_info<
1304                      sycl::info::event_profiling::command_start>()) /
1305                 1000000.0f;
1306            std::printf("  %-48s %8.1f us\n", name.c_str(), ms * 1000.0f / (float) reps);
1307            dpct::destroy_event(a);
1308            dpct::destroy_event(b);
1309        }
1310        catch (sycl::exception const &exc) {
1311          std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1312                    << ", line:" << __LINE__ << std::endl;
1313          std::exit(1);
1314        }
1315        };
1316        const int reps = 20;
1317        timeit("qsa_index  (8193 pooled rows x 4 heads)", reps,
1318               [&] { strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr); });
1319        timeit("topk_512   (32768 cells)", reps,
1320               [&] { strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr); });
1321        strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr);
1322        timeit("kv_gather  (2051 ids through the page table)", reps,
1323               [&] { strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr); });
1324        timeit("qsa_attend (2051 selected, 24 heads)", reps,
1325               [&] { strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr); });
1326        timeit("kv_append  (one cell, 2 heads x 256)", 200,
1327               [&] { strata::kernels::kv_append(dpk.p, dpv.p, dtab.p, 0, dkz.p, dvz.p, S, nullptr); });
1328        timeit("ONE QSA LAYER (index+topk+gather+attend)", reps, [&] {
1329            strata::kernels::qsa_index(dpp.p, nbid, dqidx.p, nullptr, S, T, dsc.p, nullptr);
1330            strata::kernels::topk_512(dsc.p, T, S, w, dsel.p, nullptr);
1331            strata::kernels::kv_gather(dpk.p, dpv.p, dtab.p, dsel.p, w, S, dks.p, dvs.p, nullptr);
1332            strata::kernels::qsa_attend(dq.p, dks.p, dvs.p, w, S, dattn.p, dwt.p, nullptr);
1333        });
1334    }
1335
1336    // ================= 6. indexer_key_append IS CAPTURABLE =================
1337    //
1338    // THE PROPERTY THE DEVICE-POSITION REFACTOR WAS FOR, TESTED DIRECTLY rather than argued.  `indexer_key_append`
1339    // took `int64_t pos` as a host scalar, which a CUDA graph bakes in at capture time - so a captured call
1340    // would replay the first token's position forever: `slot = pos % r` never advances, no block completes, and
1341    // the indexer keeps pooling cells 0-3 for the whole sequence.
1342    //
1343    // The test captures ONE call, then replays the SAME graph twice with `pos_dev` and `raw` changed between
1344    // them, and requires the second replay to land in a DIFFERENT pooled row with the reference's value.  If the
1345    // position were still baked in, both replays would write row 0 and the pooled rows would be identical.
1346    //
1347    // That is the negative control built into the assertion: "row 1 is correct" alone could also pass for a
1348    // graph that reread the position by accident, but "row 0 unchanged AND row 1 correct AND row 1 != row 0"
1349    // cannot pass for a baked-in position.
1350    {
1351        std::printf("\n-- indexer_key_append under graph capture\n");
1352        const int R2 = 4;
1353        const int64_t NCELL = 8;                       // two complete blocks of r=4
1354        const size_t IDXD2 = (size_t) IDXD;
1355        std::vector<float> raw2((size_t) NCELL * IDXD2);
1356        for (size_t i = 0; i < raw2.size(); ++i) raw2[i] = (float) std::sin((double) i * 0.013) * 2.0f - 0.3f;
1357
1358        const int64_t nb2 = NCELL / R2;
1359        Dev<float> pooled2((size_t) (nb2 + 2) * IDXD2), dead2(IDXD2), tail2((size_t) (R2 - 1) * IDXD2);
1360        Dev<int32_t> bpos2(1), pos2(1);
1361        Dev<float> raw2d(IDXD2);
1362        strata::kernels::QsaIndexerBuffers bufs2{tail2.p, dead2.p, pooled2.p, bpos2.p};
1363
1364        // capture ONE call, on its own stream
1365        dpct::queue_ptr cs = &dpct::get_in_order_queue();
1366        check(DPCT_CHECK_ERROR(
1367                  cs = dpct::get_current_device().create_queue(true)),
1368              "cs");
1369        check(DPCT_CHECK_ERROR(dpct::experimental::begin_recording(cs)),
1370              "begincap");
1371        strata::kernels::indexer_key_append(raw2d.p, pos2.p, POS_BASE, dw_kn.p, EPS, bufs2, S, dcos.p, dsin.p,
1372                                            (void*) cs);
1373        dpct::experimental::command_graph_ptr g2 = nullptr;
1374        check(DPCT_CHECK_ERROR(dpct::experimental::end_recording(cs, &g2)),
1375              "endcap");
1376        check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(cs)),
1377              "csd");
1378        size_t nodes2 = 0;
1379        check(DPCT_CHECK_ERROR(
1380                  dpct::experimental::get_nodes(g2, nullptr, &nodes2)),
1381              "nodes");
1382        dpct::experimental::command_graph_exec_ptr ex2 = nullptr;
1383        check(DPCT_CHECK_ERROR(
1384                  ex2 = new sycl::ext::oneapi::experimental::command_graph<
1385                      sycl::ext::oneapi::experimental::graph_state::executable>(
1386                      g2->finalize())),
1387              "inst");
1388
1389        // replay A: cells 0..3, which completes block 0
1390        for (int t = 0; t < 4; ++t) {
1391            check(DPCT_CHECK_ERROR(
1392                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1393                          .memcpy(raw2d.p, &raw2[(size_t)t * IDXD2], IDXD2 * 4)
1394                          .wait()),
1395                  "r2");
1396            const int32_t tp = t;
1397            check(DPCT_CHECK_ERROR(
1398                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(pos2.p, &tp, 4).wait()),
1399                  "p2");
1400            check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().ext_oneapi_graph(*ex2)),
1401                  "launchA");
1402        }
1403        const std::vector<float> afterA = pooled2.get((size_t) (nb2 + 2) * IDXD2);
1404
1405        // replay B: cells 4..7 through the SAME graph, which completes block 1
1406        for (int t = 4; t < 8; ++t) {
1407            check(DPCT_CHECK_ERROR(
1408                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1409                          .memcpy(raw2d.p, &raw2[(size_t)t * IDXD2], IDXD2 * 4)
1410                          .wait()),
1411                  "r3");
1412            const int32_t tp = t;
1413            check(DPCT_CHECK_ERROR(
1414                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(pos2.p, &tp, 4).wait()),
1415                  "p3");
1416            check(DPCT_CHECK_ERROR(dpct::get_in_order_queue().ext_oneapi_graph(*ex2)),
1417                  "launchB");
1418        }
1419        check(DPCT_CHECK_ERROR(
1420                  dpct::get_current_device().queues_wait_and_throw()),
1421              "sync2");
1422        const std::vector<float> afterB = pooled2.get((size_t) (nb2 + 2) * IDXD2);
1423
1424        std::printf("  %-44s %zu nodes for one call\n", "the pooled kernel is capturable", nodes2);
1425
1426        // row 0 must be UNTOUCHED by the second block's replays
1427        int row0_same = 0;
1428        for (size_t d = 0; d < IDXD2; ++d)
1429            if (afterA[d] == afterB[d]) ++row0_same;
1430        std::printf("  %-44s %d of %zu unchanged\n", "the first block's row survives replay B", row0_same,
1431                    IDXD2);
1432        if (row0_same != (int) IDXD2) ++g_bad;
1433
1434        // row 1 must now be FILLED by the captured graph - the whole point
1435        int row1_nonzero = 0;
1436        for (size_t d = 0; d < IDXD2; ++d)
1437            if (afterB[IDXD2 + d] != 0.0f) ++row1_nonzero;
1438        std::printf("  %-44s %d of %zu non-zero\n", "the SECOND block's row arrives through the same graph",
1439                    row1_nonzero, IDXD2);
1440        if (row1_nonzero != (int) IDXD2) ++g_bad;
1441
1442        // and the two rows must DIFFER, which a baked-in position cannot produce
1443        int rows_differ = 0;
1444        for (size_t d = 0; d < IDXD2; ++d)
1445            if (afterB[d] != afterB[IDXD2 + d]) ++rows_differ;
1446        std::printf("  %-44s %d of %zu differ\n", "the two pooled rows are different keys", rows_differ,
1447                    IDXD2);
1448        // A baked-in position would have written row 0 a second time and left row 1 at zero, so these two
1449        // assertions together are the negative control for the refactor.
1450        if (rows_differ != (int) IDXD2) ++g_bad;
1451
1452        check(DPCT_CHECK_ERROR(delete (ex2)), "exd");
1453        check(DPCT_CHECK_ERROR(delete (g2)), "gd");
1454    }
1455
1456    // ================= the NATIVE indexer's batched append vs the sequential one =================
1457    // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends
1458    // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's
1459    // one-rotation rule).  So the batch's whole end state must be BIT-IDENTICAL to the sequential appends',
1460    // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction)
1461    // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling.
1462    // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would
1463    // pass a NaN-payload or -0.0 flip that the claim does not cover.  Eight cells: exactly two completed
1464    // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential
1465    // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own
1466    // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract).
1467    {
1468        std::printf("\n-- the native indexer's batched append vs the sequential one\n");
1469        const int64_t NB = 8;                          // exactly two complete blocks of r=4
1470        const int32_t BASE = 100;                      // positions 100..107, not cell indices 0..7
1471        const int64_t MC = 1024;                       // the capacity both sides validate against
1472        using RST = strata::kernels::RopeScalingType;
1473        struct Variant { const char* name; RST type; double factor; double ext; };
1474        const Variant variants[] = {{"none", RST::None, 1.0, 0.0},
1475                                    {"linear 2", RST::Linear, 2.0, 0.0},
1476                                    {"yarn 2", RST::YaRN, 2.0, 1.0}};
1477        std::vector<float> raws((size_t) NB * IDXD);
1478        for (int64_t t = 0; t < NB; ++t)
1479            for (int64_t d = 0; d < IDXD; ++d)
1480                raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4)));
1481        dpct::queue_ptr cs = &dpct::get_in_order_queue();
1482        check(DPCT_CHECK_ERROR(
1483                  cs = dpct::get_current_device().create_queue(true)),
1484              "cs");
1485        std::vector<float> none_pooled;
1486        for (const Variant& var : variants) {
1487            strata::kernels::RopeScaling sc;
1488            sc.type = var.type;
1489            sc.factor = var.factor;
1490            sc.ext_factor = var.ext;
1491            const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD;
1492            Dev<float> pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows);
1493            Dev<int32_t> bposA(1), bposB(1), dpos(1);
1494            for (Dev<float>* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB})
1495                check(
1496                    DPCT_CHECK_ERROR(
1497                        (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1498                            .memset(dp->p, 0,
1499                                    dp == &pooledA || dp == &pooledB ? prows * 4
1500                                    : dp == &deadA || dp == &deadB   ? IDXD * 4
1501                                                                   : trows * 4)
1502                            .wait()),
1503                    "zero");
1504            check(DPCT_CHECK_ERROR(
1505                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(bposA.p, 0, 4).wait()),
1506                  "zero");
1507                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1508                                           .memset(bposB.p, 0, 4)
1509                                           .wait()),
1510                      "zero");
1511            Dev<float> draw((size_t) IDXD), drawAll;
1512            drawAll.put(raws);
1513            strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p};
1514            strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p};
1515            for (int64_t t = 0; t < NB; ++t) {         // the sequential side: one cell, its device position
1516                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1517                                           .memcpy(draw.p,
1518                                                   &raws[(size_t)t * IDXD],
1519                                                   (size_t)IDXD * 4)
1520                                           .wait()),
1521                      "raw");
1522                const int32_t tp = (int32_t) t;
1523                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1524                                           .memcpy(dpos.p, &tp, 4)
1525                                           .wait()),
1526                      "pos");
1527                strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs);
1528                // SYCL port: cudaMemcpy on the legacy stream waited for this append before the next copy refilled
1529                // `draw`; a default-queue copy does not wait for work on `cs`, so without this the next cell's raw
1530                // keys could overwrite this one before the kernel reads them
1531                check(DPCT_CHECK_ERROR(cs->wait()), "append");
1532            }
1533            strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs);
1534            // #783 PR-d: native_qsa_indexer_append_steps - the verify window's n cells in one launch (positions at a
1535            // stride: kStepCount in a window, 1 in the commit graph) - leaves the same buffers as the sequential calls
1536            for (const int stride : {1, 5}) {
1537                Dev<float> pooledC(prows), deadC(IDXD), tailC(trows);
1538                Dev<int32_t> bposC(1), dposC((size_t) NB * stride);
1539                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1540                                           .memset(pooledC.p, 0, prows * 4)
1541                                           .wait()),
1542                      "zero");
1543                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1544                                           .memset(deadC.p, 0, IDXD * 4)
1545                                           .wait()),
1546                      "zero");
1547                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1548                                           .memset(tailC.p, 0, trows * 4)
1549                                           .wait()),
1550                      "zero");
1551                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1552                                           .memset(bposC.p, 0, 4)
1553                                           .wait()),
1554                      "zero");
1555                std::vector<int32_t> hp((size_t) NB * stride, -1);
1556                for (int64_t t = 0; t < NB; ++t) hp[(size_t) t * stride] = (int32_t) t;
1557                /*
1558                DPCT1114: cudaMemcpy is migrated to asynchronization
1559                memcpy, assuming in the original code the source host memory is
1560                pageable memory. If the memory is not pageable, call wait() on
1561                event return by memcpy API to ensure synchronization behavior.
1562                */
1563                check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(
1564                          dposC.p, hp.data(), hp.size() * 4).wait()),
1565                      "pos");
1566                strata::kernels::QsaIndexerBuffers bufsC{tailC.p, deadC.p, pooledC.p, bposC.p};
1567                strata::kernels::native_qsa_indexer_append_steps(drawAll.p, dposC.p, stride, (int) NB, BASE, dw_kn.p, EPS,
1568                                                                 bufsC, S, MC, sc, cs);
1569                check(DPCT_CHECK_ERROR(cs->wait()), "sync");
1570                const std::vector<float> pc = pooledC.get(prows), dc = deadC.get((size_t) IDXD), tc = tailC.get(trows);
1571                const std::vector<int32_t> bc = bposC.get(1);
1572                const std::vector<float> pa2 = pooledA.get(prows), da2 = deadA.get((size_t) IDXD), ta2 = tailA.get(trows);
1573                const std::vector<int32_t> ba2 = bposA.get(1);
1574                const bool same = std::memcmp(pc.data(), pa2.data(), pc.size() * 4) == 0 &&
1575                                  std::memcmp(dc.data(), da2.data(), dc.size() * 4) == 0 &&
1576                                  std::memcmp(tc.data(), ta2.data(), tc.size() * 4) == 0 && bc[0] == ba2[0];
1577                std::printf("  %-44s %s\n", (std::string("append_steps (stride ") + std::to_string(stride) + ") vs sequential, " + var.name).c_str(),
1578                            same ? "bit-identical" : "*** WRONG ***");
1579                if (!same) ++g_bad;
1580            }
1581            check(DPCT_CHECK_ERROR(cs->wait()), "sync");
1582            const std::vector<float> pa = pooledA.get(prows), pb = pooledB.get(prows);
1583            const std::vector<float> da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD);
1584            const std::vector<float> ta = tailA.get(trows), tbb = tailB.get(trows);
1585            const std::vector<int32_t> ba = bposA.get(1), bb = bposB.get(1);
1586            long long bad = 0;
1587            for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0;
1588            for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0;
1589            for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0;
1590            bad += std::memcmp(&ba[0], &bb[0], 4) != 0;
1591            std::printf("  %-44s %s (%lld of %zu state words differ)\n",
1592                        (std::string("batch vs sequential, ") + var.name).c_str(),
1593                        bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1);
1594            if (bad) ++g_bad;
1595            if (var.type == RST::None) none_pooled = pa;
1596            else {
1597                int moved = 0;
1598                for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0;
1599                std::printf("  %-44s %d of %zu pooled words differ from the none baseline\n",
1600                            (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size());
1601                if (!moved) { std::printf("    *** the batched append ignored its scaling ***\n"); ++g_bad; }
1602            }
1603        }
1604        check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(cs)),
1605              "csd");
1606    }
1607
1608    // ================= the spare (position 0) under rope scaling: the table indexer vs the native one =========
1609    // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0.  Its sine is
1610    // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the
1611    // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and
1612    // the native kernel's spare carry.  The table kernel used to skip the rotation at position 0, which left
1613    // the spare the one unscaled key of a scaled cache.  Asserted per variant: the table spare is BIT-EXACTLY
1614    // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals
1615    // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and
1616    // under YaRN the factor is observable (row 0 is not 1).
1617    {
1618        std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n");
1619        using RST = strata::kernels::RopeScalingType;
1620        struct Variant { const char* name; RST type; double factor; double ext; };
1621        const Variant variants[] = {{"none", RST::None, 1.0, 0.0},
1622                                    {"linear 2", RST::Linear, 2.0, 0.0},
1623                                    {"yarn 2", RST::YaRN, 2.0, 1.0}};
1624        const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot;
1625        std::vector<float> raw0((size_t) IDXD);
1626        for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0);
1627        Dev<float> draw0;
1628        draw0.put(raw0);
1629        Dev<int32_t> dpos0(1);
1630        const int32_t zero = 0;
1631        check(DPCT_CHECK_ERROR(
1632                  (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(dpos0.p, &zero, 4).wait()),
1633              "pos0");
1634        dpct::queue_ptr cs = &dpct::get_in_order_queue();
1635        check(DPCT_CHECK_ERROR(
1636                  cs = dpct::get_current_device().create_queue(true)),
1637              "cs");
1638        const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD;
1639        // one cell at position 0 through either kernel; returns (dead, pooled[0])
1640        auto spare = [&](bool native, const strata::kernels::RopeScaling &sc,
1641                         std::vector<float> &dead,
1642                         std::vector<float> &pooled0) {
1643            try {
1644                         Dev<float> pooled(prows), dd((size_t)IDXD), tail(trows);
1645            Dev<int32_t> bpos(1);
1646            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1647                                       .memset(pooled.p, 0, prows * 4)
1648                                       .wait()),
1649                  "zero");
1650            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1651                                       .memset(dd.p, 0, (size_t)IDXD * 4)
1652                                       .wait()),
1653                  "zero");
1654            check(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
1655                                       .memset(tail.p, 0, trows * 4)
1656                                       .wait()),
1657                  "zero");
1658            check(DPCT_CHECK_ERROR(
1659                      (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(bpos.p, 0, 4).wait()),
1660                  "zero");
1661            strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p};
1662            if (native) {
1663                strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs);
1664            } else {
1665                std::vector<float> tc((size_t) (MC * HALF)), ts(tc.size());
1666                strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data());
1667                Dev<float> dc, dsn;
1668                dc.put(tc);
1669                dsn.put(ts);
1670                strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs);
1671            }
1672            check(DPCT_CHECK_ERROR(cs->wait()), "sync");
1673            dead = dd.get((size_t) IDXD);
1674            pooled0 = pooled.get((size_t) IDXD);
1675        }
1676                         catch (sycl::exception const &exc) {
1677                           std::cerr << exc.what()
1678                                     << "Exception caught at file:" << __FILE__
1679                                     << ", line:" << __LINE__ << std::endl;
1680                           std::exit(1);
1681                         }
1682        };
1683        std::vector<float> t_none, t_none_p, n_none, n_none_p;
1684        for (const Variant& var : variants) {
1685            strata::kernels::RopeScaling sc;
1686            sc.type = var.type;
1687            sc.factor = var.factor;
1688            sc.ext_factor = var.ext;
1689            std::vector<float> row0c((size_t) (MC * HALF)), row0s(row0c.size());
1690            strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data());
1691            std::vector<float> td, tp, nd, np;
1692            spare(false, sc, td, tp);
1693            spare(true, sc, nd, np);
1694            if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; }
1695            long long tbad = 0, pbad = 0, sin_bad = 0;
1696            double nworst = 0;
1697            for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f;
1698            for (int64_t d = 0; d < IDXD; ++d) {
1699                const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f;
1700                const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d];
1701                tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0;
1702                pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0;
1703                const double nwant = (double) n_none[(size_t) d] * (double) c0;
1704                const double den = std::max(std::fabs(nwant), 1e-6);
1705                nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den);
1706            }
1707            require(std::string("  ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0,
1708                    std::to_string(sin_bad) + " nonzero sines");
1709            require(std::string("  ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT",
1710                    tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong");
1711            require(std::string("  ") + var.name + ": the table's pooled[0] is its spare", pbad == 0,
1712                    std::to_string(pbad) + " wrong");
1713            require(std::string("  ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7,
1714                    "worst relative " + std::to_string(nworst));
1715            if (var.type == RST::YaRN) {
1716                int moved = 0;
1717                for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0;
1718                require("  yarn 2: the magnitude correction is observable on the table spare",
1719                        row0c[0] != 1.0f && moved > NROT / 2,
1720                        "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved");
1721            }
1722        }
1723        check(DPCT_CHECK_ERROR(dpct::get_current_device().destroy_queue(cs)),
1724              "csd");
1725    }
1726
1727    std::printf("\nqsa: %d failures\n", g_bad);
1728    if (g_bad) return 1;
1729    if (selftest) std::printf("qsa_parity OK\n");
1730    return 0;
1731}