okami.mom/strata

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

Niko1221Merge branch 'f-132-pr' into rel-0.1.32b0abdeb44

main
43.1 KiB821 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#include "strata/core/emulate.hpp"
44#include "strata/kernels/qsa.hpp"
45
46#include "strata/kernels/f16_bits.hpp"
47#include "strata/kernels/kv_stream.hpp"
48#include "strata/kernels/rope.hpp"
49#include "strata/kernels/mrope.hpp"
50
51#include <cuda_runtime.h>
52
53#include <cfloat>
54#include <cmath>
55#include <cstdio>
56#include <cstdlib>
57#include <cstring>
58
59namespace strata::kernels {
60namespace {
61
62constexpr int THREADS = 128;
63
64void fail(const char* what) {
65    std::fprintf(stderr, "qsa: %s\n", what);
66    std::exit(1);
67}
68
69void check_launch(const char* what) {
70    const cudaError_t e = cudaGetLastError();
71    if (e != cudaSuccess) {
72        std::fprintf(stderr, "qsa: %s launch: %s\n", what, cudaGetErrorString(e));
73        std::exit(1);
74    }
75}
76
77/// The SYNCHRONOUS entry points must check their own wait.  Without this the sticky error from a kernel that
78/// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel -
79/// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one.
80void check_sync(const char* what) {
81    const cudaError_t e = cudaDeviceSynchronize();
82    if (e != cudaSuccess) {
83        std::fprintf(stderr, "qsa: %s (synchronise): %s\n", what, cudaGetErrorString(e));
84        std::exit(1);
85    }
86}
87
88/// Geometry validation.  A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently
89/// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused.
90void validate(const QsaShapes& s, const char* who) {
91    if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 ||
92        s.idx_block < 2 || s.page_size < 1) {
93        std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who);
94        std::exit(1);
95    }
96    if (s.n_head % s.n_head_kv != 0) {
97        std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who,
98                     (long long) s.n_head, (long long) s.n_head_kv);
99        std::exit(1);
100    }
101    if (s.head_dim % 4 != 0) {
102        std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who,
103                     (long long) s.head_dim);
104        std::exit(1);
105    }
106    if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) {
107        std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who,
108                     (long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim);
109        std::exit(1);
110    }
111    if (s.idx_n_head > 32) {
112        std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who,
113                     (long long) s.idx_n_head);
114        std::exit(1);
115    }
116}
117
118__device__ __forceinline__ float h2f(uint16_t bits) { return f32_from_f16(bits); }
119
120// ================= 1. kv_append =================
121
122__global__ void kv_append_kernel(uint16_t* __restrict__ k_pool, uint16_t* __restrict__ v_pool,
123                                 const int32_t* __restrict__ table, const int32_t* __restrict__ step,
124                                 const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads,
125                                 int head_dim, int page_size, KvHostPools host) {
126    const long long pos = (long long) __ldg(step + kStepPos);
127    const int i = blockIdx.x * blockDim.x + threadIdx.x;
128    if (i >= kv_heads * head_dim) return;
129    const int h = i / head_dim, d = i - h * head_dim;
130    // `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page.
131    // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident.
132    const long long page = (long long) table[pos / page_size];
133    if (page >= 0) {
134        const long long row = (page * kv_heads + h) * page_size + (pos % page_size);
135        k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
136        v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
137    }
138    if (host.k_pool != nullptr) {
139        const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size);
140        host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]);
141        host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]);
142    }
143}
144
145// ================= 2. indexer_key_append =================
146
147/// Appends the raw key, and on a block completion pools AND ROTATES the pooled row.  One thread per indexer
148/// dim, shared `mean` in double.
149///
150/// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.**  It used to be
151/// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on
152/// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's
153/// position forever.  Doing it here reads the position from `pos_dev` like every other kernel, so the grid and
154/// the arguments are the same for every token and the graph replays correctly.
155__global__ void indexer_key_append_kernel(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev,
156                                          int pos_base, const float* __restrict__ w_k_norm, float eps,
157                                          float* __restrict__ tail, float* __restrict__ dead,
158                                          float* __restrict__ pooled, int32_t* __restrict__ block_pos,
159                                          int idx_dim, int r, int n_rot, const float* __restrict__ cos_tab,
160                                          const float* __restrict__ sin_tab, const int32_t* __restrict__ mtab) {
161    extern __shared__ double s_mean[];   // idx_dim doubles
162    const int d = threadIdx.x;
163    const int pos = (int) __ldg(pos_dev);
164    const int slot = pos % r;
165
166    // The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly.
167    // That is what makes `idx_block - 1` rows enough.
168    if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d];
169
170    // The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason
171    // cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block.
172    if (pos == 0) {
173        double p = (double) raw[d];
174        double ss = 0.0;
175        // Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential.
176        // Every thread computes the same `ss` and uses only its own output element.
177        //
178        // `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision
179        // intrinsics, and using them on doubles silently rounds every operation to float.  `ss` then carries
180        // only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare
181        // key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices.  `__ddiv_rn`
182        // and `__dsqrt_rn` pin the reciprocal square root for the same reason.
183        for (int i = 0; i < idx_dim; ++i) {
184            const double v = (double) raw[i];
185            ss = __dadd_rn(ss, __dmul_rn(v, v));
186        }
187        const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps));
188        float y = (float) (p * inv * (double) w_k_norm[d]);
189        // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native
190        // indexer's spare does.  At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the
191        // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier).
192        // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the
193        // parity test holds bit-exact.  Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude
194        // correction exactly like every other pooled row and like the native kernel's spare (the unrotated
195        // dims pass through, as in the rotation of the completed blocks below).  Skipping the rotation here,
196        // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache.
197        if (d < n_rot) y *= cos_tab[d % (n_rot / 2)];
198        dead[d] = y;
199        pooled[d] = y;
200    }
201
202    if (slot != r - 1) return;
203    __syncthreads();                     // the tail rows this thread is about to read are written above
204
205    // The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming
206    // cell (slot r-1).  The sum of r f32 values is exact in double, so the mean's order cannot matter here -
207    // but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides.
208    double m = 0.0;
209    for (int j = 0; j < r - 1; ++j) m = __dadd_rn(m, (double) tail[(size_t) j * idx_dim + d]);
210    m = __dadd_rn(m, (double) raw[d]);
211    m = m / (double) r;
212    s_mean[d] = m;
213    __syncthreads();
214
215    double ss = 0.0;
216    for (int i = 0; i < idx_dim; ++i) ss = __dadd_rn(ss, __dmul_rn(s_mean[i], s_mean[i]));
217    const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps));
218
219    const int b = pos / r;
220    pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]);
221    // The spare slot MOVES to b+1 and is rewritten with the same constant value.
222    pooled[(size_t) (b + 1) * idx_dim + d] = dead[d];
223    // The rotation position for this row, kept because a capture reader and the debug dumps want it.  It is the
224    // block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`.
225    if (d == 0) *block_pos = (int32_t) (pos_base + b * r);
226    __syncthreads();   // the row is complete only now; the rotation below reads TWO elements of it
227
228    // ---- the rotation of the row that just completed, IN PLACE.
229    //
230    // `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the
231    // barrier above, which is why the guard is here and not around the whole block's tail.
232    //
233    // The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps
234    // every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence.
235    const int half = n_rot / 2;
236    if (d < half) {
237        float* row = pooled + (size_t) b * idx_dim;
238        const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half;
239        // THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES.  A second transcription of the pairing is
240        // what this project keeps finding written down wrong.
241        rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]);
242    }
243}
244
245// ================= 3. qsa_index =================
246
247/// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps
248/// the row's score onto its cells.  The reference's Relu is PER HEAD, so the dots cannot be summed first.
249__global__ void qsa_index_kernel(const float* __restrict__ pooled,
250                                 const float* __restrict__ q_idx, const float* __restrict__ bias,
251                                 int idx_n_head, int idx_dim, long long r,
252                                 const int32_t* __restrict__ step, float* __restrict__ cell_scores) {
253    const long long n_bid = (long long) __ldg(step + kStepNBid);
254    const long long n_kv = (long long) __ldg(step + kStepNKv);
255    __shared__ double s_dot[32];
256    const long long b = blockIdx.x;
257    // A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING.  This is what lets the LAYER launch a CONSTANT
258    // grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value
259    // is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument.
260    // Without this guard, a capacity-sized grid would score pooled rows that have not been written yet -
261    // reading zeros and producing a plausible score for a block that does not exist.
262    if (b > n_bid) return;
263    const int wid = threadIdx.x >> 5, lane = threadIdx.x & 31;
264    if (wid == 0) s_dot[lane] = 0.0;     // thread 0 reads all idx_n_head entries; zero the unused ones
265    __syncthreads();
266
267    double acc = 0.0;
268    for (int d = lane; d < idx_dim; d += 32)
269        acc = __dadd_rn(acc, __dmul_rn((double) pooled[(size_t) b * idx_dim + d],
270                                       (double) q_idx[(size_t) wid * idx_dim + d]));
271    for (int o = 16; o > 0; o >>= 1) acc = __dadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, o));
272    if (lane == 0) s_dot[wid] = acc;
273    __syncthreads();
274
275    if (threadIdx.x != 0) return;
276    double score = 0.0;
277    for (int h = 0; h < idx_n_head; ++h) score += (s_dot[h] > 0.0) ? s_dot[h] : 0.0;
278    if (bias != nullptr) score += (double) bias[b];
279    // cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid
280    long long lo = b * r, hi = lo + r;
281    if (b == n_bid) hi = n_kv;
282    if (hi > n_kv) hi = n_kv;
283    // llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells
284    // a finite +1e9 bias before top-k.  Read the current step on every replay:
285    // the spare row becomes an ordinary block as soon as its fourth cell arrives.
286    float sc = (float) score;
287    if (b == n_bid && n_kv % r != 0) sc += 1e9f;
288    for (long long j = lo; j < hi; ++j) cell_scores[j] = sc;
289}
290
291// ================= 4. topk_512 =================
292
293/// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float
294/// semantics.  `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by
295/// index), while the raw bit pattern orders them.  A NaN is mapped to 0, below every real key, i.e. never
296/// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement.
297__device__ __forceinline__ uint32_t order_key(float s) {
298    const float v = s + 0.0f;
299    if (!(v == v)) return 0u;
300    uint32_t b;
301    memcpy(&b, &v, 4);
302    return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
303}
304
305constexpr int TOPK_THREADS = 256;
306
307__global__ void topk_kernel(const float* __restrict__ scores, const int32_t* __restrict__ step,
308                           int* __restrict__ out_ids) {
309    const long long n_kv = (long long) __ldg(step + kStepNKv);
310    const long long width = (long long) __ldg(step + kStepWidth);
311    __shared__ int s_a[TOPK_THREADS];
312    __shared__ int s_b[TOPK_THREADS];
313    __shared__ long long s_cgt;
314    const int t = threadIdx.x;
315    const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS;
316    const long long lo = (long long) t * chunk;
317    long long hi = lo + chunk;
318    if (hi > n_kv) hi = n_kv;
319
320    // ---- binary lifting: the largest key v with count(key >= v) >= width.  Monotone in v, so setting the
321    // bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1).
322    uint32_t v = 0u;
323    for (int bit = 31; bit >= 0; --bit) {
324        const uint32_t cand = v | (1u << bit);
325        int c = 0;
326        for (long long j = lo; j < hi; ++j) if (order_key(scores[j]) >= cand) ++c;
327        s_a[t] = c;
328        __syncthreads();
329        for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) {
330            if (t < s) s_a[t] += s_a[t + s];
331            __syncthreads();
332        }
333        const int tot = s_a[0];
334        __syncthreads();     // before the next round overwrites s_a
335        if (tot >= (int) width) v = cand;
336    }
337    const uint32_t thr = v;
338
339    // ---- counts and their exclusive prefixes.  The prefixes are computed by thread 0 in one walk, which is
340    // 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already
341    // 32 passes deep.
342    int gt = 0, eq = 0;
343    for (long long j = lo; j < hi; ++j) {
344        const uint32_t k = order_key(scores[j]);
345        if (k > thr) ++gt;
346        else if (k == thr) ++eq;
347    }
348    s_a[t] = gt;
349    s_b[t] = eq;
350    __syncthreads();
351    if (t == 0) {
352        long long ag = 0, ae = 0;
353        for (int i = 0; i < TOPK_THREADS; ++i) {
354            const int g = s_a[i], e = s_b[i];
355            s_a[i] = (int) ag;
356            s_b[i] = (int) ae;
357            ag += g;
358            ae += e;
359        }
360        s_cgt = ag;    // how many are strictly above the threshold, i.e. where the equals start
361    }
362    __syncthreads();
363    // THE RANK VS THE COUNT.  `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is
364    // compared against `eq_budget`, the number of them the selection has room for.  The first version wrote
365    // `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and
366    // compared THAT against the budget.  With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing
367    // was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale.
368    // Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide.
369    const long long off_eq = s_b[t];
370    const long long eq_budget = width - s_cgt;
371
372    // ---- how many this chunk selects, so the ascending walk can be scattered into place
373    int sel = 0;
374    {
375        long long e = off_eq;
376        for (long long j = lo; j < hi; ++j) {
377            const uint32_t k = order_key(scores[j]);
378            if (k > thr) ++sel;
379            else if (k == thr && e < eq_budget) { ++sel; ++e; }
380        }
381    }
382    s_a[t] = sel;
383    __syncthreads();
384    if (t == 0) {
385        long long a = 0;
386        for (int i = 0; i < TOPK_THREADS; ++i) {
387            const int c = s_a[i];
388            s_a[i] = (int) a;
389            a += c;
390        }
391    }
392    __syncthreads();
393
394    // ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself
395    long long w = s_a[t];
396    long long e = off_eq;
397    for (long long j = lo; j < hi; ++j) {
398        const uint32_t k = order_key(scores[j]);
399        if (k > thr) out_ids[w++] = (int) j;
400        else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; }
401    }
402}
403
404// ================= 5. kv_gather =================
405
406__global__ void kv_gather_kernel(const uint16_t* __restrict__ k_pool, const uint16_t* __restrict__ v_pool,
407                                 const int32_t* __restrict__ table, const int32_t* __restrict__ ids,
408                                const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size,
409                                uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) {
410    const long long n_ids = (long long) __ldg(step + kStepWidth);
411    const int per = head_dim / 4;                       // 4 halfs per uint2
412    const long long total = n_ids * kv_heads * per;
413    const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
414    if (i >= total) return;
415    const long long id = i / (kv_heads * (long long) per);
416    const int rem = (int) (i % (kv_heads * (long long) per));
417    const int h = rem / per, q = rem - h * per;
418    const int cell = ids[id];
419    const long long page = (long long) table[cell / page_size];
420    const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q;
421    const long long dst = (id * kv_heads + h) * (long long) per + q;
422    reinterpret_cast<uint2*>(k_scratch)[dst] = reinterpret_cast<const uint2*>(k_pool)[src];
423    reinterpret_cast<uint2*>(v_scratch)[dst] = reinterpret_cast<const uint2*>(v_pool)[src];
424}
425
426// ================= 6. qsa_attend =================
427
428__device__ __forceinline__ float warp_max(float v) {
429    for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
430    return v;
431}
432
433__device__ __forceinline__ float warp_sum(float v) {
434    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
435    return v;
436}
437
438/// One block per query head.  `s` holds the scores, which are then overwritten with the softmax weights.
439__global__ void qsa_attend_kernel(const float* __restrict__ q, const uint16_t* __restrict__ k_scratch,
440                                  const uint16_t* __restrict__ v_scratch, const int32_t* __restrict__ step,
441                                 int n_head, int n_head_kv, int head_dim,
442                                 float* __restrict__ attn, float* __restrict__ weights) {
443    const long long n_ids = (long long) __ldg(step + kStepWidth);
444    extern __shared__ float s_w[];       // CAPACITY floats (scores, then weights) + 32 for the reductions
445    float* red = s_w;                    // red[0..31] live past the scores/weights: see the launch
446    float* w = s_w + 32;
447    const int h = blockIdx.x;
448    const int d = threadIdx.x;
449    // AN EMPTY SELECTION IS HANDLED HERE, not by a host early return.  The wrapper used to check `n_ids == 0`
450    // and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the
451    // device, and this is also the only form a graph can replay: the launch is unconditional and the kernel
452    // decides.  Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is
453    // reachable only for a genuinely empty cache, and the reference returns zeros for that.
454    if (n_ids == 0) {
455        for (int i = d; i < head_dim; i += blockDim.x) attn[(size_t) h * head_dim + i] = 0.0f;
456        return;
457    }
458    const int kv = h / (n_head / n_head_kv);       // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv
459    const float scale = 1.0f / sqrtf((float) head_dim);
460    const int lane = d & 31, wid = d >> 5, nwarp = (int) ((blockDim.x + 31) >> 5);
461
462    for (long long j = d; j < n_ids; j += blockDim.x) {
463        const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim;
464        float acc = 0.0f;
465        for (int i = 0; i < head_dim; ++i) acc += h2f(krow[i]) * q[(size_t) h * head_dim + i];
466        w[j] = acc * scale;
467    }
468    __syncthreads();
469
470    float mx = -FLT_MAX;    // not -inf, whose double -> float conversion nvcc warns about
471    for (long long j = d; j < n_ids; j += blockDim.x) mx = fmaxf(mx, w[j]);
472    mx = warp_max(mx);
473    if (lane == 0) red[wid] = mx;
474    __syncthreads();
475    if (wid == 0) {
476        mx = (lane < nwarp) ? red[lane] : -FLT_MAX;
477        mx = warp_max(mx);
478        if (lane == 0) red[0] = mx;
479    }
480    __syncthreads();
481    mx = red[0];
482    __syncthreads();
483
484    float sum = 0.0f;
485    for (long long j = d; j < n_ids; j += blockDim.x) {
486        const float e = expf(w[j] - mx);
487        w[j] = e;
488        sum += e;
489    }
490    sum = warp_sum(sum);
491    if (lane == 0) red[wid] = sum;
492    __syncthreads();
493    if (wid == 0) {
494        sum = (lane < nwarp) ? red[lane] : 0.0f;
495        sum = warp_sum(sum);
496        if (lane == 0) red[0] = 1.0f / sum;
497    }
498    __syncthreads();
499    const float inv = red[0];
500    __syncthreads();
501
502    float acc = 0.0f;
503    for (long long j = 0; j < n_ids; ++j)
504        acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]);
505    attn[(size_t) h * head_dim + d] = acc;
506    if (weights != nullptr) {
507        for (long long j = d; j < n_ids; j += blockDim.x) weights[(size_t) h * n_ids + j] = w[j] * inv;
508    }
509}
510
511// ================= 7. qsa_gate_apply =================
512
513__global__ void qsa_gate_apply_kernel(const float* __restrict__ attn, const float* __restrict__ q_full,
514                                      int n_head, int head_dim, uint16_t* __restrict__ out) {
515    const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
516    if (i >= (long long) n_head * head_dim) return;
517    const int h = (int) (i / head_dim), d = (int) (i % head_dim);
518    const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d];   // the SECOND half
519    const double sig = 1.0 / (1.0 + exp(-g));
520    out[i] = f16_from_f32((float) ((double) attn[i] * sig));
521}
522
523inline unsigned grid_for(long long n, int threads) {
524    return (unsigned) ((n + threads - 1) / threads);
525}
526
527}  // namespace
528
529/// THE STEP STATE, UPLOADED.  Every kernel below reads its per-token counts from here rather than from a kernel
530/// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`.  This
531/// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels
532/// already read the device values; the layer will pass its own buffer once it captures.
533///
534/// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same
535/// stream and the host is the only writer.  `cudaMemcpyAsync` on the null stream is ordered against the null
536/// stream's kernels, which is what every direct-launch caller here uses.
537namespace {
538
539int32_t* step_scratch() {
540    static int32_t* d_step = nullptr;
541    if (d_step == nullptr) {
542        if (cudaMalloc(&d_step, qsa_step_bytes()) != cudaSuccess) {
543            std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n");
544            std::exit(1);
545        }
546    }
547    return d_step;
548}
549
550void step_upload_raw(const int32_t* h_step) {
551    int32_t* d = step_scratch();
552    if (cudaMemcpy(d, h_step, qsa_step_bytes(), cudaMemcpyHostToDevice) != cudaSuccess) {
553        std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n");
554        std::exit(1);
555    }
556}
557
558/// From a POSITION: fills all four entries.  This is the form the layer will use, and the only form that cannot
559/// produce an inconsistent `n_kv`/`n_bid`/`width`.
560const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) {
561    int32_t h[kStepCount];
562    qsa_step_fill(h, pos, s);
563    // A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the
564    // inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent
565    // preference for one of the two.
566    if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) {
567        std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint,
568                     h[kStepNKv]);
569        std::exit(1);
570    }
571    step_upload_raw(h);
572    return step_scratch();
573}
574
575/// From a WIDTH.  `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so
576/// only that entry is meaningful for them; the others are set consistently anyway rather than left stale,
577/// because a stale entry is a value the NEXT kernel might read.
578const int32_t* step_upload_width(int64_t width, const QsaShapes& s) {
579    int32_t h[kStepCount];
580    for (int i = 0; i < kStepCount; ++i) h[i] = 0;
581    h[kStepWidth] = (int32_t) width;
582    (void) s;
583    step_upload_raw(h);
584    return step_scratch();
585}
586
587}  // namespace
588
589// ================= THE CAPTURABLE ENTRY POINTS =================
590//
591// These are the REAL implementations: every launch below is sized from a constant capacity and every per-token
592// count comes from `step`.  The host-scalar entry points further down are wrappers that fill a module-level step
593// buffer and forward this token's counts as the capacities.
594
595void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step,
596                    const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) {
597    validate(s, "kv_append");
598    if (step == nullptr) fail("kv_append: step is null");
599    // The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell.
600    const long long n = s.n_head_kv * s.head_dim;
601    kv_append_kernel<<<grid_for(n, THREADS), THREADS, 0, (cudaStream_t) stream>>>(
602        k_pool, v_pool, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,
603        host ? *host : KvHostPools{});
604    check_launch("kv_append");
605    if (stream == nullptr) check_sync("kv_append");
606}
607
608void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s,
609                    const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) {
610    validate(s, "qsa_index");
611    if (step == nullptr) fail("qsa_index: step is null");
612    if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive");
613    // THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`.  The kernel returns for
614    // `b > n_bid`, so the surplus blocks cost a launch and nothing else.
615    const int threads = 32 * (int) s.idx_n_head;
616    qsa_index_kernel<<<(unsigned) max_blocks, threads, 0, (cudaStream_t) stream>>>(
617        pooled, q_idx, bias, (int) s.idx_n_head, (int) s.idx_dim, s.idx_block, step, cell_scores);
618    check_launch("qsa_index");
619    if (stream == nullptr) check_sync("qsa_index");
620}
621
622void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step,
623                   int32_t* ids, void* stream) {
624    validate(s, "topk_512");
625    if (step == nullptr) fail("topk_512: step is null");
626    // `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this
627    // token's is a device value.  The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and
628    // `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write.
629    const int64_t width_max = qsa_selection_width(kTopkMaxCells, s);
630    if (cap < width_max) {
631        std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n",
632                     (long long) cap, (long long) width_max);
633        std::exit(1);
634    }
635    // One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`.
636    topk_kernel<<<1, TOPK_THREADS, 0, (cudaStream_t) stream>>>(cell_scores, step, ids);
637    check_launch("topk_512");
638    if (stream == nullptr) check_sync("topk_512");
639}
640
641void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table,
642                    const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s,
643                    uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
644    validate(s, "kv_gather");
645    if (step == nullptr) fail("kv_gather: step is null");
646    if (max_ids <= 0) return;
647    // THE GRID IS THE CAPACITY.  The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;`
648    // guard leaves the surplus threads idle.
649    const long long total = max_ids * s.n_head_kv * (s.head_dim / 4);
650    kv_gather_kernel<<<grid_for(total, 256), 256, 0, (cudaStream_t) stream>>>(
651        k_pool, v_pool, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size,
652        k_scratch, v_scratch);
653    check_launch("kv_gather");
654    if (stream == nullptr) check_sync("kv_gather");
655}
656
657void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch,
658                     const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights,
659                     void* stream) {
660    validate(s, "qsa_attend");
661    if (step == nullptr) fail("qsa_attend: step is null");
662    if (max_ids <= 0) fail("qsa_attend: max_ids must be positive");
663    // THE SHARED SIZE IS THE CAPACITY.  Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from
664    // this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and
665    // then index past it at token 500.  The kernel reads the real count from `step`, so a larger allocation is
666    // exactly what it wants.  The opt-in therefore happens once, for the capacity.
667    const size_t smem = (size_t) (max_ids + 32) * sizeof(float);
668    // per DEVICE: the opt-in is a device setting (a layer split runs this on two cards)
669    static size_t s_configured_dev[64] = {};
670    int cur_dev = 0;
671    cudaGetDevice(&cur_dev);
672    size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0];
673    if (smem > s_configured) {
674        int dev = 0, max_shared = 0;
675        cudaGetDevice(&dev);
676        cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
677        max_shared = strata::smem_optin_of(max_shared);
678        if ((int) smem > max_shared) {
679            std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n",
680                         (long long) max_ids, smem, max_shared);
681            std::exit(1);
682        }
683        const cudaError_t e =
684            cudaFuncSetAttribute(qsa_attend_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem);
685        if (e != cudaSuccess) {
686            std::fprintf(stderr, "qsa: qsa_attend: shared opt-in: %s\n", cudaGetErrorString(e));
687            std::exit(1);
688        }
689        s_configured = smem;
690    }
691    qsa_attend_kernel<<<(unsigned) s.n_head, (unsigned) s.head_dim, smem, (cudaStream_t) stream>>>(
692        q, k_scratch, v_scratch, step, (int) s.n_head, (int) s.n_head_kv, (int) s.head_dim, attn, weights);
693    check_launch("qsa_attend");
694    if (stream == nullptr) check_sync("qsa_attend");
695}
696
697// ================= host entry points =================
698
699void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) {
700    if (host_step == nullptr) return;
701    if (pos < 0) fail("qsa_step_fill: pos < 0");
702    // ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four
703    // separate parameters.  `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in
704    // itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency
705    // now has a single writer to check against instead of two independent arguments.
706    //
707    // This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one
708    // H2D per token updates all of them and no entry point takes a per-token scalar.
709    const int64_t n_kv = pos + 1;
710    host_step[kStepPos] = (int32_t) pos;
711    host_step[kStepNKv] = (int32_t) n_kv;
712    host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block);
713    host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s);
714}
715
716void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos,
717               const float* kcur, const float* vcur, const QsaShapes& s, void* stream) {
718    if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); }
719    kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream);
720}
721
722void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm,
723                        float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab,
724                        const float* sin_tab, void* stream) {
725    validate(s, "indexer_key_append");
726    if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null");
727    if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr)
728        fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)");
729    const int threads = (int) s.idx_dim;
730    const size_t smem = (size_t) s.idx_dim * sizeof(double);
731    // **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.**  The completion rotation is inside the kernel now.  The
732    // arguments here are identical for every token, which is the property a CUDA graph needs: this function can
733    // be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data.
734    indexer_key_append_kernel<<<1, threads, smem, (cudaStream_t) stream>>>(
735        raw, pos_dev, (int) pos_base, w_k_norm, eps, b.tail, b.dead, b.pooled, b.block_pos, (int) s.idx_dim,
736        (int) s.idx_block, (int) s.n_rot, cos_tab, sin_tab, mrope_table());
737    check_launch("indexer_key_append");
738    if (stream == nullptr) check_sync("indexer_key_append");
739}
740
741void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s,
742               int64_t n_kv, float* cell_scores, void* stream) {
743    validate(s, "qsa_index");
744    if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0");
745    // `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments
746    // disagree rather than launching a kernel that would score the wrong number of blocks.
747    if ((n_kv / s.idx_block) != n_bid) {
748        std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid,
749                     (long long) n_kv, (long long) s.idx_block);
750        std::exit(1);
751    }
752    // THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph.  The layer passes a
753    // constant `max_blocks` from its state instead - see the note in `qsa.hpp`.
754    qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream);
755}
756
757void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids,
758              void* stream) {
759    validate(s, "topk_512");
760    if (n_kv <= 0) return;
761    if (n_kv > kTopkMaxCells) {
762        std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n",
763                     (long long) n_kv, (long long) kTopkMaxCells);
764        std::exit(1);
765    }
766    topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream);
767}
768
769void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids,
770               int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) {
771    validate(s, "kv_gather");
772    if (n_ids <= 0) return;
773    kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch,
774                   v_scratch, stream);
775}
776
777void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids,
778                const QsaShapes& s, float* attn, float* weights, void* stream) {
779    validate(s, "qsa_attend");
780    if (n_ids < 0) fail("qsa_attend: n_ids < 0");
781    if (n_ids == 0) {
782        // The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the
783        // wrapper gives it the geometry's capacity rather than 0.
784        qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s),
785                        qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream);
786        return;
787    }
788    qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream);
789}
790
791/// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller
792/// whose weight is a K-quant needs the f32 form.  Identical arithmetic up to the last step.
793__global__ void qsa_gate_apply_f32_kernel(const float* __restrict__ attn, const float* __restrict__ q_full,
794                                          int n_head, int head_dim, float* __restrict__ out) {
795    const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x;
796    if (i >= (long long) n_head * head_dim) return;
797    const int h = (int) (i / head_dim), d = (int) (i % head_dim);
798    const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d];   // the SECOND half
799    const double sig = 1.0 / (1.0 + exp(-g));
800    out[i] = (float) ((double) attn[i] * sig);
801}
802
803void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) {
804    validate(s, "qsa_gate_apply_f32");
805    const long long n = s.n_head * s.head_dim;
806    qsa_gate_apply_f32_kernel<<<grid_for(n, 256), 256, 0, (cudaStream_t) stream>>>(attn, q_full, (int) s.n_head,
807                                                                                  (int) s.head_dim, out);
808    check_launch("qsa_gate_apply_f32");
809    if (stream == nullptr) check_sync("qsa_gate_apply_f32");
810}
811
812void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) {
813    validate(s, "qsa_gate_apply");
814    const long long n = s.n_head * s.head_dim;
815    qsa_gate_apply_kernel<<<grid_for(n, 256), 256, 0, (cudaStream_t) stream>>>(attn, q_full, (int) s.n_head,
816                                                                              (int) s.head_dim, out);
817    check_launch("qsa_gate_apply");
818    if (stream == nullptr) check_sync("qsa_gate_apply");
819}
820
821}  // namespace strata::kernels