okami.mom/strata

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

Niko1221Merge f-latency into f-144-rel0b8d31013

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