// src/kernels/cuda/qsa.cu - P2.S2: the QSA cache, indexer and attention (see include/strata/kernels/qsa.hpp). // // The header documents the layouts and the scope; this file documents the four decisions that are about the // KERNEL rather than about the interface. // // 1. THE THRESHOLD SEARCH IN `topk_512` RATHER THAN A SORT. The selection has to reproduce `ggml_top_k` on the // masked per-cell scores with the reference's tie rule (ascending index), and it has to be EXACT: a // different selected set is a different attention input, and `docs/capture-format.md` L127 gives // `indexer_ids` no tolerance. The kernel therefore computes the width-th largest score as a 32-bit // "order key" by binary lifting (32 monotone passes with `count(key >= cand) >= width`), and then emits - // in ONE ascending walk - every cell strictly above it and the first `width - c_gt` cells equal to it. That // is provably the same set as sorting by (score desc, index asc) and taking the first width, it needs no // scratch and no sort, it is deterministic, and it is the reason `kTopkMaxCells` exists: the whole selection // runs in ONE block so the ascending walk is a chunked scan rather than a second global pass. Phase 3 // replaces it with a radix select; this one is the thing that radix select has to agree with. // // 2. ONE BLOCK PER HEAD IN `qsa_attend`, SCORES IN SHARED MEMORY. n_ids reaches 2051, so a per-head score // vector is 8 KB and 24 heads are 24 blocks: the whole attention is 24 blocks x 256 threads, which is a // small grid, but it is also exactly the shape the source uses (one flash tile per query head) and it keeps // the softmax's three passes over the scores in shared memory instead of in global. The score loop has one // thread per CELL walking the 256 dims sequentially, which reads 16-byte-vectorisable half2 runs; the value // loop has one thread per DIM walking the cells, whose warp-wide reads are contiguous within a cell. Both // are coalesced for the layout the gather produces. // // 3. NO `__float2half`. `f16_from_f32` from f16_bits.hpp, for the reason round 193 recorded: `__float2half` // produced 0x2600 for 0x26DB and 0x3C01 for exactly 1.0. The parity test checks that converter against // vectors generated by numpy's float16, which is an oracle sharing no code with it. // // 4. THE POOLING ARITHMETIC IS IN DOUBLE AND ORDER-FIXED. `pooled` and the spare key are compared BIT-EXACT // against the reference (the spare key's rotation is at position 0, where the f32 rope kernel is an exact // identity, so the comparison is not weakened by the rope). That needs the same summation order on both // sides: the `r` raw keys are added in CELL order, the sum of squares runs d = 0..idx_dim-1 sequentially, // and `__dadd_rn`/`__dmul_rn` block FMA contraction, which would otherwise fuse `ss + m*m` into one // operation with no intermediate rounding and land one ulp away from the host. // // THE `d` IN THOSE NAMES IS NOT COSMETIC. The first version wrote `__fadd_rn`/`__fmul_rn`, which are // the SINGLE-precision intrinsics: the compiler converted each double operand to float, operated // there, and converted back, so the whole pooling arithmetic ran in single precision - `ss` held only // float precision (121.82236480712891 on the device against 121.82236342931094 in the reference). // Every comparison still passed at any sane tolerance, the spare key landing 0.4 f32 ulp away; only a // BIT-EXACT assertion plus a full-precision probe of the intermediate found it. That is the strongest // argument in this file for keeping both. #include "strata/core/emulate.hpp" #include "strata/kernels/qsa.hpp" #include "strata/kernels/f16_bits.hpp" #include "strata/kernels/kv_stream.hpp" #include "strata/kernels/rope.hpp" #include "strata/kernels/mrope.hpp" #include #include #include #include #include #include namespace strata::kernels { namespace { constexpr int THREADS = 128; void fail(const char* what) { std::fprintf(stderr, "qsa: %s\n", what); std::exit(1); } void check_launch(const char* what) { const cudaError_t e = cudaGetLastError(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa: %s launch: %s\n", what, cudaGetErrorString(e)); std::exit(1); } } /// The SYNCHRONOUS entry points must check their own wait. Without this the sticky error from a kernel that /// faulted becomes visible only at the NEXT call's `cudaGetLastError()`, which then names the wrong kernel - /// exactly the mis-attribution that made round 198's first `kv_append` failure look like a later one. void check_sync(const char* what) { const cudaError_t e = cudaDeviceSynchronize(); if (e != cudaSuccess) { std::fprintf(stderr, "qsa: %s (synchronise): %s\n", what, cudaGetErrorString(e)); std::exit(1); } } /// Geometry validation. A silently wrong `head_dim % 4` would corrupt the gather's uint2 copy and a silently /// wrong `n_head % n_head_kv` would produce a plausible attention with the wrong key, so both are refused. void validate(const QsaShapes& s, const char* who) { if (s.n_head <= 0 || s.n_head_kv <= 0 || s.head_dim <= 0 || s.idx_dim <= 0 || s.idx_n_head <= 0 || s.idx_block < 2 || s.page_size < 1) { std::fprintf(stderr, "qsa: %s: geometry is not set up\n", who); std::exit(1); } if (s.n_head % s.n_head_kv != 0) { std::fprintf(stderr, "qsa: %s: n_head %lld is not a multiple of n_head_kv %lld\n", who, (long long) s.n_head, (long long) s.n_head_kv); std::exit(1); } if (s.head_dim % 4 != 0) { std::fprintf(stderr, "qsa: %s: head_dim %lld must be a multiple of 4 (the gather copies uint2)\n", who, (long long) s.head_dim); std::exit(1); } if (s.n_rot <= 0 || s.n_rot % 2 != 0 || s.n_rot > s.head_dim || s.n_rot > s.idx_dim) { std::fprintf(stderr, "qsa: %s: n_rot %lld must be even and <= head_dim %lld and idx_dim %lld\n", who, (long long) s.n_rot, (long long) s.head_dim, (long long) s.idx_dim); std::exit(1); } if (s.idx_n_head > 32) { std::fprintf(stderr, "qsa: %s: idx_n_head %lld > 32 (one warp per indexer head)\n", who, (long long) s.idx_n_head); std::exit(1); } } __device__ __forceinline__ float h2f(uint16_t bits) { return f32_from_f16(bits); } // ================= 1. kv_append ================= __global__ void kv_append_kernel(uint16_t* __restrict__ k_pool, uint16_t* __restrict__ v_pool, const int32_t* __restrict__ table, const int32_t* __restrict__ step, const float* __restrict__ kcur, const float* __restrict__ vcur, int kv_heads, int head_dim, int page_size, KvHostPools host) { const long long pos = (long long) __ldg(step + kStepPos); const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= kv_heads * head_dim) return; const int h = i / head_dim, d = i - h * head_dim; // `[page][kv_head][page_size][head_dim]`: one head's consecutive cells are contiguous inside a page. // KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident. const long long page = (long long) table[pos / page_size]; if (page >= 0) { const long long row = (page * kv_heads + h) * page_size + (pos % page_size); k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); } if (host.k_pool != nullptr) { const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); host.k_pool[row * head_dim + d] = f16_from_f32(kcur[i]); host.v_pool[row * head_dim + d] = f16_from_f32(vcur[i]); } } // ================= 2. indexer_key_append ================= /// Appends the raw key, and on a block completion pools AND ROTATES the pooled row. One thread per indexer /// dim, shared `mean` in double. /// /// **THE ROTATION IS INSIDE THIS KERNEL, AND THAT IS WHAT MAKES THE WHOLE FUNCTION CAPTURABLE.** It used to be /// a second launch from the host wrapper, guarded by `if (pos % idx_block == idx_block - 1)` - a HOST branch on /// `pos`, which forced `pos` to be a host scalar, which meant a captured graph would replay the first token's /// position forever. Doing it here reads the position from `pos_dev` like every other kernel, so the grid and /// the arguments are the same for every token and the graph replays correctly. __global__ void indexer_key_append_kernel(const float* __restrict__ raw, const int32_t* __restrict__ pos_dev, int pos_base, const float* __restrict__ w_k_norm, float eps, float* __restrict__ tail, float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, int idx_dim, int r, int n_rot, const float* __restrict__ cos_tab, const float* __restrict__ sin_tab, const int32_t* __restrict__ mtab) { extern __shared__ double s_mean[]; // idx_dim doubles const int d = threadIdx.x; const int pos = (int) __ldg(pos_dev); const int slot = pos % r; // The RAW tail: a cell that COMPLETES a block is not stored, because the pool below consumes it directly. // That is what makes `idx_block - 1` rows enough. if (slot < r - 1) tail[(size_t) slot * idx_dim + d] = raw[d]; // The spare slot's key is `rms_norm(raw[0])`, which is CONSTANT for the sequence and is the only reason // cell 0's raw key has to be kept: the three-row tail no longer holds it after the first block. if (pos == 0) { double p = (double) raw[d]; double ss = 0.0; // Same order as the pooled path, so the two are comparable: sum of squares over the dims, sequential. // Every thread computes the same `ss` and uses only its own output element. // // `__dadd_rn`/`__dmul_rn`, NOT `__fadd_rn`/`__fmul_rn`: the `f` names are the SINGLE-precision // intrinsics, and using them on doubles silently rounds every operation to float. `ss` then carries // only float precision (121.82236480712891 against the reference's 121.82236342931094) and the spare // key comes out 0.4 f32 ulp away - close enough that only a BIT-EXACT assertion notices. `__ddiv_rn` // and `__dsqrt_rn` pin the reciprocal square root for the same reason. for (int i = 0; i < idx_dim; ++i) { const double v = (double) raw[i]; ss = __dadd_rn(ss, __dmul_rn(v, v)); } const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); float y = (float) (p * inv * (double) w_k_norm[d]); // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude // correction exactly like every other pooled row and like the native kernel's spare (the unrotated // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. if (d < n_rot) y *= cos_tab[d % (n_rot / 2)]; dead[d] = y; pooled[d] = y; } if (slot != r - 1) return; __syncthreads(); // the tail rows this thread is about to read are written above // The mean of this block's r raw keys, in CELL order: the r-1 tail rows (slots 0..r-2) then the incoming // cell (slot r-1). The sum of r f32 values is exact in double, so the mean's order cannot matter here - // but the order of the SUM OF SQUARES below can, and it is fixed to d ascending on both sides. double m = 0.0; for (int j = 0; j < r - 1; ++j) m = __dadd_rn(m, (double) tail[(size_t) j * idx_dim + d]); m = __dadd_rn(m, (double) raw[d]); m = m / (double) r; s_mean[d] = m; __syncthreads(); double ss = 0.0; for (int i = 0; i < idx_dim; ++i) ss = __dadd_rn(ss, __dmul_rn(s_mean[i], s_mean[i])); const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); const int b = pos / r; pooled[(size_t) b * idx_dim + d] = (float) (m * inv * (double) w_k_norm[d]); // The spare slot MOVES to b+1 and is rewritten with the same constant value. pooled[(size_t) (b + 1) * idx_dim + d] = dead[d]; // The rotation position for this row, kept because a capture reader and the debug dumps want it. It is the // block's first cell's POSITION, `pos_base + b*r`, and NOT the cell index `b*r`. if (d == 0) *block_pos = (int32_t) (pos_base + b * r); __syncthreads(); // the row is complete only now; the rotation below reads TWO elements of it // ---- the rotation of the row that just completed, IN PLACE. // // `i` pairs with `i + half`, so only the first `half` threads do any work - but EVERY thread must reach the // barrier above, which is why the guard is here and not around the whole block's tail. // // The position is the BLOCK'S FIRST cell (`ref/qsa.py` PROPERTY 4: rotating at the block's last cell keeps // every shape and every magnitude), and it comes from `pos_base`, which is constant for a sequence. const int half = n_rot / 2; if (d < half) { float* row = pooled + (size_t) b * idx_dim; const size_t toff = (size_t) mrope_pos(mtab, pos_base + b * r, d) * half; // THE SAME `rope_neox_pair` THE STANDALONE ROPE KERNEL USES. A second transcription of the pairing is // what this project keeps finding written down wrong. rope_neox_pair(row[d], row[half + d], cos_tab[toff + d], sin_tab[toff + d], row[d], row[half + d]); } } // ================= 3. qsa_index ================= /// One warp per indexer head, one block per pooled row; thread 0 sums the relu'd dots IN HEAD ORDER and maps /// the row's score onto its cells. The reference's Relu is PER HEAD, so the dots cannot be summed first. __global__ void qsa_index_kernel(const float* __restrict__ pooled, const float* __restrict__ q_idx, const float* __restrict__ bias, int idx_n_head, int idx_dim, long long r, const int32_t* __restrict__ step, float* __restrict__ cell_scores) { const long long n_bid = (long long) __ldg(step + kStepNBid); const long long n_kv = (long long) __ldg(step + kStepNKv); __shared__ double s_dot[32]; const long long b = blockIdx.x; // A BLOCK PAST THE COMPLETED-BLOCK COUNT MUST DO NOTHING. This is what lets the LAYER launch a CONSTANT // grid of the maximum block count instead of this token's `n_bid + 1`: a grid sized from a per-token value // is a per-token LAUNCH CONFIGURATION, and a CUDA graph bakes those in exactly as it bakes in an argument. // Without this guard, a capacity-sized grid would score pooled rows that have not been written yet - // reading zeros and producing a plausible score for a block that does not exist. if (b > n_bid) return; const int wid = threadIdx.x >> 5, lane = threadIdx.x & 31; if (wid == 0) s_dot[lane] = 0.0; // thread 0 reads all idx_n_head entries; zero the unused ones __syncthreads(); double acc = 0.0; for (int d = lane; d < idx_dim; d += 32) acc = __dadd_rn(acc, __dmul_rn((double) pooled[(size_t) b * idx_dim + d], (double) q_idx[(size_t) wid * idx_dim + d])); for (int o = 16; o > 0; o >>= 1) acc = __dadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, o)); if (lane == 0) s_dot[wid] = acc; __syncthreads(); if (threadIdx.x != 0) return; double score = 0.0; for (int h = 0; h < idx_n_head; ++h) score += (s_dot[h] > 0.0) ? s_dot[h] : 0.0; if (bias != nullptr) score += (double) bias[b]; // cell_block: cells of block b for b < n_bid, and the WHOLE incomplete tail for b == n_bid long long lo = b * r, hi = lo + r; if (b == n_bid) hi = n_kv; if (hi > n_kv) hi = n_kv; // llama-memory-hybrid-idx.cpp::set_input_qsa gives incomplete-tail cells // a finite +1e9 bias before top-k. Read the current step on every replay: // the spare row becomes an ordinary block as soon as its fourth cell arrives. float sc = (float) score; if (b == n_bid && n_kv % r != 0) sc += 1e9f; for (long long j = lo; j < hi; ++j) cell_scores[j] = sc; } // ================= 4. topk_512 ================= /// Total order over f32 as an unsigned key, so one integer comparison orders scores with numpy's float /// semantics. `+ 0.0f` maps -0.0 to +0.0 because numpy treats them as EQUAL (and would break the tie by /// index), while the raw bit pattern orders them. A NaN is mapped to 0, below every real key, i.e. never /// selected - numpy sorts NaN LAST, and silently selecting one would be worse than the disagreement. __device__ __forceinline__ uint32_t order_key(float s) { const float v = s + 0.0f; if (!(v == v)) return 0u; uint32_t b; memcpy(&b, &v, 4); return (b & 0x80000000u) ? ~b : (b | 0x80000000u); } constexpr int TOPK_THREADS = 256; __global__ void topk_kernel(const float* __restrict__ scores, const int32_t* __restrict__ step, int* __restrict__ out_ids) { const long long n_kv = (long long) __ldg(step + kStepNKv); const long long width = (long long) __ldg(step + kStepWidth); __shared__ int s_a[TOPK_THREADS]; __shared__ int s_b[TOPK_THREADS]; __shared__ long long s_cgt; const int t = threadIdx.x; const long long chunk = (n_kv + TOPK_THREADS - 1) / TOPK_THREADS; const long long lo = (long long) t * chunk; long long hi = lo + chunk; if (hi > n_kv) hi = n_kv; // ---- binary lifting: the largest key v with count(key >= v) >= width. Monotone in v, so setting the // bits from the top down lands on exactly that value, and count(>= v) >= width > count(>= v+1). uint32_t v = 0u; for (int bit = 31; bit >= 0; --bit) { const uint32_t cand = v | (1u << bit); int c = 0; for (long long j = lo; j < hi; ++j) if (order_key(scores[j]) >= cand) ++c; s_a[t] = c; __syncthreads(); for (int s = TOPK_THREADS / 2; s > 0; s >>= 1) { if (t < s) s_a[t] += s_a[t + s]; __syncthreads(); } const int tot = s_a[0]; __syncthreads(); // before the next round overwrites s_a if (tot >= (int) width) v = cand; } const uint32_t thr = v; // ---- counts and their exclusive prefixes. The prefixes are computed by thread 0 in one walk, which is // 256 iterations ONCE per kernel and removes 2 log-steps of scan machinery from a path that is already // 32 passes deep. int gt = 0, eq = 0; for (long long j = lo; j < hi; ++j) { const uint32_t k = order_key(scores[j]); if (k > thr) ++gt; else if (k == thr) ++eq; } s_a[t] = gt; s_b[t] = eq; __syncthreads(); if (t == 0) { long long ag = 0, ae = 0; for (int i = 0; i < TOPK_THREADS; ++i) { const int g = s_a[i], e = s_b[i]; s_a[i] = (int) ag; s_b[i] = (int) ae; ag += g; ae += e; } s_cgt = ag; // how many are strictly above the threshold, i.e. where the equals start } __syncthreads(); // THE RANK VS THE COUNT. `off_eq` is how many equal-to-threshold cells come BEFORE this chunk, and it is // compared against `eq_budget`, the number of them the selection has room for. The first version wrote // `c_gt + prefix_eq` - where an equal cell would land in a "greater-than first, then equal" LAYOUT - and // compared THAT against the budget. With distinct scores `c_gt == width` and `eq_budget == 0`, so nothing // was ever selected at the threshold and the kernel emitted `width` ids with one missing and one stale. // Every all-equal fixture passed, because there `c_gt == 0` and the two readings coincide. const long long off_eq = s_b[t]; const long long eq_budget = width - s_cgt; // ---- how many this chunk selects, so the ascending walk can be scattered into place int sel = 0; { long long e = off_eq; for (long long j = lo; j < hi; ++j) { const uint32_t k = order_key(scores[j]); if (k > thr) ++sel; else if (k == thr && e < eq_budget) { ++sel; ++e; } } } s_a[t] = sel; __syncthreads(); if (t == 0) { long long a = 0; for (int i = 0; i < TOPK_THREADS; ++i) { const int c = s_a[i]; s_a[i] = (int) a; a += c; } } __syncthreads(); // ---- emit, walking the cells ASCENDING so the tie rule's "first by index" is the walk order itself long long w = s_a[t]; long long e = off_eq; for (long long j = lo; j < hi; ++j) { const uint32_t k = order_key(scores[j]); if (k > thr) out_ids[w++] = (int) j; else if (k == thr && e < eq_budget) { ++e; out_ids[w++] = (int) j; } } } // ================= 5. kv_gather ================= __global__ void kv_gather_kernel(const uint16_t* __restrict__ k_pool, const uint16_t* __restrict__ v_pool, const int32_t* __restrict__ table, const int32_t* __restrict__ ids, const int32_t* __restrict__ step, int kv_heads, int head_dim, int page_size, uint16_t* __restrict__ k_scratch, uint16_t* __restrict__ v_scratch) { const long long n_ids = (long long) __ldg(step + kStepWidth); const int per = head_dim / 4; // 4 halfs per uint2 const long long total = n_ids * kv_heads * per; const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; if (i >= total) return; const long long id = i / (kv_heads * (long long) per); const int rem = (int) (i % (kv_heads * (long long) per)); const int h = rem / per, q = rem - h * per; const int cell = ids[id]; const long long page = (long long) table[cell / page_size]; const long long src = ((page * kv_heads + h) * page_size + (cell % page_size)) * (long long) per + q; const long long dst = (id * kv_heads + h) * (long long) per + q; reinterpret_cast(k_scratch)[dst] = reinterpret_cast(k_pool)[src]; reinterpret_cast(v_scratch)[dst] = reinterpret_cast(v_pool)[src]; } // ================= 6. qsa_attend ================= __device__ __forceinline__ float warp_max(float v) { for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); return v; } __device__ __forceinline__ float warp_sum(float v) { for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); return v; } /// One block per query head. `s` holds the scores, which are then overwritten with the softmax weights. __global__ void qsa_attend_kernel(const float* __restrict__ q, const uint16_t* __restrict__ k_scratch, const uint16_t* __restrict__ v_scratch, const int32_t* __restrict__ step, int n_head, int n_head_kv, int head_dim, float* __restrict__ attn, float* __restrict__ weights) { const long long n_ids = (long long) __ldg(step + kStepWidth); extern __shared__ float s_w[]; // CAPACITY floats (scores, then weights) + 32 for the reductions float* red = s_w; // red[0..31] live past the scores/weights: see the launch float* w = s_w + 32; const int h = blockIdx.x; const int d = threadIdx.x; // AN EMPTY SELECTION IS HANDLED HERE, not by a host early return. The wrapper used to check `n_ids == 0` // and `cudaMemsetAsync` the output, but `n_ids` is a device value now - so the branch has to be on the // device, and this is also the only form a graph can replay: the launch is unconditional and the kernel // decides. Below the selection bound the selection is the IDENTITY, so `n_ids` is never 0 there; it is // reachable only for a genuinely empty cache, and the reference returns zeros for that. if (n_ids == 0) { for (int i = d; i < head_dim; i += blockDim.x) attn[(size_t) h * head_dim + i] = 0.0f; return; } const int kv = h / (n_head / n_head_kv); // ops.cpp L8729: iv2 = iq2 / rv2, NOT h % n_head_kv const float scale = 1.0f / sqrtf((float) head_dim); const int lane = d & 31, wid = d >> 5, nwarp = (int) ((blockDim.x + 31) >> 5); for (long long j = d; j < n_ids; j += blockDim.x) { const uint16_t* krow = k_scratch + (j * n_head_kv + kv) * head_dim; float acc = 0.0f; for (int i = 0; i < head_dim; ++i) acc += h2f(krow[i]) * q[(size_t) h * head_dim + i]; w[j] = acc * scale; } __syncthreads(); float mx = -FLT_MAX; // not -inf, whose double -> float conversion nvcc warns about for (long long j = d; j < n_ids; j += blockDim.x) mx = fmaxf(mx, w[j]); mx = warp_max(mx); if (lane == 0) red[wid] = mx; __syncthreads(); if (wid == 0) { mx = (lane < nwarp) ? red[lane] : -FLT_MAX; mx = warp_max(mx); if (lane == 0) red[0] = mx; } __syncthreads(); mx = red[0]; __syncthreads(); float sum = 0.0f; for (long long j = d; j < n_ids; j += blockDim.x) { const float e = expf(w[j] - mx); w[j] = e; sum += e; } sum = warp_sum(sum); if (lane == 0) red[wid] = sum; __syncthreads(); if (wid == 0) { sum = (lane < nwarp) ? red[lane] : 0.0f; sum = warp_sum(sum); if (lane == 0) red[0] = 1.0f / sum; } __syncthreads(); const float inv = red[0]; __syncthreads(); float acc = 0.0f; for (long long j = 0; j < n_ids; ++j) acc += (w[j] * inv) * h2f(v_scratch[(j * n_head_kv + kv) * head_dim + d]); attn[(size_t) h * head_dim + d] = acc; if (weights != nullptr) { for (long long j = d; j < n_ids; j += blockDim.x) weights[(size_t) h * n_ids + j] = w[j] * inv; } } // ================= 7. qsa_gate_apply ================= __global__ void qsa_gate_apply_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, int n_head, int head_dim, uint16_t* __restrict__ out) { const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; if (i >= (long long) n_head * head_dim) return; const int h = (int) (i / head_dim), d = (int) (i % head_dim); const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half const double sig = 1.0 / (1.0 + exp(-g)); out[i] = f16_from_f32((float) ((double) attn[i] * sig)); } inline unsigned grid_for(long long n, int threads) { return (unsigned) ((n + threads - 1) / threads); } } // namespace /// THE STEP STATE, UPLOADED. Every kernel below reads its per-token counts from here rather than from a kernel /// argument, because a CUDA graph bakes arguments in at capture time - see the long note in `qsa.hpp`. This /// module-level buffer is what lets the OLD host-scalar signatures keep working unchanged while the kernels /// already read the device values; the layer will pass its own buffer once it captures. /// /// It is per-PROCESS and reused, which is safe because the upload and the kernel that reads it are on the same /// stream and the host is the only writer. `cudaMemcpyAsync` on the null stream is ordered against the null /// stream's kernels, which is what every direct-launch caller here uses. namespace { int32_t* step_scratch() { static int32_t* d_step = nullptr; if (d_step == nullptr) { if (cudaMalloc(&d_step, qsa_step_bytes()) != cudaSuccess) { std::fprintf(stderr, "qsa: step upload: cudaMalloc failed\n"); std::exit(1); } } return d_step; } void step_upload_raw(const int32_t* h_step) { int32_t* d = step_scratch(); if (cudaMemcpy(d, h_step, qsa_step_bytes(), cudaMemcpyHostToDevice) != cudaSuccess) { std::fprintf(stderr, "qsa: step upload: cudaMemcpy failed\n"); std::exit(1); } } /// From a POSITION: fills all four entries. This is the form the layer will use, and the only form that cannot /// produce an inconsistent `n_kv`/`n_bid`/`width`. const int32_t* step_upload(int64_t pos, int64_t n_kv_hint, const QsaShapes& s) { int32_t h[kStepCount]; qsa_step_fill(h, pos, s); // A caller that also knows `n_kv` is CHECKED against it rather than believed: a disagreement is exactly the // inconsistency `qsa_step_fill` exists to make impossible, so it is worth an exit rather than a silent // preference for one of the two. if (n_kv_hint >= 0 && n_kv_hint != (int64_t) h[kStepNKv]) { std::fprintf(stderr, "qsa: step upload: n_kv %lld disagrees with pos+1 = %d\n", (long long) n_kv_hint, h[kStepNKv]); std::exit(1); } step_upload_raw(h); return step_scratch(); } /// From a WIDTH. `kv_gather` and `qsa_attend` are handed the selection width directly and never see `pos`, so /// only that entry is meaningful for them; the others are set consistently anyway rather than left stale, /// because a stale entry is a value the NEXT kernel might read. const int32_t* step_upload_width(int64_t width, const QsaShapes& s) { int32_t h[kStepCount]; for (int i = 0; i < kStepCount; ++i) h[i] = 0; h[kStepWidth] = (int32_t) width; (void) s; step_upload_raw(h); return step_scratch(); } } // namespace // ================= THE CAPTURABLE ENTRY POINTS ================= // // These are the REAL implementations: every launch below is sized from a constant capacity and every per-token // count comes from `step`. The host-scalar entry points further down are wrappers that fill a module-level step // buffer and forward this token's counts as the capacities. void kv_append_step(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, const KvHostPools* host) { validate(s, "kv_append"); if (step == nullptr) fail("kv_append: step is null"); // The grid is the head x dim count, which is a CONSTANT - `kv_append` writes one cell. const long long n = s.n_head_kv * s.head_dim; kv_append_kernel<<>>( k_pool, v_pool, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, host ? *host : KvHostPools{}); check_launch("kv_append"); if (stream == nullptr) check_sync("kv_append"); } void qsa_index_step(const float* pooled, const float* q_idx, const float* bias, const QsaShapes& s, const int32_t* step, int64_t max_blocks, float* cell_scores, void* stream) { validate(s, "qsa_index"); if (step == nullptr) fail("qsa_index: step is null"); if (max_blocks <= 0) fail("qsa_index: max_blocks must be positive"); // THE GRID IS `max_blocks`, A CONSTANT - not this token's `n_bid + 1`. The kernel returns for // `b > n_bid`, so the surplus blocks cost a launch and nothing else. const int threads = 32 * (int) s.idx_n_head; qsa_index_kernel<<<(unsigned) max_blocks, threads, 0, (cudaStream_t) stream>>>( pooled, q_idx, bias, (int) s.idx_n_head, (int) s.idx_dim, s.idx_block, step, cell_scores); check_launch("qsa_index"); if (stream == nullptr) check_sync("qsa_index"); } void topk_512_step(const float* cell_scores, const QsaShapes& s, int64_t cap, const int32_t* step, int32_t* ids, void* stream) { validate(s, "topk_512"); if (step == nullptr) fail("topk_512: step is null"); // `cap` is checked against the GEOMETRY'S largest possible width rather than this token's, because this // token's is a device value. The two are the same guarantee: `width = min(n_kv, top_k + r - 1)` and // `n_kv <= kTopkMaxCells`, so this is the most the kernel can ever write. const int64_t width_max = qsa_selection_width(kTopkMaxCells, s); if (cap < width_max) { std::fprintf(stderr, "qsa: topk_512: cap %lld < the largest possible selection width %lld\n", (long long) cap, (long long) width_max); std::exit(1); } // One block, so the launch is already constant; the kernel reads `n_kv` and `width` from `step`. topk_kernel<<<1, TOPK_THREADS, 0, (cudaStream_t) stream>>>(cell_scores, step, ids); check_launch("topk_512"); if (stream == nullptr) check_sync("topk_512"); } void kv_gather_step(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, const int32_t* step, int64_t max_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { validate(s, "kv_gather"); if (step == nullptr) fail("kv_gather: step is null"); if (max_ids <= 0) return; // THE GRID IS THE CAPACITY. The kernel reads the real `n_ids` from `step` and its `if (i >= total) return;` // guard leaves the surplus threads idle. const long long total = max_ids * s.n_head_kv * (s.head_dim / 4); kv_gather_kernel<<>>( k_pool, v_pool, page_table, ids, step, (int) s.n_head_kv, (int) s.head_dim, (int) s.page_size, k_scratch, v_scratch); check_launch("kv_gather"); if (stream == nullptr) check_sync("kv_gather"); } void qsa_attend_step(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, const int32_t* step, int64_t max_ids, const QsaShapes& s, float* attn, float* weights, void* stream) { validate(s, "qsa_attend"); if (step == nullptr) fail("qsa_attend: step is null"); if (max_ids <= 0) fail("qsa_attend: max_ids must be positive"); // THE SHARED SIZE IS THE CAPACITY. Shared memory is part of the LAUNCH CONFIGURATION, so sizing it from // this token's `n_ids` bakes the sequence length in: a captured layer would allocate room for token 1 and // then index past it at token 500. The kernel reads the real count from `step`, so a larger allocation is // exactly what it wants. The opt-in therefore happens once, for the capacity. const size_t smem = (size_t) (max_ids + 32) * sizeof(float); // per DEVICE: the opt-in is a device setting (a layer split runs this on two cards) static size_t s_configured_dev[64] = {}; int cur_dev = 0; cudaGetDevice(&cur_dev); size_t& s_configured = s_configured_dev[(cur_dev >= 0 && cur_dev < 64) ? cur_dev : 0]; if (smem > s_configured) { int dev = 0, max_shared = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&max_shared, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev); max_shared = strata::smem_optin_of(max_shared); if ((int) smem > max_shared) { std::fprintf(stderr, "qsa: qsa_attend: max_ids %lld needs %zu B of shared, over the %d B limit\n", (long long) max_ids, smem, max_shared); std::exit(1); } const cudaError_t e = cudaFuncSetAttribute(qsa_attend_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); if (e != cudaSuccess) { std::fprintf(stderr, "qsa: qsa_attend: shared opt-in: %s\n", cudaGetErrorString(e)); std::exit(1); } s_configured = smem; } qsa_attend_kernel<<<(unsigned) s.n_head, (unsigned) s.head_dim, smem, (cudaStream_t) stream>>>( q, k_scratch, v_scratch, step, (int) s.n_head, (int) s.n_head_kv, (int) s.head_dim, attn, weights); check_launch("qsa_attend"); if (stream == nullptr) check_sync("qsa_attend"); } // ================= host entry points ================= void qsa_step_fill(int32_t* host_step, int64_t pos, const QsaShapes& s) { if (host_step == nullptr) return; if (pos < 0) fail("qsa_step_fill: pos < 0"); // ONE PLACE COMPUTES ALL FOUR, which is the whole reason the step state is a BUFFER rather than four // separate parameters. `n_kv`, `n_bid` and `width` are DERIVED from `pos`, so a caller filling them in // itself could fill them inconsistently - and `qsa_index`'s host guard against exactly that inconsistency // now has a single writer to check against instead of two independent arguments. // // This is the form the LAYER will use: every value a QSA kernel needs derives from one position, so one // H2D per token updates all of them and no entry point takes a per-token scalar. const int64_t n_kv = pos + 1; host_step[kStepPos] = (int32_t) pos; host_step[kStepNKv] = (int32_t) n_kv; host_step[kStepNBid] = (int32_t) (n_kv / s.idx_block); host_step[kStepWidth] = (int32_t) qsa_selection_width(n_kv, s); } void kv_append(uint16_t* k_pool, uint16_t* v_pool, const int32_t* page_table, int64_t pos, const float* kcur, const float* vcur, const QsaShapes& s, void* stream) { if (pos < 0) { validate(s, "kv_append"); fail("kv_append: pos < 0"); } kv_append_step(k_pool, v_pool, page_table, step_upload(pos, -1, s), kcur, vcur, s, stream); } void indexer_key_append(const float* raw, const int32_t* pos_dev, int32_t pos_base, const float* w_k_norm, float eps, const QsaIndexerBuffers& b, const QsaShapes& s, const float* cos_tab, const float* sin_tab, void* stream) { validate(s, "indexer_key_append"); if (pos_dev == nullptr) fail("indexer_key_append: pos_dev is null"); if (b.tail == nullptr || b.dead == nullptr || b.pooled == nullptr || b.block_pos == nullptr) fail("indexer_key_append: the indexer buffers are not all set (tail/dead/pooled/block_pos)"); const int threads = (int) s.idx_dim; const size_t smem = (size_t) s.idx_dim * sizeof(double); // **ONE LAUNCH, NO HOST BRANCH ON THE POSITION.** The completion rotation is inside the kernel now. The // arguments here are identical for every token, which is the property a CUDA graph needs: this function can // be captured and replayed, and the position arrives through `pos_dev` like every other kernel's data. indexer_key_append_kernel<<<1, threads, smem, (cudaStream_t) stream>>>( raw, pos_dev, (int) pos_base, w_k_norm, eps, b.tail, b.dead, b.pooled, b.block_pos, (int) s.idx_dim, (int) s.idx_block, (int) s.n_rot, cos_tab, sin_tab, mrope_table()); check_launch("indexer_key_append"); if (stream == nullptr) check_sync("indexer_key_append"); } void qsa_index(const float* pooled, int64_t n_bid, const float* q_idx, const float* bias, const QsaShapes& s, int64_t n_kv, float* cell_scores, void* stream) { validate(s, "qsa_index"); if (n_bid < 0 || n_kv <= 0) fail("qsa_index: n_bid < 0 or n_kv <= 0"); // `n_kv`, `n_bid` and `width` are DERIVED from one position, so this refuses a caller whose two arguments // disagree rather than launching a kernel that would score the wrong number of blocks. if ((n_kv / s.idx_block) != n_bid) { std::fprintf(stderr, "qsa: qsa_index: n_bid %lld is not n_kv %lld / r %lld\n", (long long) n_bid, (long long) n_kv, (long long) s.idx_block); std::exit(1); } // THIS TOKEN'S counts as the CAPACITIES: correct for a direct launch, WRONG in a graph. The layer passes a // constant `max_blocks` from its state instead - see the note in `qsa.hpp`. qsa_index_step(pooled, q_idx, bias, s, step_upload(n_kv - 1, n_kv, s), n_bid + 1, cell_scores, stream); } void topk_512(const float* cell_scores, int64_t n_kv, const QsaShapes& s, int64_t cap, int32_t* ids, void* stream) { validate(s, "topk_512"); if (n_kv <= 0) return; if (n_kv > kTopkMaxCells) { std::fprintf(stderr, "qsa: topk_512: n_kv %lld > kTopkMaxCells %lld (one block; phase 3 replaces this)\n", (long long) n_kv, (long long) kTopkMaxCells); std::exit(1); } topk_512_step(cell_scores, s, cap, step_upload(n_kv - 1, n_kv, s), ids, stream); } void kv_gather(const uint16_t* k_pool, const uint16_t* v_pool, const int32_t* page_table, const int32_t* ids, int64_t n_ids, const QsaShapes& s, uint16_t* k_scratch, uint16_t* v_scratch, void* stream) { validate(s, "kv_gather"); if (n_ids <= 0) return; kv_gather_step(k_pool, v_pool, page_table, ids, step_upload_width(n_ids, s), n_ids, s, k_scratch, v_scratch, stream); } void qsa_attend(const float* q, const uint16_t* k_scratch, const uint16_t* v_scratch, int64_t n_ids, const QsaShapes& s, float* attn, float* weights, void* stream) { validate(s, "qsa_attend"); if (n_ids < 0) fail("qsa_attend: n_ids < 0"); if (n_ids == 0) { // The empty selection goes through the kernel's own zero path; `max_ids` must still be positive, so the // wrapper gives it the geometry's capacity rather than 0. qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(0, s), qsa_selection_width(kTopkMaxCells, s), s, attn, weights, stream); return; } qsa_attend_step(q, k_scratch, v_scratch, step_upload_width(n_ids, s), n_ids, s, attn, weights, stream); } /// The same multiply as `qsa_gate_apply_kernel` WITHOUT the fp16 round - see the header for why the caller /// whose weight is a K-quant needs the f32 form. Identical arithmetic up to the last step. __global__ void qsa_gate_apply_f32_kernel(const float* __restrict__ attn, const float* __restrict__ q_full, int n_head, int head_dim, float* __restrict__ out) { const long long i = blockIdx.x * (long long) blockDim.x + threadIdx.x; if (i >= (long long) n_head * head_dim) return; const int h = (int) (i / head_dim), d = (int) (i % head_dim); const double g = (double) q_full[((size_t) h * 2 * head_dim) + head_dim + d]; // the SECOND half const double sig = 1.0 / (1.0 + exp(-g)); out[i] = (float) ((double) attn[i] * sig); } void qsa_gate_apply_f32(const float* attn, const float* q_full, const QsaShapes& s, float* out, void* stream) { validate(s, "qsa_gate_apply_f32"); const long long n = s.n_head * s.head_dim; qsa_gate_apply_f32_kernel<<>>(attn, q_full, (int) s.n_head, (int) s.head_dim, out); check_launch("qsa_gate_apply_f32"); if (stream == nullptr) check_sync("qsa_gate_apply_f32"); } void qsa_gate_apply(const float* attn, const float* q_full, const QsaShapes& s, uint16_t* out, void* stream) { validate(s, "qsa_gate_apply"); const long long n = s.n_head * s.head_dim; qsa_gate_apply_kernel<<>>(attn, q_full, (int) s.n_head, (int) s.head_dim, out); check_launch("qsa_gate_apply"); if (stream == nullptr) check_sync("qsa_gate_apply"); } } // namespace strata::kernels