okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
61.7 KiB1278 linesraw
1// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp).
2//
3// The header documents the layouts and the scope; this file documents the four decisions that are about the
4// KERNEL rather than about the interface.
5//
6// 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT.  The selection has to reproduce `ggml_top_k` on the
7//    masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a
8//    different selected set is a different attention input, and `docs/capture-format.md` L127 gives
9//    `indexer_ids` no tolerance.  The kernel therefore computes the width-th largest score as a 32-bit
10//    "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits -
11//    in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it.  That
12//    is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no
13//    scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection
14//    runs in ONE block so the ascending walk is a chunked scan rather than a second global pass.  Phase 3
15//    replaces it with a radix select; this one is the thing that radix select has to agree with.
16//
17// 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY.  n_ids reaches 2051, so a per-head score
18//    vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a
19//    small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps
20//    the softmax's three passes over the scores in shared memory instead of in global.  The score loop has one
21//    thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value
22//    loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell.  Both
23//    are coalesced for the layout the gather produces.
24//
25// 3. NO `__float2half`.  `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half`
26//    produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0.  The parity test checks that converter against
27//    vectors generated by numpy's float16, which is an oracle sharing no code with it.
28//
29// 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED.  `pooled` and the spare key are compared BIT-EXACT
30//    against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact
31//    identity, so the comparison is not weakened by the rope).  That needs the same summation order on both
32//    sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially,
33//    and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one
34//    operation with no intermediate rounding and land one ulp away from the host.
35//
36//    THE `d` IN THOSE NAMES IS NOT COSMETIC.  The first version wrote `__fadd_rn`/`__fmul_rn`, which are
37//    the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated
38//    there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only
39//    float precision (121.82236480712891 on the device against 121.82236342931094 in the reference).
40//    Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a
41//    BIT-EXACT assertion plus a full-precision probe of the intermediate found it.  That is the strongest
42//    argument in this file for keeping both.
43#define DPCT_PROFILING_ENABLED
44#include <sycl/sycl.hpp>
45#include "strata/kprof.hpp"
46#include <dpct/dpct.hpp>
47#include "strata/sycl_queue.hpp"
48#include "strata/core/emulate.hpp"
49#include "strata/kernels/qsa.hpp"
50
51#include "strata/kernels/f16_bits.hpp"
52#include "strata/kernels/kv_stream.hpp"
53#include "strata/kernels/rope.hpp"
54#include "strata/kernels/mrope.hpp"
55
56#include <cfloat>
57#include <cmath>
58#include <cstdio>
59#include <cstdlib>
60#include <cstring>
61
62namespace strata::kernels {
63namespace {
64
65constexpr int THREADS = 128;
66
67void fail(const char* what) {
68    std::fprintf(stderr, "qsa: %s\n", what);
69    std::exit(1);
70}
71
72void check_launch(const char* what) {
73    /*
74    DPCT1010: SYCL uses exceptions to report errors and does not use the
75    error codes. The cudaGetLastError function call was replaced with 0. You
76    need to rewrite this code.
77    */
78    const dpct::err0 e = 0;
79}
80
81/// The SYNCHRONOUS entry points must check their own wait.  Without this the sticky error from a kernel that
82/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel -
83/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one.
84void check_sync(const char *what) try {
85    const dpct::err0 e =
86        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
87}
88catch (sycl::exception const &exc) {
89  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
90            << ", line:" << __LINE__ << std::endl;
91  std::exit(1);
92}
93
94/// Geometry validation.  A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently
95/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused.
96void validate(const QsaShapes& s, const char* who) {
97    if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 ||
98        s.idx_block < 2 || s.page_size < 1) {
99        std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who);
100        std::exit(1);
101    }
102    if (s.n_head % s.n_head_kv != 0) {
103        std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who,
104                     (long long) s.n_head, (long long) s.n_head_kv);
105        std::exit(1);
106    }
107    if (s.head_dim % 4 != 0) {
108        std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who,
109                     (long long) s.head_dim);
110        std::exit(1);
111    }
112    if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) {
113        std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who,
114                     (long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim);
115        std::exit(1);
116    }
117    if (s.idx_n_head > 32) {
118        std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who,
119                     (long long) s.idx_n_head);
120        std::exit(1);
121    }
122}
123
124__dpct_inline__ float h2f(uint16_t bits) { return f32_from_f16(bits); }
125
126// ================= 1. kv_append =================
127
128__dpct_inline__ void
129kv_append_kernel(uint16_t *__restrict__ k_pool, uint16_t *__restrict__ v_pool,
130                 const int32_t *__restrict__ table,
131                 const int32_t *__restrict__ step,
132                 const float *__restrict__ kcur, const float *__restrict__ vcur,
133                 int kv_heads, int head_dim, int page_size, KvHostPools host) {
134    /*
135    DPCT1098: The '*' expression is used instead of the __ldg call. These
136    two expressions do not provide the exact same functionality. Check the
137    generated code for potential precision and/or performance issues.
138    */
139    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
140    const long long pos = (long long)*(step + kStepPos);
141    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
142                  item_ct1.get_local_id(2);
143    if (i >= kv_heads * head_dim) return;
144    const int h = i / head_dim, d = i - h * head_dim;
145    // `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page.
146    // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident.
147    const long long page = (long long) table[pos / page_size];
148    if (page >= 0) {
149        const long long row = (page * kv_heads + h) * page_size + (pos % page_size);
150        k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
151        v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
152    }
153    if (host.k_pool != nullptr) {
154        const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
155        host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
156        host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
157    }
158}
159
160// ================= 2. indexer_key_append =================
161
162/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row.  One thread per indexer
163/// dim, shared `mean` in double.
164///
165/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.**  It used to be
166/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on
167/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's
168/// position forever.  Doing it here reads the position from `pos_dev` like every other kernel, so the grid and
169/// the arguments are the same for every token and the graph replays correctly.
170__dpct_inline__ void indexer_key_append_kernel(
171    const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
172    int pos_base, const float *__restrict__ w_k_norm, float eps,
173    float *__restrict__ tail, float *__restrict__ dead,
174    float *__restrict__ pooled, int32_t *__restrict__ block_pos, int idx_dim,
175    int r, int n_rot, const float *__restrict__ cos_tab,
176    const float *__restrict__ sin_tab, const int32_t *__restrict__ mtab,
177    uint8_t *dpct_local) {
178    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
179    auto s_mean = (double *)dpct_local; // idx_dim doubles
180    const int d = item_ct1.get_local_id(2);
181    /*
182    DPCT1098: The '*' expression is used instead of the __ldg call. These
183    two expressions do not provide the exact same functionality. Check the
184    generated code for potential precision and/or performance issues.
185    */
186    const int pos = (int)*pos_dev;
187    const int slot = pos % r;
188
189    // The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly.
190    // That is what makes `idx_block - 1` rows enough.
191    if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d];
192
193    // The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason
194    // cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block.
195    if (pos == 0) {
196        double p = (double) raw[d];
197        double ss = 0.0;
198        // Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential.
199        // Every thread computes the same `ss` and uses only its own output element.
200        //
201        // `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision
202        // intrinsics, and using them on doubles silently rounds every operation to float.  `ss` then carries
203        // only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare
204        // key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices.  `__ddiv_rn`
205        // and `__dsqrt_rn` pin the reciprocal square root for the same reason.
206        for (int i = 0; i < idx_dim; ++i) {
207            const double v = (double) raw[i];
208            /*
209            DPCT1013: The rounding mode could not be specified and the
210            generated code may have different accuracy than the original code.
211            Verify the correctness. SYCL math built-in function rounding mode is
212            aligned with OpenCL C 1.2 standard.
213            */
214            ss = ss + v * v;
215        }
216        /*
217        DPCT1013: The rounding mode could not be specified and the generated
218        code may have different accuracy than the original code. Verify the
219        correctness. SYCL math built-in function rounding mode is aligned with
220        OpenCL C 1.2 standard.
221        */
222        const double inv = 1.0 / sycl::sqrt(ss / (double)idx_dim + (double)eps);
223        float y = (float) (p * inv * (double) w_k_norm[d]);
224        // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native
225        // indexer's spare does.  At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the
226        // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier).
227        // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the
228        // parity test holds bit-exact.  Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude
229        // correction exactly like every other pooled row and like the native kernel's spare (the unrotated
230        // dims pass through, as in the rotation of the completed blocks below).  Skipping the rotation here,
231        // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache.
232        if (d < n_rot) y *= cos_tab[d % (n_rot / 2)];
233        dead[d] = y;
234        pooled[d] = y;
235    }
236
237    if (slot != r - 1) return;
238    /*
239    DPCT1065: Consider replacing sycl::nd_item::barrier() with
240    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
241    performance if there is no access to global memory.
242    */
243    item_ct1.barrier(); // the tail rows this thread is about to read are
244                        // written above
245
246    // The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming
247    // cell (slot r-1).  The sum of r f32 values is exact in double, so the mean's order cannot matter here -
248    // but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides.
249    double m = 0.0;
250    /*
251DPCT1013: The rounding mode could not be specified and the generated code
252may have different accuracy than the original code. Verify the correctness. SYCL
253math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
254*/
255#pragma unroll
256    for (int j = 0; j < r - 1; ++j)
257        m = m + (double)tail[(size_t)j * idx_dim + d];
258    /*
259    DPCT1013: The rounding mode could not be specified and the generated
260    code may have different accuracy than the original code. Verify the
261    correctness. SYCL math built-in function rounding mode is aligned with
262    OpenCL C 1.2 standard.
263    */
264    m = m + (double)raw[d];
265    m = m / (double) r;
266    s_mean[d] = m;
267    /*
268    DPCT1065: Consider replacing sycl::nd_item::barrier() with
269    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
270    performance if there is no access to global memory.
271    */
272    item_ct1.barrier();
273
274    double ss = 0.0;
275    /*
276DPCT1013: The rounding mode could not be specified and the generated code
277may have different accuracy than the original code. Verify the correctness. SYCL
278math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
279*/
280#pragma unroll
281    for (int i = 0; i < idx_dim; ++i) ss = ss + s_mean[i] * s_mean[i];
282    /*
283    DPCT1013: The rounding mode could not be specified and the generated
284    code may have different accuracy than the original code. Verify the
285    correctness. SYCL math built-in function rounding mode is aligned with
286    OpenCL C 1.2 standard.
287    */
288    const double inv = 1.0 / sycl::sqrt(ss / (double)idx_dim + (double)eps);
289
290    const int b = pos / r;
291    pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]);
292    // The spare slot MOVES to b+1 and is rewritten with the same constant value.
293    pooled[(size_t) (b + 1) * idx_dim + d] = dead[d];
294    // The rotation position for this row, kept because a capture reader and the debug dumps want it.  It is the
295    // block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`.
296    if (d == 0) *block_pos = (int32_t) (pos_base + b * r);
297    /*
298    DPCT1065: Consider replacing sycl::nd_item::barrier() with
299    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
300    performance if there is no access to global memory.
301    */
302    item_ct1.barrier(); // the row is complete only now; the rotation below
303                        // reads TWO elements of it
304
305    // ---- the rotation of the row that just completed, IN PLACE.
306    //
307    // `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the
308    // barrier above, which is why the guard is here and not around the whole block's tail.
309    //
310    // The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps
311    // every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence.
312    const int half = n_rot / 2;
313    if (d < half) {
314        float* row = pooled + (size_t) b * idx_dim;
315        const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half;
316        // THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES.  A second transcription of the pairing is
317        // what this project keeps finding written down wrong.
318        rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]);
319    }
320}
321
322// ================= 3. qsa_index =================
323
324/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps
325/// the row's score onto its cells.  The reference's Relu is PER HEAD, so the dots cannot be summed first.
326__dpct_inline__ void qsa_index_kernel(const float *__restrict__ pooled,
327                                      const float *__restrict__ q_idx,
328                                      const float *__restrict__ bias,
329                                      int idx_n_head, int idx_dim, long long r,
330                                      const int32_t *__restrict__ step,
331                                      float *__restrict__ cell_scores) {
332    /*
333    DPCT1098: The '*' expression is used instead of the __ldg call. These
334    two expressions do not provide the exact same functionality. Check the
335    generated code for potential precision and/or performance issues.
336    */
337    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
338    const long long n_bid = (long long)*(step + kStepNBid);
339    /*
340    DPCT1098: The '*' expression is used instead of the __ldg call. These
341    two expressions do not provide the exact same functionality. Check the
342    generated code for potential precision and/or performance issues.
343    */
344    const long long n_kv = (long long)*(step + kStepNKv);
345    auto &s_dot =
346        *sycl::ext::oneapi::group_local_memory_for_overwrite<double[32]>(
347            sycl::ext::oneapi::this_work_item::get_work_group<3>());
348    const long long b = item_ct1.get_group(2);
349    // A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING.  This is what lets the LAYER launch a CONSTANT
350    // grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value
351    // is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument.
352    // Without this guard, a capacity-sized grid would score pooled rows that have not been written yet -
353    // reading zeros and producing a plausible score for a block that does not exist.
354    if (b > n_bid) return;
355    const int wid = item_ct1.get_local_id(2) >> 5,
356              lane = item_ct1.get_local_id(2) & 31;
357    if (wid == 0) s_dot[lane] = 0.0;     // thread 0 reads all idx_n_head entries; zero the unused ones
358    item_ct1.barrier(sycl::access::fence_space::local_space);
359
360    double acc = 0.0;
361#pragma unroll
362    for (int d = lane; d < idx_dim; d += 32)
363        /*
364        DPCT1013: The rounding mode could not be specified and the generated
365        code may have different accuracy than the original code. Verify the
366        correctness. SYCL math built-in function rounding mode is aligned with
367        OpenCL C 1.2 standard.
368        */
369        acc = acc + (double)pooled[(size_t)b * idx_dim + d] *
370                        (double)q_idx[(size_t)wid * idx_dim + d];
371    /*
372DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
373masked sub_group function which may not be supported by all compilers or
374runtimes. You may need to adjust the code.
375*/
376    /*
377DPCT1013: The rounding mode could not be specified and the generated code
378may have different accuracy than the original code. Verify the correctness. SYCL
379math built-in function rounding mode is aligned with OpenCL C 1.2 standard.
380*/
381#pragma unroll
382    for (int o = 16; o > 0; o >>= 1) acc =
383        acc + dpct::experimental::permute_sub_group_by_xor(
384                  0xffffffffu,
385                  sycl::ext::oneapi::this_work_item::get_sub_group(), acc, o);
386    if (lane == 0) s_dot[wid] = acc;
387    item_ct1.barrier(sycl::access::fence_space::local_space);
388
389    if (item_ct1.get_local_id(2) != 0) return;
390    double score = 0.0;
391#pragma unroll
392    for (int h = 0; h < idx_n_head; ++h) score +=
393        (s_dot[h] > 0.0) ? s_dot[h] : 0.0;
394    if (bias != nullptr) score += (double) bias[b];
395    // cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid
396    long long lo = b * r, hi = lo + r;
397    if (b == n_bid) hi = n_kv;
398    if (hi > n_kv) hi = n_kv;
399    // llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells
400    // a finite +1e9 bias before top-k.  Read the current step on every replay:
401    // the spare row becomes an ordinary block as soon as its fourth cell arrives.
402    float sc = (float) score;
403    if (b == n_bid && n_kv % r != 0) sc += 1e9f;
404#pragma unroll
405    for (long long j = lo; j < hi; ++j) cell_scores[j] = sc;
406}
407
408// ================= 4. topk_512 =================
409
410/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float
411/// semantics.  `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by
412/// index), while the raw bit pattern orders them.  A NaN is mapped to 0, below every real key, i.e. never
413/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement.
414__dpct_inline__ uint32_t order_key(float s) {
415    const float v = s + 0.0f;
416    if (!(v == v)) return 0u;
417    uint32_t b;
418    memcpy(&b, &v, 4);
419    return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
420}
421
422constexpr int TOPK_THREADS = 256;
423
424/*
425DPCT1110: The total declared local variable size in device function
426topk_kernel exceeds 128 bytes and may cause high register pressure. Consult with
427your hardware vendor to find the total register size available and adjust the
428code, or use smaller sub-group size to avoid high register pressure.
429*/
430__dpct_inline__ void topk_kernel(const float *__restrict__ scores,
431                                 const int32_t *__restrict__ step,
432                                 int *__restrict__ out_ids) {
433    /*
434    DPCT1098: The '*' expression is used instead of the __ldg call. These
435    two expressions do not provide the exact same functionality. Check the
436    generated code for potential precision and/or performance issues.
437    */
438    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
439    const long long n_kv = (long long)*(step + kStepNKv);
440    /*
441    DPCT1098: The '*' expression is used instead of the __ldg call. These
442    two expressions do not provide the exact same functionality. Check the
443    generated code for potential precision and/or performance issues.
444    */
445    const long long width = (long long)*(step + kStepWidth);
446    auto &s_a =
447        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_THREADS]>(
448            sycl::ext::oneapi::this_work_item::get_work_group<3>());
449    auto &s_b =
450        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[TOPK_THREADS]>(
451            sycl::ext::oneapi::this_work_item::get_work_group<3>());
452    auto &s_cgt =
453        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long>(
454            sycl::ext::oneapi::this_work_item::get_work_group<3>());
455    const int t = item_ct1.get_local_id(2);
456    const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS;
457    const long long lo = (long long) t * chunk;
458    long long hi = lo + chunk;
459    if (hi > n_kv) hi = n_kv;
460
461    // ---- binary lifting: the largest key v with count(key >= v) >= width.  Monotone in v, so setting the
462    // bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1).
463    uint32_t v = 0u;
464    for (int bit = 31; bit >= 0; --bit) {
465        const uint32_t cand = v | (1u << bit);
466        int c = 0;
467#pragma unroll
468        for (long long j = lo; j < hi;
469             ++j) if (order_key(scores[j]) >= cand)++ c;
470        s_a[t] = c;
471        /*
472        DPCT1118: SYCL group functions and algorithms must be encountered in
473        converged control flow. You may need to adjust the code.
474        */
475        item_ct1.barrier(sycl::access::fence_space::local_space);
476#pragma unroll
477        for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) {
478            if (t < s) s_a[t] += s_a[t + s];
479            /*
480            DPCT1118: SYCL group functions and algorithms must be
481            encountered in converged control flow. You may need to adjust the
482            code.
483            */
484            item_ct1.barrier(sycl::access::fence_space::local_space);
485        }
486        const int tot = s_a[0];
487        /*
488        DPCT1118: SYCL group functions and algorithms must be encountered in
489        converged control flow. You may need to adjust the code.
490        */
491        item_ct1.barrier(
492            sycl::access::fence_space::local_space); // before the next round
493                                                     // overwrites s_a
494        if (tot >= (int) width) v = cand;
495    }
496    const uint32_t thr = v;
497
498    // ---- counts and their exclusive prefixes.  The prefixes are computed by thread 0 in one walk, which is
499    // 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already
500    // 32 passes deep.
501    int gt = 0, eq = 0;
502    for (long long j = lo; j < hi; ++j) {
503        const uint32_t k = order_key(scores[j]);
504        if (k > thr) ++gt;
505        else if (k == thr) ++eq;
506    }
507    s_a[t] = gt;
508    s_b[t] = eq;
509    item_ct1.barrier(sycl::access::fence_space::local_space);
510    if (t == 0) {
511        long long ag = 0, ae = 0;
512        for (int i = 0; i < TOPK_THREADS; ++i) {
513            const int g = s_a[i], e = s_b[i];
514            s_a[i] = (int) ag;
515            s_b[i] = (int) ae;
516            ag += g;
517            ae += e;
518        }
519        s_cgt = ag;    // how many are strictly above the threshold, i.e. where the equals start
520    }
521    item_ct1.barrier(sycl::access::fence_space::local_space);
522    // THE RANK VS THE COUNT.  `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is
523    // compared against `eq_budget`, the number of them the selection has room for.  The first version wrote
524    // `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and
525    // compared THAT against the budget.  With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing
526    // was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale.
527    // Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide.
528    const long long off_eq = s_b[t];
529    const long long eq_budget = width - s_cgt;
530
531    // ---- how many this chunk selects, so the ascending walk can be scattered into place
532    int sel = 0;
533    {
534        long long e = off_eq;
535        for (long long j = lo; j < hi; ++j) {
536            const uint32_t k = order_key(scores[j]);
537            if (k > thr) ++sel;
538            else if (k == thr && e < eq_budget) { ++sel; ++e; }
539        }
540    }
541    s_a[t] = sel;
542    item_ct1.barrier(sycl::access::fence_space::local_space);
543    if (t == 0) {
544        long long a = 0;
545        for (int i = 0; i < TOPK_THREADS; ++i) {
546            const int c = s_a[i];
547            s_a[i] = (int) a;
548            a += c;
549        }
550    }
551    item_ct1.barrier(sycl::access::fence_space::local_space);
552
553    // ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself
554    long long w = s_a[t];
555    long long e = off_eq;
556    for (long long j = lo; j < hi; ++j) {
557        const uint32_t k = order_key(scores[j]);
558        if (k > thr) out_ids[w++] = (int) j;
559        else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; }
560    }
561}
562
563// ================= 5. kv_gather =================
564
565__dpct_inline__ void kv_gather_kernel(
566    const uint16_t *__restrict__ k_pool, const uint16_t *__restrict__ v_pool,
567    const int32_t *__restrict__ table, const int32_t *__restrict__ ids,
568    const int32_t *__restrict__ step, int kv_heads, int head_dim, int page_size,
569    uint16_t *__restrict__ k_scratch, uint16_t *__restrict__ v_scratch) {
570    /*
571    DPCT1098: The '*' expression is used instead of the __ldg call. These
572    two expressions do not provide the exact same functionality. Check the
573    generated code for potential precision and/or performance issues.
574    */
575    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
576    const long long n_ids = (long long)*(step + kStepWidth);
577    const int per = head_dim / 4;                       // 4 halfs per uint2
578    const long long total = n_ids * kv_heads * per;
579    const long long i =
580        item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
581        item_ct1.get_local_id(2);
582    if (i >= total) return;
583    const long long id = i / (kv_heads * (long long) per);
584    const int rem = (int) (i % (kv_heads * (long long) per));
585    const int h = rem / per, q = rem - h * per;
586    const int cell = ids[id];
587    const long long page = (long long) table[cell / page_size];
588    const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q;
589    const long long dst = (id * kv_heads + h) * (long long) per + q;
590    reinterpret_cast<sycl::uint2 *>(k_scratch)[dst] =
591        reinterpret_cast<const sycl::uint2 *>(k_pool)[src];
592    reinterpret_cast<sycl::uint2 *>(v_scratch)[dst] =
593        reinterpret_cast<const sycl::uint2 *>(v_pool)[src];
594}
595
596// ================= 6. qsa_attend =================
597
598__dpct_inline__ float warp_max(float v) {
599    /*
600DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
601masked sub_group function which may not be supported by all compilers or
602runtimes. You may need to adjust the code.
603*/
604#pragma unroll
605    for (int o = 16; o > 0; o >>= 1) v = sycl::fmax(
606        v, dpct::experimental::permute_sub_group_by_xor(
607               0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
608               v, o));
609    return v;
610}
611
612__dpct_inline__ float warp_sum(float v) {
613    /*
614DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
615masked sub_group function which may not be supported by all compilers or
616runtimes. You may need to adjust the code.
617*/
618#pragma unroll
619    for (int o = 16; o > 0; o >>= 1) v +=
620        dpct::experimental::permute_sub_group_by_xor(
621            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
622            o);
623    return v;
624}
625
626/// One block per query head.  `s` holds the scores, which are then overwritten with the softmax weights.
627/*
628DPCT1110: The total declared local variable size in device function
629qsa_attend_kernel exceeds 128 bytes and may cause high register pressure.
630Consult with your hardware vendor to find the total register size available and
631adjust the code, or use smaller sub-group size to avoid high register pressure.
632*/
633__dpct_inline__ void qsa_attend_kernel(
634    const float *__restrict__ q, const uint16_t *__restrict__ k_scratch,
635    const uint16_t *__restrict__ v_scratch, const int32_t *__restrict__ step,
636    int n_head, int n_head_kv, int head_dim, float *__restrict__ attn,
637    float *__restrict__ weights, uint8_t *dpct_local) {
638    /*
639    DPCT1098: The '*' expression is used instead of the __ldg call. These
640    two expressions do not provide the exact same functionality. Check the
641    generated code for potential precision and/or performance issues.
642    */
643    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
644    const long long n_ids = (long long)*(step + kStepWidth);
645    auto s_w = (float *)dpct_local; // CAPACITY floats (scores, then weights) +
646                                    // 32 for the reductions
647    float* red = s_w;                    // red[0..31] live past the scores/weights: see the launch
648    float* w = s_w + 32;
649    const int h = item_ct1.get_group(2);
650    const int d = item_ct1.get_local_id(2);
651    // AN EMPTY SELECTION IS HANDLED HERE, not by a host early return.  The wrapper used to check `n_ids == 0`
652    // and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the
653    // device, and this is also the only form a graph can replay: the launch is unconditional and the kernel
654    // decides.  Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is
655    // reachable only for a genuinely empty cache, and the reference returns zeros for that.
656    if (n_ids == 0) {
657#pragma unroll
658        for (int i = d; i < head_dim; i += item_ct1.get_local_range(2))
659            attn[(size_t)h * head_dim + i] = 0.0f;
660        return;
661    }
662    const int kv = h / (n_head / n_head_kv);       // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv
663    const float scale = 1.0f / sycl::sqrt((float)head_dim);
664    const int lane = d & 31, wid = d >> 5,
665              nwarp = (int)((item_ct1.get_local_range(2) + 31) >> 5);
666
667    for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2)) {
668        const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim;
669        float acc = 0.0f;
670#pragma unroll
671        for (int i = 0; i < head_dim; ++i) acc +=
672            h2f(krow[i]) * q[(size_t)h * head_dim + i];
673        w[j] = acc * scale;
674    }
675    /*
676    DPCT1065: Consider replacing sycl::nd_item::barrier() with
677    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
678    performance if there is no access to global memory.
679    */
680    item_ct1.barrier();
681
682    float mx = -FLT_MAX;    // not -inf, whose double -> float conversion nvcc warns about
683#pragma unroll
684    for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2))
685        mx = sycl::fmax(mx, w[j]);
686    mx = warp_max(mx);
687    if (lane == 0) red[wid] = mx;
688    /*
689    DPCT1065: Consider replacing sycl::nd_item::barrier() with
690    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
691    performance if there is no access to global memory.
692    */
693    item_ct1.barrier();
694    if (wid == 0) {
695        mx = (lane < nwarp) ? red[lane] : -FLT_MAX;
696        mx = warp_max(mx);
697        if (lane == 0) red[0] = mx;
698    }
699    /*
700    DPCT1065: Consider replacing sycl::nd_item::barrier() with
701    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
702    performance if there is no access to global memory.
703    */
704    item_ct1.barrier();
705    mx = red[0];
706    /*
707    DPCT1065: Consider replacing sycl::nd_item::barrier() with
708    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
709    performance if there is no access to global memory.
710    */
711    item_ct1.barrier();
712
713    float sum = 0.0f;
714    for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2)) {
715        const float e = sycl::native::exp(w[j] - mx);
716        w[j] = e;
717        sum += e;
718    }
719    sum = warp_sum(sum);
720    if (lane == 0) red[wid] = sum;
721    /*
722    DPCT1065: Consider replacing sycl::nd_item::barrier() with
723    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
724    performance if there is no access to global memory.
725    */
726    item_ct1.barrier();
727    if (wid == 0) {
728        sum = (lane < nwarp) ? red[lane] : 0.0f;
729        sum = warp_sum(sum);
730        if (lane == 0) red[0] = 1.0f / sum;
731    }
732    /*
733    DPCT1065: Consider replacing sycl::nd_item::barrier() with
734    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
735    performance if there is no access to global memory.
736    */
737    item_ct1.barrier();
738    const float inv = red[0];
739    /*
740    DPCT1065: Consider replacing sycl::nd_item::barrier() with
741    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
742    performance if there is no access to global memory.
743    */
744    item_ct1.barrier();
745
746    float acc = 0.0f;
747#pragma unroll
748    for (long long j = 0; j < n_ids; ++j)
749        acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]);
750    attn[(size_t) h * head_dim + d] = acc;
751    if (weights != nullptr) {
752#pragma unroll
753        for (long long j = d; j < n_ids; j += item_ct1.get_local_range(2))
754            weights[(size_t)h * n_ids + j] = w[j] * inv;
755    }
756}
757
758// ================= 7. qsa_gate_apply =================
759
760__dpct_inline__ void qsa_gate_apply_kernel(const float *__restrict__ attn,
761                                           const float *__restrict__ q_full,
762                                           int n_head, int head_dim,
763                                           uint16_t *__restrict__ out) {
764    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
765    const long long i =
766        item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
767        item_ct1.get_local_id(2);
768    if (i >= (long long) n_head * head_dim) return;
769    const int h = (int) (i / head_dim), d = (int) (i % head_dim);
770    const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d];   // the SECOND half
771    const double sig = 1.0 / (1.0 + sycl::exp(-g));
772    out[i] = f16_from_f32((float) ((double) attn[i] * sig));
773}
774
775inline unsigned grid_for(long long n, int threads) {
776    return (unsigned) ((n + threads - 1) / threads);
777}
778
779}  // namespace
780
781/// THE STEP STATE, UPLOADED.  Every kernel below reads its per-token counts from here rather than from a kernel
782/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`.  This
783/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels
784/// already read the device values; the layer will pass its own buffer once it captures.
785///
786/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same
787/// stream and the host is the only writer.  `cudaMemcpyAsync` on the null stream is ordered against the null
788/// stream's kernels, which is what every direct-launch caller here uses.
789namespace {
790
791int32_t *step_scratch() try {
792    static int32_t* d_step = nullptr;
793    if (d_step == nullptr) {
794        if (DPCT_CHECK_ERROR(
795                d_step = (int32_t *)sycl::malloc_device(
796                    qsa_step_bytes(), dpct::get_in_order_queue())) != 0) {
797            std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n");
798            std::exit(1);
799        }
800    }
801    return d_step;
802}
803catch (sycl::exception const &exc) {
804  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
805            << ", line:" << __LINE__ << std::endl;
806  std::exit(1);
807}
808
809void step_upload_raw(const int32_t *h_step) try {
810    int32_t* d = step_scratch();
811    /*
812    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
813    the original code the source host memory is pageable memory. If the memory
814    is not pageable, call wait() on event return by memcpy API to ensure
815    synchronization behavior.
816    */
817    if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
818            d, h_step, qsa_step_bytes()).wait()) != 0) {
819        std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n");
820        std::exit(1);
821    }
822}
823catch (sycl::exception const &exc) {
824  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
825            << ", line:" << __LINE__ << std::endl;
826  std::exit(1);
827}
828
829/// From a POSITION: fills all four entries.  This is the form the layer will use, and the only form that cannot
830/// produce an inconsistent `n_kv`/`n_bid`/`width`.
831const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) {
832    int32_t h[kStepCount];
833    qsa_step_fill(h, pos, s);
834    // A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the
835    // inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent
836    // preference for one of the two.
837    if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) {
838        std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint,
839                     h[kStepNKv]);
840        std::exit(1);
841    }
842    step_upload_raw(h);
843    return step_scratch();
844}
845
846/// From a WIDTH.  `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so
847/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale,
848/// because a stale entry is a value the NEXT kernel might read.
849const int32_t* step_upload_width(int64_t width, const QsaShapes& s) {
850    int32_t h[kStepCount];
851    for (int i = 0; i < kStepCount; ++i) h[i] = 0;
852    h[kStepWidth] = (int32_t) width;
853    (void) s;
854    step_upload_raw(h);
855    return step_scratch();
856}
857
858}  // namespace
859
860// ================= THE CAPTURABLE ENTRY POINTS =================
861//
862// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token
863// count comes from `step`.  The host-scalar entry points further down are wrappers that fill a module-level step
864// buffer and forward this token's counts as the capacities.
865
866void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step,
867                    const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) {
868    validate(s, "kv_append");
869    if (step == nullptr) fail("kv_append: step is null");
870    // The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell.
871    const long long n = s.n_head_kv * s.head_dim;
872    {
873        auto exp_props = sycl::ext::oneapi::experimental::properties{
874            sycl::ext::oneapi::experimental::use_root_sync};
875
876        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
877            ->submit([&](sycl::handler &cgh) {
878                KvHostPools host_host_KvHostPools_ct9 =
879                    host ? *host : KvHostPools{};
880
881                cgh.parallel_for<
882                    dpct_kernel_name<class kv_append_kernel_19f129>>(
883                    sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, THREADS)) *
884                                          sycl::range(1, 1, THREADS),
885                                      sycl::range(1, 1, THREADS)),
886                    exp_props, [=](sycl::nd_item<3> item_ct1) {
887                        kv_append_kernel(k_pool, v_pool, page_table, step, kcur,
888                                         vcur, (int)s.n_head_kv,
889                                         (int)s.head_dim, (int)s.page_size,
890                                         host_host_KvHostPools_ct9);
891                    });
892            });
893    }
894    check_launch("kv_append");
895    if (stream == nullptr) check_sync("kv_append");
896}
897
898void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s,
899                    const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) {
900    validate(s, "qsa_index");
901    if (step == nullptr) fail("qsa_index: step is null");
902    if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive");
903    // THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`.  The kernel returns for
904    // `b > n_bid`, so the surplus blocks cost a launch and nothing else.
905    const int threads = 32 * (int) s.idx_n_head;
906    /*
907    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
908    limit. To get the device limit, query info::device::max_work_group_size.
909    Adjust the work-group size if needed.
910    */
911    {
912        auto exp_props = sycl::ext::oneapi::experimental::properties{
913            sycl::ext::oneapi::experimental::use_root_sync};
914        dpct::has_capability_or_fail(
915            strata::q_of(stream)->get_device(),
916            {sycl::aspect::fp64});
917
918        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
919            ->template parallel_for<dpct_kernel_name<class qsa_index_kernel_bb65cd>>(
920                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)max_blocks) *
921                                      sycl::range(1, 1, threads),
922                                  sycl::range(1, 1, threads)),
923                exp_props,
924                [=](sycl::nd_item<3> item_ct1)
925                    [[sycl::reqd_sub_group_size(32)]] {
926                        qsa_index_kernel(pooled, q_idx, bias, (int)s.idx_n_head,
927                                         (int)s.idx_dim, s.idx_block, step,
928                                         cell_scores);
929                    });
930    }
931    check_launch("qsa_index");
932    if (stream == nullptr) check_sync("qsa_index");
933}
934
935void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step,
936                   int32_t* ids, void* stream) {
937    validate(s, "topk_512");
938    if (step == nullptr) fail("topk_512: step is null");
939    // `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this
940    // token's is a device value.  The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and
941    // `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write.
942    const int64_t width_max = qsa_selection_width(kTopkMaxCells, s);
943    if (cap < width_max) {
944        std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n",
945                     (long long) cap, (long long) width_max);
946        std::exit(1);
947    }
948    // One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`.
949    {
950        auto exp_props = sycl::ext::oneapi::experimental::properties{
951            sycl::ext::oneapi::experimental::use_root_sync};
952
953        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
954            ->template parallel_for<dpct_kernel_name<class topk_kernel_97d5c9>>(
955                sycl::nd_range<3>(sycl::range(1, 1, TOPK_THREADS),
956                                  sycl::range(1, 1, TOPK_THREADS)),
957                exp_props, [=](sycl::nd_item<3> item_ct1) {
958                    topk_kernel(cell_scores, step, ids);
959                });
960    }
961    check_launch("topk_512");
962    if (stream == nullptr) check_sync("topk_512");
963}
964
965void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table,
966                    const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s,
967                    uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
968    validate(s, "kv_gather");
969    if (step == nullptr) fail("kv_gather: step is null");
970    if (max_ids <= 0) return;
971    // THE GRID IS THE CAPACITY.  The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;`
972    // guard leaves the surplus threads idle.
973    const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
974    {
975        auto exp_props = sycl::ext::oneapi::experimental::properties{
976            sycl::ext::oneapi::experimental::use_root_sync};
977
978        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
979            ->template parallel_for<dpct_kernel_name<class kv_gather_kernel_3473e7>>(
980                sycl::nd_range<3>(sycl::range(1, 1, grid_for(total, 256)) *
981                                      sycl::range(1, 1, 256),
982                                  sycl::range(1, 1, 256)),
983                exp_props, [=](sycl::nd_item<3> item_ct1) {
984                    kv_gather_kernel(k_pool, v_pool, page_table, ids, step,
985                                     (int)s.n_head_kv, (int)s.head_dim,
986                                     (int)s.page_size, k_scratch, v_scratch);
987                });
988    }
989    check_launch("kv_gather");
990    if (stream == nullptr) check_sync("kv_gather");
991}
992
993void qsa_attend_step(const float *q, const uint16_t *k_scratch,
994                     const uint16_t *v_scratch, const int32_t *step,
995                     int64_t max_ids, const QsaShapes &s, float *attn,
996                     float *weights, void *stream) try {
997    validate(s, "qsa_attend");
998    if (step == nullptr) fail("qsa_attend: step is null");
999    if (max_ids <= 0) fail("qsa_attend: max_ids must be positive");
1000    // THE SHARED SIZE IS THE CAPACITY.  Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from
1001    // this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and
1002    // then index past it at token 500.  The kernel reads the real count from `step`, so a larger allocation is
1003    // exactly what it wants.  The opt-in therefore happens once, for the capacity.
1004    /*
1005    DPCT1083: The size of local memory in the migrated code may be different
1006    from the original code. Check that the allocated memory size in the migrated
1007    code is correct.
1008    */
1009    const size_t smem = (size_t)(max_ids + 32) * sizeof(float);
1010    // per DEVICE: the opt-in is a device setting (a layer split runs this on two cards)
1011    static size_t s_configured_dev[64] = {};
1012    int cur_dev = 0;
1013    cur_dev = dpct::get_current_device_id();
1014    size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0];
1015    if (smem > s_configured) {
1016        int dev = 0, max_shared = 0;
1017        dev = dpct::get_current_device_id();
1018        /*
1019        DPCT1019: local_mem_size in SYCL is not a complete equivalent of
1020        cudaDevAttrMaxSharedMemoryPerBlockOptin in CUDA. You may need to adjust
1021        the code.
1022        */
1023        max_shared = dpct::get_device(dev).get_local_mem_size();
1024        max_shared = strata::smem_optin_of(max_shared);
1025        if ((int) smem > max_shared) {
1026            std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n",
1027                         (long long) max_ids, smem, max_shared);
1028            std::exit(1);
1029        }
1030        const dpct::err0 e =
1031            /*
1032            DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
1033            because SYCL currently does not support corresponding setting.
1034            */
1035            0;
1036
1037        s_configured = smem;
1038    }
1039    /*
1040    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1041    limit. To get the device limit, query info::device::max_work_group_size.
1042    Adjust the work-group size if needed.
1043    */
1044    {
1045        auto exp_props = sycl::ext::oneapi::experimental::properties{
1046            sycl::ext::oneapi::experimental::use_root_sync};
1047
1048        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1049            ->submit([&](sycl::handler &cgh) {
1050                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1051                    sycl::range(smem), cgh);
1052
1053                cgh.parallel_for<
1054                    dpct_kernel_name<class qsa_attend_kernel_6a355d>>(
1055                    sycl::nd_range<3>(
1056                        sycl::range(1, 1, (unsigned)s.n_head) *
1057                            sycl::range(1, 1, (unsigned)s.head_dim),
1058                        sycl::range(1, 1, (unsigned)s.head_dim)),
1059                    exp_props,
1060                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
1061                        32)]] {
1062                        qsa_attend_kernel(
1063                            q, k_scratch, v_scratch, step, (int)s.n_head,
1064                            (int)s.n_head_kv, (int)s.head_dim, attn, weights,
1065                            dpct_local_acc_ct1
1066                                .get_multi_ptr<sycl::access::decorated::no>()
1067                                .get());
1068                    });
1069            });
1070    }
1071    check_launch("qsa_attend");
1072    if (stream == nullptr) check_sync("qsa_attend");
1073}
1074catch (sycl::exception const &exc) {
1075  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1076            << ", line:" << __LINE__ << std::endl;
1077  std::exit(1);
1078}
1079
1080// ================= host entry points =================
1081
1082void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) {
1083    if (host_step == nullptr) return;
1084    if (pos < 0) fail("qsa_step_fill: pos < 0");
1085    // ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four
1086    // separate parameters.  `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in
1087    // itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency
1088    // now has a single writer to check against instead of two independent arguments.
1089    //
1090    // This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one
1091    // H2D per token updates all of them and no entry point takes a per-token scalar.
1092    const int64_t n_kv = pos + 1;
1093    host_step[kStepPos] = (int32_t) pos;
1094    host_step[kStepNKv] = (int32_t) n_kv;
1095    host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block);
1096    host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s);
1097}
1098
1099void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos,
1100               const float* kcur, const float* vcur, const QsaShapes& s, void* stream) {
1101    if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); }
1102    kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream);
1103}
1104
1105void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm,
1106                        float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab,
1107                        const float* sin_tab, void* stream) {
1108    validate(s, "indexer_key_append");
1109    if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null");
1110    if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr)
1111        fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)");
1112    const int threads = (int) s.idx_dim;
1113    /*
1114    DPCT1083: The size of local memory in the migrated code may be different
1115    from the original code. Check that the allocated memory size in the migrated
1116    code is correct.
1117    */
1118    const size_t smem = (size_t)s.idx_dim * sizeof(double);
1119    // **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.**  The completion rotation is inside the kernel now.  The
1120    // arguments here are identical for every token, which is the property a CUDA graph needs: this function can
1121    // be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data.
1122    /*
1123    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1124    limit. To get the device limit, query info::device::max_work_group_size.
1125    Adjust the work-group size if needed.
1126    */
1127    {
1128        auto exp_props = sycl::ext::oneapi::experimental::properties{
1129            sycl::ext::oneapi::experimental::use_root_sync};
1130        dpct::has_capability_or_fail(
1131            strata::q_of(stream)->get_device(),
1132            {sycl::aspect::fp64});
1133
1134        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1135            ->submit([&](sycl::handler &cgh) {
1136                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1137                    sycl::range(smem), cgh);
1138
1139                auto mrope_table_ct14 = mrope_table();
1140
1141                cgh.parallel_for<
1142                    dpct_kernel_name<class indexer_key_append_kernel_9e74e0>>(
1143                    sycl::nd_range<3>(sycl::range(1, 1, threads),
1144                                      sycl::range(1, 1, threads)),
1145                    exp_props, [=](sycl::nd_item<3> item_ct1) {
1146                        indexer_key_append_kernel(
1147                            raw, pos_dev, (int)pos_base, w_k_norm, eps, b.tail,
1148                            b.dead, b.pooled, b.block_pos, (int)s.idx_dim,
1149                            (int)s.idx_block, (int)s.n_rot, cos_tab, sin_tab,
1150                            mrope_table_ct14,
1151                            dpct_local_acc_ct1
1152                                .get_multi_ptr<sycl::access::decorated::no>()
1153                                .get());
1154                    });
1155            });
1156    }
1157    check_launch("indexer_key_append");
1158    if (stream == nullptr) check_sync("indexer_key_append");
1159}
1160
1161void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s,
1162               int64_t n_kv, float* cell_scores, void* stream) {
1163    validate(s, "qsa_index");
1164    if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0");
1165    // `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments
1166    // disagree rather than launching a kernel that would score the wrong number of blocks.
1167    if ((n_kv / s.idx_block) != n_bid) {
1168        std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid,
1169                     (long long) n_kv, (long long) s.idx_block);
1170        std::exit(1);
1171    }
1172    // THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph.  The layer passes a
1173    // constant `max_blocks` from its state instead - see the note in `qsa.hpp`.
1174    qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream);
1175}
1176
1177void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids,
1178              void* stream) {
1179    validate(s, "topk_512");
1180    if (n_kv <= 0) return;
1181    if (n_kv > kTopkMaxCells) {
1182        std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n",
1183                     (long long) n_kv, (long long) kTopkMaxCells);
1184        std::exit(1);
1185    }
1186    topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream);
1187}
1188
1189void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids,
1190               int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
1191    validate(s, "kv_gather");
1192    if (n_ids <= 0) return;
1193    kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch,
1194                   v_scratch, stream);
1195}
1196
1197void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids,
1198                const QsaShapes& s, float* attn, float* weights, void* stream) {
1199    validate(s, "qsa_attend");
1200    if (n_ids < 0) fail("qsa_attend: n_ids < 0");
1201    if (n_ids == 0) {
1202        // The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the
1203        // wrapper gives it the geometry's capacity rather than 0.
1204        qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s),
1205                        qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream);
1206        return;
1207    }
1208    qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream);
1209}
1210
1211/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller
1212/// whose weight is a K-quant needs the f32 form.  Identical arithmetic up to the last step.
1213__dpct_inline__ void qsa_gate_apply_f32_kernel(const float *__restrict__ attn,
1214                                               const float *__restrict__ q_full,
1215                                               int n_head, int head_dim,
1216                                               float *__restrict__ out) {
1217    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1218    const long long i =
1219        item_ct1.get_group(2) * (long long)item_ct1.get_local_range(2) +
1220        item_ct1.get_local_id(2);
1221    if (i >= (long long) n_head * head_dim) return;
1222    const int h = (int) (i / head_dim), d = (int) (i % head_dim);
1223    const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d];   // the SECOND half
1224    const double sig = 1.0 / (1.0 + sycl::exp(-g));
1225    out[i] = (float) ((double) attn[i] * sig);
1226}
1227
1228void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) {
1229    validate(s, "qsa_gate_apply_f32");
1230    const long long n = s.n_head * s.head_dim;
1231    {
1232        auto exp_props = sycl::ext::oneapi::experimental::properties{
1233            sycl::ext::oneapi::experimental::use_root_sync};
1234        dpct::has_capability_or_fail(
1235            strata::q_of(stream)->get_device(),
1236            {sycl::aspect::fp64});
1237
1238        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1239            ->template parallel_for<
1240                dpct_kernel_name<class qsa_gate_apply_f32_kernel_7cff4f>>(
1241                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, 256)) *
1242                                      sycl::range(1, 1, 256),
1243                                  sycl::range(1, 1, 256)),
1244                exp_props, [=](sycl::nd_item<3> item_ct1) {
1245                    qsa_gate_apply_f32_kernel(attn, q_full, (int)s.n_head,
1246                                              (int)s.head_dim, out);
1247                });
1248    }
1249    check_launch("qsa_gate_apply_f32");
1250    if (stream == nullptr) check_sync("qsa_gate_apply_f32");
1251}
1252
1253void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) {
1254    validate(s, "qsa_gate_apply");
1255    const long long n = s.n_head * s.head_dim;
1256    {
1257        auto exp_props = sycl::ext::oneapi::experimental::properties{
1258            sycl::ext::oneapi::experimental::use_root_sync};
1259        dpct::has_capability_or_fail(
1260            strata::q_of(stream)->get_device(),
1261            {sycl::aspect::fp64});
1262
1263        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1264            ->template parallel_for<
1265                dpct_kernel_name<class qsa_gate_apply_kernel_650dec>>(
1266                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n, 256)) *
1267                                      sycl::range(1, 1, 256),
1268                                  sycl::range(1, 1, 256)),
1269                exp_props, [=](sycl::nd_item<3> item_ct1) {
1270                    qsa_gate_apply_kernel(attn, q_full, (int)s.n_head,
1271                                          (int)s.head_dim, out);
1272                });
1273    }
1274    check_launch("qsa_gate_apply");
1275    if (stream == nullptr) check_sync("qsa_gate_apply");
1276}
1277
1278}  // namespace strata::kernels