okami.mom/strata

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

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
69.4 KiB1299 linesraw
1// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp.
2#include "strata/kernels/qsa_decode_attn.hpp"
3#include "strata/core/sm75_series.hpp"
4#include "strata/core/sm120_series.hpp"
5#include "strata/core/geometry.hpp"
6#include "strata/kernels/kv_q8.hpp"
7#include "strata/kernels/kv_q4.hpp"
8#if defined(STRATA_HIP_GFX906)
9#include "strata/kernels/gfx_arch.hpp"
10#endif
11
12#include <cuda_fp16.h>
13#include <cuda_runtime.h>
14
15#include <cfloat>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19
20namespace strata::kernels {
21namespace {
22
23constexpr int HD = 256;          // head_dim
24constexpr int G = strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv;   // query heads per KV head (12 for Flash-Next; 1..16, a multiple of 4)
25static_assert(G % 4 == 0 && G <= 16, "qsa_decode_attn: query heads per KV head must be 4, 8, 12 or 16 (float4 probability rows, the 16-lane score reduce)");
26static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_decode_attn is compiled for core/geometry.hpp");
27constexpr int CHUNK = 64;        // cells per block
28constexpr int THREADS = 256;
29constexpr int WARPS = THREADS / 32;
30
31__device__ __forceinline__ float warp_sum(float v) {
32#pragma unroll
33    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
34    return v;
35}
36__device__ __forceinline__ float warp_max(float v) {
37#pragma unroll
38    for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o));
39    return v;
40}
41
42// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8).
43// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side.
44__device__ __forceinline__ void load8_f16(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
45    const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0;
46    const uint4 raw = *reinterpret_cast<const uint4*>(base);
47    const __half2* h2 = reinterpret_cast<const __half2*>(&raw);
48#pragma unroll
49    for (int j = 0; j < 4; ++j) {
50        const float2 f = __half22float2(h2[j]);
51        out[2 * j] = f.x;
52        out[2 * j + 1] = f.y;
53    }
54}
55__device__ __forceinline__ void load8_q8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
56    const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0;
57    const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP];
58    const float sc = __half2float(__ushort_as_half(sbits));
59    const uint2 raw = *reinterpret_cast<const uint2*>(codes);
60    const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
61#pragma unroll
62    for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc;
63}
64__device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
65    constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
66    const int b = d0 / QK4_0;
67    const int rem = d0 % QK4_0;
68    const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b;
69    const float d = __half2float(__ushort_as_half(blk->d));
70    const int j = (rem == 0 || rem == 16) ? 0 : 8;
71    const uint8_t* bytes = blk->qs + j;
72    if (rem < 16) {
73#pragma unroll
74        for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d;
75    } else {
76#pragma unroll
77        for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d;
78    }
79}
80template <int KV_MODE>
81__device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) {
82    if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
83    else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out);
84    else if constexpr (KV_MODE == 3) {
85        // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
86        // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
87        if (value) load8_q4(p, value, row, d0, out);
88        else load8_q8(p, value, row, d0, out);
89    } else load8_q4(p, value, row, d0, out);
90}
91
92// One cell's G probabilities (G/4 broadcast float4 loads) into the G accumulators: every accumulator takes one fmaf,
93// so the sums are the per-head loop's, bit for bit, for any G.
94template <int GG> __device__ __forceinline__ void fold_cell(float (&acc)[GG], const float* w, float v) {
95    const float4* w4 = reinterpret_cast<const float4*>(w);
96    if constexpr (GG == 12) {   // Flash-Next: the expressions this replaced, so its device code is unchanged
97        const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];
98        acc[0] = fmaf(w0.x, v, acc[0]);  acc[1] = fmaf(w0.y, v, acc[1]);
99        acc[2] = fmaf(w0.z, v, acc[2]);  acc[3] = fmaf(w0.w, v, acc[3]);
100        acc[4] = fmaf(w1.x, v, acc[4]);  acc[5] = fmaf(w1.y, v, acc[5]);
101        acc[6] = fmaf(w1.z, v, acc[6]);  acc[7] = fmaf(w1.w, v, acc[7]);
102        acc[8] = fmaf(w2.x, v, acc[8]);  acc[9] = fmaf(w2.y, v, acc[9]);
103        acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);
104        return;
105    }
106#pragma unroll
107    for (int i = 0; i < GG / 4; ++i) {
108        const float4 x = w4[i];
109        acc[4 * i + 0] = fmaf(x.x, v, acc[4 * i + 0]);
110        acc[4 * i + 1] = fmaf(x.y, v, acc[4 * i + 1]);
111        acc[4 * i + 2] = fmaf(x.z, v, acc[4 * i + 2]);
112        acc[4 * i + 3] = fmaf(x.w, v, acc[4 * i + 3]);
113    }
114}
115
116// the q8_v3 kernel's value loop: Flash-Next (12 heads per KV head) keeps the expressions this kernel always had (its device code is
117// unchanged); any other G folds the cell with fold_cell.  A template, so the branch not taken is not instantiated (G is not 12 in a
118// non-Flash-Next build, and the 12-element initialiser below would not compile).
119template <int GG> __device__ __forceinline__ void fold_cell_v3(float (&acc)[GG], const float* w, float v) {
120    if constexpr (GG == 12) {
121        const float4 p0 = *reinterpret_cast<const float4*>(&w[0]);
122        const float4 p1 = *reinterpret_cast<const float4*>(&w[4]);
123        const float4 p2 = *reinterpret_cast<const float4*>(&w[8]);
124        const float pr[GG] = {p0.x, p0.y, p0.z, p0.w, p1.x, p1.y, p1.z, p1.w, p2.x, p2.y, p2.z, p2.w};
125#pragma unroll
126        for (int h = 0; h < GG; ++h) acc[h] = fmaf(pr[h], v, acc[h]);
127    } else {
128        fold_cell<GG>(acc, w, v);
129    }
130}
131
132
133// Exact-intent score reduce-scatter: the same butterfly pairs as twelve warp_sum calls,
134// with 16 shuffle exchanges instead of 60. Used only by the opt-in gfx906 INT8
135// query-swizzled specialization; softmax, value accumulation and merge are unchanged.
136__device__ __forceinline__ float reduce12_gfx906(const float (&part)[16], int lane) {
137    float r8[8];
138#pragma unroll
139    for (int i = 0; i < 8; ++i) {
140        const bool hi = (lane & 16) != 0;
141        r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16);
142    }
143    float r4[4];
144#pragma unroll
145    for (int i = 0; i < 4; ++i) {
146        const bool hi = (lane & 8) != 0;
147        r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8);
148    }
149    float r2[2];
150#pragma unroll
151    for (int i = 0; i < 2; ++i) {
152        const bool hi = (lane & 4) != 0;
153        r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4);
154    }
155    const bool hi2 = (lane & 2) != 0;
156    const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2);
157    return r1 + __shfl_xor_sync(0xffffffffu, r1, 1);
158}
159__device__ __forceinline__ int reduce12_head_of_lane(int lane) {
160    return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
161}
162
163// The chunk kernel's body; `p` is the query's KV pools (the call's one set, or blockIdx.z's slot's set).
164// (the body is a device function so the batch window's rows kernel below can run it over each query's own pools without
165// the default kernel's signature, or the function-pointer types the pre-sm_75 / HIP selections build, changing)
166template <int KV_MODE, bool LANE_CELL, bool QUERY_SWIZZLE, bool REDUCE12>
167__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p,
168                                                const int32_t* __restrict__ ids, const int32_t* __restrict__ step,
169                                                int n_kv_heads, int page_size, float scale,
170                                                float* __restrict__ part_acc, float* __restrict__ part_m,
171                                                float* __restrict__ part_l, int n_chunks, int cap,
172                                                long long scratch_stride) {
173    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
174    q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
175    ids += (size_t) blockIdx.z * (size_t) cap;
176    step += (size_t) blockIdx.z * kStepCount;
177    part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
178    part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
179    part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
180    __shared__ __align__(16) float sq[G][HD];     // 12 KB: this KV head's query heads
181    __shared__ float sp[G][CHUNK];                // scores, then probabilities
182    __shared__ long long srow[CHUNK];             // pool row of each cell (page, kv head, slot)
183    const int n_ids = __ldg(step + kStepWidth);
184    const int chunk = blockIdx.x, kvh = blockIdx.y;
185    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
186    const int c0 = chunk * CHUNK;
187    const int n_here = min(CHUNK, n_ids - c0);
188    const int slot = kvh * n_chunks + chunk;
189    if (n_here <= 0) {
190        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
191        return;
192    }
193    // Opt-in gfx906 batched attention: a bijective XOR of query dimensions in LDS only. It swaps the two
194    // float4 halves of lanes whose bit 2 is set, retaining 16-byte alignment and the 12 KB tile.
195    // The scoring reads undo this permutation; FP operands and operation order are unchanged.
196    static_assert(!QUERY_SWIZZLE || !LANE_CELL, "query swizzle is for warp scoring only");
197    for (int i = t; i < G * HD; i += THREADS) {
198        const int d = i % HD;
199        const int sd = QUERY_SWIZZLE ? (d ^ ((d >> 3) & 4)) : d;
200        sq[i / HD][sd] = q[(size_t) (kvh * G) * HD + i];
201    }
202    if (t < CHUNK) {
203        long long r = -1;
204        if (t < n_here) {
205            const int cell = ids[c0 + t];
206            const long long page = (long long) p.page_table[cell / page_size];
207            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
208            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
209            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
210        }
211        srow[t] = r;
212    }
213    __syncthreads();
214    if constexpr (LANE_CELL) {
215        // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same
216        // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as
217        // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle
218        // reductions per cell
219        constexpr int HPT = G * CHUNK / THREADS;   // heads per thread (3)
220        const int c = t % CHUNK, h0 = (t / CHUNK) * HPT;
221        if (c >= n_here || srow[c] < 0) {
222#pragma unroll
223            for (int j = 0; j < HPT; ++j) sp[h0 + j][c] = -FLT_MAX;
224        } else {
225            float a[HPT][32];
226#pragma unroll
227            for (int l = 0; l < 32; ++l) {
228                float k8[8];
229                load8<KV_MODE>(p, false, srow[c], l * 8, k8);
230#pragma unroll
231                for (int j = 0; j < HPT; ++j) {
232                    const float4 qa = *reinterpret_cast<const float4*>(&sq[h0 + j][l * 8]);
233                    const float4 qb = *reinterpret_cast<const float4*>(&sq[h0 + j][l * 8 + 4]);
234                    float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
235                              k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
236                    a[j][l] = s;
237                }
238            }
239#pragma unroll
240            for (int j = 0; j < HPT; ++j) {
241#pragma unroll
242                for (int o = 16; o > 0; o >>= 1)
243#pragma unroll
244                    for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o];
245                sp[h0 + j][c] = a[j][0] * scale;
246            }
247        }
248    } else
249    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
250    for (int c = warp; c < CHUNK; c += WARPS) {
251        if (c >= n_here || srow[c] < 0) {
252            if (lane < G) sp[lane][c] = -FLT_MAX;
253            continue;
254        }
255        if constexpr (REDUCE12) {
256        float k8[8];
257        load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
258        float part[16];
259#pragma unroll
260        for (int h = 0; h < G; ++h) {
261            const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0;
262            const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + qflip]);
263            const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + (qflip ^ 4)]);
264            float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
265                      k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
266            part[h] = s;
267        }
268#pragma unroll
269        for (int h = G; h < 16; ++h) part[h] = 0.0f;
270        const float score = reduce12_gfx906(part, lane);
271        const int head = reduce12_head_of_lane(lane);
272        if ((lane & 1) == 0 && head < G) sp[head][c] = score * scale;
273        } else {
274        float k8[8];
275        load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
276#pragma unroll
277        for (int h = 0; h < G; ++h) {
278            const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0;
279            const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + qflip]);
280            const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + (qflip ^ 4)]);
281            float s = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
282                      k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
283            s = warp_sum(s);
284            if (lane == 0) sp[h][c] = s * scale;
285        }
286        }
287    }
288    __syncthreads();
289    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
290    for (int h = warp; h < G; h += WARPS) {
291        const float a = sp[h][lane], b = sp[h][lane + 32];
292        const float m = warp_max(fmaxf(a, b));
293        const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
294        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
295        sp[h][lane] = ea;
296        sp[h][lane + 32] = eb;
297        const float l = warp_sum(ea + eb);
298        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
299    }
300    __syncthreads();
301    // values: thread t owns dimension t for all 12 heads.
302    float acc[G];
303#pragma unroll
304    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
305    for (int c = 0; c < n_here; ++c) {
306        if (srow[c] < 0) continue;   // masked above, weight 0
307        float v;
308        if constexpr (KV_MODE == 0) {
309            v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
310        } else if constexpr (KV_MODE == 1) {
311            const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
312            v = (float) p.v_q[srow[c] * HD + t] * sc;
313        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
314            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
315            const int b = t / QK4_0;
316            const int rem = t % QK4_0;
317            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
318            const float d = __half2float(__ushort_as_half(blk->d));
319            const int j = rem < 16 ? rem : (rem - 16);
320            const uint8_t byte = blk->qs[j];
321            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
322            v = (float) nibble * d;
323        }
324#pragma unroll
325        for (int h = 0; h < G; ++h) acc[h] = fmaf(sp[h][c], v, acc[h]);
326    }
327#pragma unroll
328    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
329}
330
331template <int KV_MODE, bool LANE_CELL = false, bool QUERY_SWIZZLE = false, bool REDUCE12 = false>
332__global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __restrict__ q, QsaAttnPools p,
333                                                             const int32_t* __restrict__ ids,
334                                                             const int32_t* __restrict__ step, int n_kv_heads,
335                                                             int page_size, float scale, float* __restrict__ part_acc,
336                                                             float* __restrict__ part_m, float* __restrict__ part_l,
337                                                             int n_chunks, int cap = 0, long long scratch_stride = 0) {
338    attn_chunk_body<KV_MODE, LANE_CELL, QUERY_SWIZZLE, REDUCE12>(q, p, ids, step, n_kv_heads, page_size, scale,
339                                                                 part_acc, part_m, part_l, n_chunks, cap,
340                                                                 scratch_stride);
341}
342
343// The same blocks for queries of different slots: query blockIdx.z reads its own slot's pools, everything else is
344// attn_chunk_kernel's batched form (qsa_decode_attn_slots).
345template <int KV_MODE, bool LANE_CELL>
346__global__ void __launch_bounds__(THREADS) attn_chunk_slots_kernel(const float* __restrict__ q, QsaAttnSlotPools ps,
347                                                                   const int32_t* __restrict__ ids,
348                                                                   const int32_t* __restrict__ step, int n_kv_heads,
349                                                                   int page_size, float scale,
350                                                                   float* __restrict__ part_acc,
351                                                                   float* __restrict__ part_m,
352                                                                   float* __restrict__ part_l, int n_chunks, int cap,
353                                                                   long long scratch_stride) {
354    attn_chunk_body<KV_MODE, LANE_CELL, false, false>(q, ps.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale,
355                                                      part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
356}
357
358// Batch windows: query blockIdx.z attends over its own slot's pools (rows.p[z]); the default kernel otherwise.
359template <int KV_MODE>
360__global__ void __launch_bounds__(THREADS) attn_chunk_rows_kernel(const float* __restrict__ q, QsaAttnPoolsRows rows,
361                                                                  const int32_t* __restrict__ ids,
362                                                                  const int32_t* __restrict__ step, int n_kv_heads,
363                                                                  int page_size, float scale,
364                                                                  float* __restrict__ part_acc,
365                                                                  float* __restrict__ part_m,
366                                                                  float* __restrict__ part_l, int n_chunks, int cap,
367                                                                  long long scratch_stride) {
368    attn_chunk_body<KV_MODE, false, false, false>(q, rows.p[blockIdx.z], ids, step, n_kv_heads, page_size, scale,
369                                                  part_acc, part_m, part_l, n_chunks, cap, scratch_stride);
370}
371
372#if !defined(__HIPCC__)
373// Turing (INT8 pools): attn_chunk_kernel<1> bit for bit, rearranged for the SM's shared-memory pipe, which the
374// default kernel saturates (its time grew with the queries even with the SMs half empty).  Three changes, none to an
375// operand or the order of an operation:
376//   - the lane's slice of the 12 query heads (8 dimensions each) is read from shared memory once, into registers,
377//     instead of two 16-byte reads per head per cell (with a two-way bank conflict at lane * 8);
378//   - the 12 heads' lane sums are reduced with reduce12_gfx906 (16 shuffles, each sum warp_sum's pairs) instead of
379//     12 warp_sums (60 shuffles);
380//   - the probabilities are stored cell-major, so the value loop reads a cell's 12 as three 16-byte broadcasts.
381// RTX 2080 Ti, 2051 selected cells: 1 / 2 / 3 / 4 queries 51.6 / 78.5 / 110 / 146 -> 34.5 / 41.0 / 73.0 / 84.9 us
382// (with the merge); 600 cells 45.9 / 74.6 / 105 / 137 -> 28.6 / 32.8 / 33.5 / 33.3 us.  STRATA_ATTN_V3=0 keeps the
383// default kernel; =1 takes this one on any CUDA card.
384__global__ void __launch_bounds__(THREADS) attn_chunk_q8_v3_kernel(const float* __restrict__ q, QsaAttnPools p,
385                                                                   const int32_t* __restrict__ ids,
386                                                                   const int32_t* __restrict__ step, int n_kv_heads,
387                                                                   int page_size, float scale, float* __restrict__ part_acc,
388                                                                   float* __restrict__ part_m, float* __restrict__ part_l,
389                                                                   int n_chunks, int cap = 0, long long scratch_stride = 0) {
390    q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
391    ids += (size_t) blockIdx.z * (size_t) cap;
392    step += (size_t) blockIdx.z * kStepCount;
393    part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
394    part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
395    part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
396    __shared__ __align__(16) float sq[G][HD];
397    __shared__ __align__(16) float spt[CHUNK][G];   // cell-major: one cell's 12 heads are 3 float4
398    __shared__ long long srow[CHUNK];
399    const int n_ids = __ldg(step + kStepWidth);
400    const int chunk = blockIdx.x, kvh = blockIdx.y;
401    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
402    const int c0 = chunk * CHUNK;
403    const int n_here = min(CHUNK, n_ids - c0);
404    const int slot = kvh * n_chunks + chunk;
405    if (n_here <= 0) {
406        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
407        return;
408    }
409    // stored with the gfx906 swizzle (the two float4 halves of lanes with bit 2 swapped): fewer conflicts on the one read
410    for (int i = t; i < G * HD; i += THREADS) {
411        const int d = i % HD;
412        sq[i / HD][d ^ ((d >> 3) & 4)] = q[(size_t) (kvh * G) * HD + i];
413    }
414    if (t < CHUNK) {
415        long long r = -1;
416        if (t < n_here) {
417            const int cell = ids[c0 + t];
418            const long long page = (long long) p.page_table[cell / page_size];
419            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
420        }
421        srow[t] = r;
422    }
423    __syncthreads();
424    float qr[G][8];
425#pragma unroll
426    for (int h = 0; h < G; ++h) {
427        const int qflip = lane & 4;
428        const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + qflip]);
429        const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + (qflip ^ 4)]);
430        qr[h][0] = qa.x; qr[h][1] = qa.y; qr[h][2] = qa.z; qr[h][3] = qa.w;
431        qr[h][4] = qb.x; qr[h][5] = qb.y; qr[h][6] = qb.z; qr[h][7] = qb.w;
432    }
433    for (int c = warp; c < CHUNK; c += WARPS) {
434        if (c >= n_here || srow[c] < 0) {
435            if (lane < G) spt[c][lane] = -FLT_MAX;
436            continue;
437        }
438        float k8[8];
439        load8<1>(p, false, srow[c], lane * 8, k8);
440        float part[16];
441#pragma unroll
442        for (int h = 0; h < G; ++h)
443            part[h] = k8[0] * qr[h][0] + k8[1] * qr[h][1] + k8[2] * qr[h][2] + k8[3] * qr[h][3] +
444                      k8[4] * qr[h][4] + k8[5] * qr[h][5] + k8[6] * qr[h][6] + k8[7] * qr[h][7];
445#pragma unroll
446        for (int h = G; h < 16; ++h) part[h] = 0.0f;
447        const float score = reduce12_gfx906(part, lane);
448        const int head = reduce12_head_of_lane(lane);
449        if ((lane & 1) == 0 && head < G) spt[c][head] = score * scale;
450    }
451    __syncthreads();
452    for (int h = warp; h < G; h += WARPS) {
453        const float a = spt[lane][h], b = spt[lane + 32][h];
454        const float m = warp_max(fmaxf(a, b));
455        const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
456        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
457        spt[lane][h] = ea;
458        spt[lane + 32][h] = eb;
459        const float l = warp_sum(ea + eb);
460        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
461    }
462    __syncthreads();
463    float acc[G];
464#pragma unroll
465    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
466    for (int c = 0; c < n_here; ++c) {
467        if (srow[c] < 0) continue;   // masked above, weight 0
468        const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]));
469        const float v = (float) p.v_q[srow[c] * HD + t] * sc;
470        fold_cell_v3<G>(acc, &spt[c][0], v);
471    }
472#pragma unroll
473    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
474}
475bool attn_v3_on() {
476    static int on[16] = {};   // by device ordinal: 0 unknown, 1 yes, -1 no
477    static const int env = [] { const char* v = std::getenv("STRATA_ATTN_V3"); return v ? (v[0] == '0' ? 0 : 1) : -1; }();
478    if (env >= 0) return env == 1;
479    int dev = 0;
480    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false;
481    if (on[dev] == 0) {
482        int maj = 0, mnr = 0;
483        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
484                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
485        if (!ok) cudaGetLastError();
486        on[dev] = ok && strata::sm75_default(maj, mnr) ? 1 : -1;   // Turing only, with STRATA_SM75_PERF=1
487    }
488    return on[dev] > 0;
489}
490#endif
491
492// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
493// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk.  It
494// uses more registers (80 vs 38 on sm_70), so on CUDA it runs on cards below sm_75 only, and exists only in the
495// experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON).  HIP: built for wave32 cards (not the gfx906 wave64 backend) and
496// run on gfx103x (RDNA2), with 8 cells per step and the butterfly's lane exchanges in registers (DPP / permlanex16)
497// instead of ds_bpermute: there the score loop is bound by the LDS pipe (the q reads and ds_bpermute share it), not by
498// occupancy - 8 cells per step at 7 waves/SIMD beat 1 cell at 9.  Every other card keeps exactly the kernel above.
499// Fork (lab/upsync): built on every CUDA build too, for STRATA_ATTN_DAILY=1 (see daily_attn below).  With NC 2 and
500// no DPP it is the Daily's (be4cf1c) attn_chunk_kernel line for line - the same reduce12 scores, the same cell-major
501// probabilities and the same four-cell value fold - except that `spt` shares `sq`'s storage here (no arithmetic
502// change).  Without the variable nothing selects it on a card at or above sm_75.
503#if defined(STRATA_EXPERIMENTAL_SM60) || !defined(__HIPCC__) || !defined(STRATA_HIP_GFX906)
504#define STRATA_ATTN_PRE75_BUILT 1
505#endif
506#if defined(STRATA_ATTN_PRE75_BUILT)
507// A butterfly step's lane exchange, `M` = 1, 2, 4, 8 or 16.  DPP (HIP, wave32): in registers - DPP row_xmask within a
508// 16-lane row, v_permlanex16 across the two rows - instead of ds_bpermute; the same value moves, so every sum is
509// unchanged bit for bit.
510template <bool DPP, int M> __device__ __forceinline__ float shfl_x(float v) {
511#if defined(__HIPCC__)
512    if constexpr (DPP) {
513        const int x = __float_as_int(v);
514        if constexpr (M == 16) return __int_as_float(__builtin_amdgcn_permlanex16(x, x, 0x76543210, 0xfedcba98, false, false));
515        else return __int_as_float(__builtin_amdgcn_mov_dpp(x, 0x160 | M, 0xF, 0xF, false));   // row_xmask:M
516    }
517#endif
518    return __shfl_xor_sync(0xffffffffu, v, M);
519}
520// warp_sum / warp_max with the same pairing order (xor 16, 8, 4, 2, 1)
521template <bool DPP> __device__ __forceinline__ float warp_sum_x(float v) {
522    v += shfl_x<DPP, 16>(v); v += shfl_x<DPP, 8>(v); v += shfl_x<DPP, 4>(v); v += shfl_x<DPP, 2>(v); v += shfl_x<DPP, 1>(v);
523    return v;
524}
525template <bool DPP> __device__ __forceinline__ float warp_max_x(float v) {
526    v = fmaxf(v, shfl_x<DPP, 16>(v)); v = fmaxf(v, shfl_x<DPP, 8>(v)); v = fmaxf(v, shfl_x<DPP, 4>(v));
527    v = fmaxf(v, shfl_x<DPP, 2>(v)); v = fmaxf(v, shfl_x<DPP, 1>(v));
528    return v;
529}
530// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1):
531// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes),
532// for 16 shuffles instead of 12 x 5.  Lane l ends holding head head_of_lane(l); lanes l and l^1 agree.
533template <bool DPP> __device__ __forceinline__ float reduce12(const float (&part)[16], int lane) {
534    float r8[8];
535#pragma unroll
536    for (int i = 0; i < 8; ++i) {
537        const bool hi = (lane & 16) != 0;
538        r8[i] = (hi ? part[i + 8] : part[i]) + shfl_x<DPP, 16>(hi ? part[i] : part[i + 8]);
539    }
540    float r4[4];
541#pragma unroll
542    for (int i = 0; i < 4; ++i) {
543        const bool hi = (lane & 8) != 0;
544        r4[i] = (hi ? r8[i + 4] : r8[i]) + shfl_x<DPP, 8>(hi ? r8[i] : r8[i + 4]);
545    }
546    float r2[2];
547#pragma unroll
548    for (int i = 0; i < 2; ++i) {
549        const bool hi = (lane & 4) != 0;
550        r2[i] = (hi ? r4[i + 2] : r4[i]) + shfl_x<DPP, 4>(hi ? r4[i] : r4[i + 2]);
551    }
552    const bool hi2 = (lane & 2) != 0;
553    const float r1 = (hi2 ? r2[1] : r2[0]) + shfl_x<DPP, 2>(hi2 ? r2[0] : r2[1]);
554    return r1 + shfl_x<DPP, 1>(r1);
555}
556__device__ __forceinline__ int head_of_lane(int lane) {
557    return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
558}
559
560// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format.
561template <int KV_MODE>
562__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) {
563    if constexpr (KV_MODE == 0) {
564        return __half2float(__ushort_as_half(p.v_pool[row * HD + d]));
565    } else if constexpr (KV_MODE == 1) {
566        const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP]));
567        return (float) p.v_q[row * HD + d] * sc;
568    } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
569        constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
570        const int b = d / QK4_0;
571        const int rem = d % QK4_0;
572        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
573        const float dd = __half2float(__ushort_as_half(blk->d));
574        const int j = rem < 16 ? rem : (rem - 16);
575        const uint8_t byte = blk->qs[j];
576        const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
577        return (float) nibble * dd;
578    }
579}
580
581template <int KV_MODE, int NC_ = 2, bool DPP_ = false>
582__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* __restrict__ q, QsaAttnPools p,
583                                                             const int32_t* __restrict__ ids,
584                                                             const int32_t* __restrict__ step, int n_kv_heads,
585                                                             int page_size, float scale, float* __restrict__ part_acc,
586                                                             float* __restrict__ part_m, float* __restrict__ part_l,
587                                                             int n_chunks, int cap = 0, long long scratch_stride = 0) {
588    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
589    q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
590    ids += (size_t) blockIdx.z * (size_t) cap;
591    step += (size_t) blockIdx.z * kStepCount;
592    part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
593    part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
594    part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
595    __shared__ __align__(16) float sq[G][HD];     // 12 KB: this KV head's query heads (dead once the scores are done)
596    __shared__ float sp[G][CHUNK];                // scores
597    __shared__ long long srow[CHUNK];             // pool row of each cell (page, kv head, slot)
598    // probabilities, cell-major: the value loop reads one cell's 12 as three float4.  They are first written after the
599    // __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12
600    // floats) and the block's shared memory stays what it was before the cell-major layout.
601    float (*const spt)[G] = reinterpret_cast<float (*)[G]>(&sq[0][0]);
602    static_assert(CHUNK * G <= G * HD, "spt must fit in sq");
603    const int n_ids = __ldg(step + kStepWidth);
604    const int chunk = blockIdx.x, kvh = blockIdx.y;
605    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
606    const int c0 = chunk * CHUNK;
607    const int n_here = min(CHUNK, n_ids - c0);
608    const int slot = kvh * n_chunks + chunk;
609    if (n_here <= 0) {
610        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
611        return;
612    }
613    for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
614    if (t < CHUNK) {
615        long long r = -1;
616        if (t < n_here) {
617            const int cell = ids[c0 + t];
618            const long long page = (long long) p.page_table[cell / page_size];
619            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
620            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
621            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
622        }
623        srow[t] = r;
624    }
625    __syncthreads();
626    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.  NC cells per step
627    // (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts the traffic
628    // that bounds this phase (24 x 16 B per lane per cell, against the FMAs) by NC; every dot product is the same
629    // expression as for a single cell, so the scores are unchanged.
630    constexpr int NC = NC_;   // CUDA 2 (4 measured slower on a V100: the registers cost occupancy); HIP gfx103x 8
631    const int hd = head_of_lane(lane);
632    for (int i = 0; i < CHUNK / WARPS; i += NC) {
633        int cc[NC];
634        bool all_ok = true;
635#pragma unroll
636        for (int j = 0; j < NC; ++j) {
637            cc[j] = warp + WARPS * (i + j);
638            all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;
639        }
640        if (all_ok) {
641            float kk[NC][8];
642#pragma unroll
643            for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);
644            float pp[NC][16];
645#pragma unroll
646            for (int h = 0; h < G; ++h) {
647                const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
648                const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
649#pragma unroll
650                for (int j = 0; j < NC; ++j)
651                    pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w +
652                               kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;
653            }
654#pragma unroll
655            for (int j = 0; j < NC; ++j) {
656#pragma unroll
657                for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;
658                const float sj = reduce12<DPP_>(pp[j], lane);
659                if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;
660            }
661        } else {
662            for (int k = 0; k < NC; ++k) {   // a masked or out-of-range cell in the group: one cell at a time
663                const int c = cc[k];
664                if (c >= n_here || srow[c] < 0) {
665                    if (lane < G) sp[lane][c] = -FLT_MAX;
666                    continue;
667                }
668                float k8[8];
669                load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
670                float part[16];
671#pragma unroll
672                for (int h = 0; h < G; ++h) {
673                    const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
674                    const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
675                    part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
676                              k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
677                }
678#pragma unroll
679                for (int h = G; h < 16; ++h) part[h] = 0.0f;
680                const float s = reduce12<DPP_>(part, lane);
681                if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;
682            }
683        }
684    }
685    __syncthreads();
686    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
687    for (int h = warp; h < G; h += WARPS) {
688        const float a = sp[h][lane], b = sp[h][lane + 32];
689        const float m = warp_max_x<DPP_>(fmaxf(a, b));
690        const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
691        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
692        spt[lane][h] = ea;
693        spt[lane + 32][h] = eb;
694        const float l = warp_sum_x<DPP_>(ea + eb);
695        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
696    }
697    __syncthreads();
698    // values: thread t owns dimension t for all 12 heads.
699    float acc[G];
700#pragma unroll
701    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
702    // One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
703    // ascending order, so the sums are the plain loop's, bit for bit.
704    const auto fold = [&](int c, float v) {
705        fold_cell<G>(acc, spt[c], v);
706    };
707    int c = 0;
708    // four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
709    // a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.
710    for (; c + 4 <= n_here; c += 4) {
711        const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];
712        if ((r0 | r1 | r2 | r3) < 0) break;
713        const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);
714        const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);
715        fold(c, v0);
716        fold(c + 1, v1);
717        fold(c + 2, v2);
718        fold(c + 3, v3);
719    }
720    for (; c < n_here; ++c) {
721        if (srow[c] < 0) continue;   // masked above, weight 0
722        fold(c, load_v1<KV_MODE>(p, srow[c], t));
723    }
724#pragma unroll
725    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
726}
727#endif  // STRATA_ATTN_PRE75_BUILT
728
729__global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict__ part_acc,
730                                                        const float* __restrict__ part_m,
731                                                        const float* __restrict__ part_l, int n_chunks,
732                                                        float* __restrict__ attn, long long scratch_stride = 0) {
733    part_acc += (size_t) blockIdx.y * (size_t) scratch_stride;
734    part_m += (size_t) blockIdx.y * (size_t) scratch_stride;
735    part_l += (size_t) blockIdx.y * (size_t) scratch_stride;
736    attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD;
737    const int h = blockIdx.x;                 // global query head
738    const int kvh = h / G, hl = h % G;
739    const int d = threadIdx.x;
740    float M = -FLT_MAX;
741    for (int c = 0; c < n_chunks; ++c) M = fmaxf(M, part_m[(kvh * n_chunks + c) * G + hl]);
742    float L = 0.0f, acc = 0.0f;
743    for (int c = 0; c < n_chunks; ++c) {
744        const int slot = kvh * n_chunks + c;
745        const float m = part_m[slot * G + hl];
746        if (m == -FLT_MAX) continue;
747        const float w = __expf(m - M);
748        L = fmaf(part_l[slot * G + hl], w, L);
749        acc = fmaf(part_acc[((size_t) slot * G + hl) * HD + d], w, acc);
750    }
751    attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
752}
753
754// attn_merge_kernel's arithmetic in the same chunk order, with two changes that leave every output bit as it was
755// (the Daily's 3effa9d5, from Hardin22; qsa_merge_daily_parity compares the two kernels on the same partials, all four
756// KV formats):
757//
758// (1) Bounded by the width.  The chunk kernel writes m = -FLT_MAX, l = 0 for every chunk with c0 >= step[kStepWidth]
759//     (its `n_here <= 0` exit) and the merge skips exactly those, so it can stop at n_act = ceil(width / CHUNK):
760//     fmaxf with -FLT_MAX never changes M, and a skipped chunk never touches L or acc.  The drafter's merge walks its
761//     whole capacity (--mtp-window 32768: 512 chunks) at every context, where a short context fills one or two.
762// (2) Loads batched.  attn_merge_kernel loads part_l / part_acc behind its `m == -FLT_MAX` branch, so the compiler
763//     issues each chunk's l and acc loads inside that chunk's branch: a few dependent L2 round trips per chunk.  Here
764//     the m, l and acc of U chunks are loaded first, guarded only by the chunk index, then consumed in chunk order.
765//     The skip is a select on the loaded m instead of a branch, so the loads cannot move back behind it.  The values
766//     selected are the very fmaf's attn_merge_kernel computes (same operands, same order), and a skipped chunk leaves
767//     L and acc as they were, as its `continue` does.
768constexpr int kMergeU = 16;
769
770template <int U, bool TAIL>
771__device__ __forceinline__ void merge_max_block(const float* __restrict__ pm, int c0, int n_act, float& M) {
772    float mm[U];
773#pragma unroll
774    for (int u = 0; u < U; ++u) mm[u] = (!TAIL || c0 + u < n_act) ? pm[(size_t) (c0 + u) * G] : -FLT_MAX;
775#pragma unroll
776    for (int u = 0; u < U; ++u)
777        if (!TAIL || c0 + u < n_act) M = fmaxf(M, mm[u]);
778}
779
780template <int U, bool TAIL>
781__device__ __forceinline__ void merge_sum_block(const float* __restrict__ pm, const float* __restrict__ pl,
782                                                const float* __restrict__ pa, int c0, int n_act, float M, float& L,
783                                                float& acc) {
784    float mm[U], ll[U], aa[U];
785#pragma unroll
786    for (int u = 0; u < U; ++u) {
787        const bool in = !TAIL || c0 + u < n_act;
788        mm[u] = in ? pm[(size_t) (c0 + u) * G] : -FLT_MAX;
789        ll[u] = in ? pl[(size_t) (c0 + u) * G] : 0.0f;
790        aa[u] = in ? pa[(size_t) (c0 + u) * G * HD] : 0.0f;
791    }
792#pragma unroll
793    for (int u = 0; u < U; ++u) {
794        const float w = __expf(mm[u] - M);
795        const float L_next = fmaf(ll[u], w, L);
796        const float acc_next = fmaf(aa[u], w, acc);
797        const bool live = !(mm[u] == -FLT_MAX);   // attn_merge_kernel: `if (m == -FLT_MAX) continue;`
798        L = live ? L_next : L;
799        acc = live ? acc_next : acc;
800    }
801}
802
803template <int U>
804__global__ void __launch_bounds__(HD) attn_merge_v2_kernel(const float* __restrict__ part_acc,
805                                                           const float* __restrict__ part_m,
806                                                           const float* __restrict__ part_l, int n_chunks,
807                                                           const int32_t* __restrict__ steps,
808                                                           float* __restrict__ attn, long long scratch_stride = 0) {
809    part_acc += (size_t) blockIdx.y * (size_t) scratch_stride;
810    part_m += (size_t) blockIdx.y * (size_t) scratch_stride;
811    part_l += (size_t) blockIdx.y * (size_t) scratch_stride;
812    attn += (size_t) blockIdx.y * (size_t) gridDim.x * HD;
813    // the step record the chunk kernel read for this query (attn_chunk_kernel: step + blockIdx.z * kStepCount)
814    const int width = __ldg(steps + (size_t) blockIdx.y * kStepCount + kStepWidth);
815    const int n_act = width > 0 ? min(n_chunks, (width - 1) / CHUNK + 1) : 0;
816    const int h = blockIdx.x;                 // global query head
817    const int kvh = h / G, hl = h % G;
818    const int d = threadIdx.x;
819    // chunk c of this head: part_m / part_l [(kvh * n_chunks + c) * G + hl], part_acc [that * HD + d]
820    const size_t base = (size_t) kvh * (size_t) n_chunks * G + (size_t) hl;
821    const float* pm = part_m + base;
822    const float* pl = part_l + base;
823    const float* pa = part_acc + base * HD + (size_t) d;
824    const int n_full = n_act - n_act % U;
825    float M = -FLT_MAX;
826    for (int c0 = 0; c0 < n_full; c0 += U) merge_max_block<U, false>(pm, c0, n_act, M);
827    if (n_full < n_act) merge_max_block<U, true>(pm, n_full, n_act, M);
828    float L = 0.0f, acc = 0.0f;
829    for (int c0 = 0; c0 < n_full; c0 += U) merge_sum_block<U, false>(pm, pl, pa, c0, n_act, M, L, acc);
830    if (n_full < n_act) merge_sum_block<U, true>(pm, pl, pa, n_full, n_act, M, L, acc);
831    attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
832}
833
834#if defined(STRATA_HIP_GFX906)
835// The compat backend can target other architectures. Check the calling thread's current device,
836// caching only its last ordinal so a layer split or another thread cannot reuse the wrong answer.
837bool query_swizzle_gfx906_device() {
838    static thread_local int cached_device = -1;
839    static thread_local bool cached_supported = false;
840    int device = -1;
841    if (hipGetDevice(&device) != hipSuccess || device < 0) {
842        cached_device = -1;
843        cached_supported = false;
844        (void) hipGetLastError();
845        return false;
846    }
847    if (device != cached_device) {
848        cached_device = -1;
849        cached_supported = false;
850        hipDeviceProp_t prop{};
851        if (hipGetDeviceProperties(&prop, device) != hipSuccess) {
852            (void) hipGetLastError();
853            return false;
854        }
855        cached_supported = gfx_arch_is(prop.gcnArchName, "gfx906") && prop.warpSize == 64;
856        cached_device = device;
857    }
858    return cached_supported;
859}
860#endif
861
862// Fork (lab/upsync): STRATA_ATTN_DAILY=1 runs the Daily's (be4cf1c) decode attention on every CUDA card: the chunk
863// pass on PR #540's kernel (attn_chunk_kernel_pre75<M, 2, false>, the Daily's attn_chunk_kernel), bit for bit the
864// default kernel's partials.  CUDA only; unset or anything but "1" keeps upstream 0.1.42's kernels.
865// STRATA_ATTN_PRE75=0 still turns the chunk kernel off (A/B).
866// 147-verify: unset, it is on for a compute capability 12.0 card (sm120_series.hpp; RTX PRO 5000, a 4-token verify round
867// -2.6%, bitwise); STRATA_ATTN_DAILY=0 (anything but "1") keeps upstream's kernels there too.
868[[maybe_unused]] bool daily_attn() {
869#if defined(__HIPCC__)
870    return false;
871#else
872    static const int env = [] {
873        const char* v = std::getenv("STRATA_ATTN_DAILY");
874        if (v == nullptr) return -1;
875        return v[0] == '1' && v[1] == '\0' ? 1 : 0;
876    }();
877    if (env >= 0) return env != 0;
878    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
879    int dev = 0;
880    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
881    if (!per_dev[dev]) {
882        int maj = 0, mnr = 0;
883        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
884                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
885        if (!ok) cudaGetLastError();
886        per_dev[dev] = ok && strata::sm120_default(maj, mnr) ? 2 : 1;
887    }
888    return per_dev[dev] == 2;
889#endif
890}
891
892#if defined(STRATA_ATTN_PRE75_BUILT)
893// CUDA: the current device is below sm_75 (experimental build) or STRATA_ATTN_DAILY=1 (any card); HIP: it is gfx103x
894// (per device: a layer split can mix cards).
895// STRATA_ATTN_PRE75=0 turns PR #540's kernel off (A/B); on HIP =1 also runs it on another wave32 card.
896bool pre75_attn() {
897    static const int env = [] {
898        const char* e = std::getenv("STRATA_ATTN_PRE75");
899        return e == nullptr ? -1 : e[0] == '0' ? 0 : e[0] == '1' ? 1 : -1;
900    }();
901    if (env == 0) return false;
902#if !defined(__HIPCC__) && !defined(STRATA_EXPERIMENTAL_SM60)
903    return daily_attn();   // the ready-made engine: upstream's attn_chunk_kernel unless STRATA_ATTN_DAILY=1
904#else
905#if !defined(__HIPCC__)
906    if (daily_attn()) return true;
907#endif
908    static int cc[64] = {};
909    int dev = 0;
910    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
911#if defined(__HIPCC__)
912    if (cc[dev] == 0) {   // 2: gfx103x, 1: another card
913        hipDeviceProp_t prop{};
914        if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }
915        cc[dev] = std::strncmp(prop.gcnArchName, "gfx103", 6) == 0 ? 2 : 1;
916    }
917    return env == 1 || cc[dev] == 2;
918#else
919    if (cc[dev] == 0) {
920        int major = 0, minor = 0;
921        if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
922            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
923            cudaGetLastError();
924            return false;
925        }
926        cc[dev] = 10 * major + minor;
927    }
928    return cc[dev] < 75;
929#endif
930#endif  // ready-made CUDA engine
931}
932// `PRE` picks PR #540's kernel; the environment's choice is STRATA_ATTN_CHUNK.
933#if defined(__HIPCC__)
934#define STRATA_ATTN_CHUNK_SEL(M, PRE) ((PRE) ? attn_chunk_kernel_pre75<M, 8, true> : attn_chunk_kernel<M>)
935#else
936#define STRATA_ATTN_CHUNK_SEL(M, PRE) ((PRE) ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
937#endif
938#define STRATA_ATTN_CHUNK(M) STRATA_ATTN_CHUNK_SEL(M, pre75_attn())
939#else
940#define STRATA_ATTN_CHUNK_SEL(M, PRE) attn_chunk_kernel<M>
941#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
942#endif
943
944// S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
945bool lane_cell_attn() {
946    static const bool on = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
947    return on;
948}
949
950// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V
951int attn_kv_mode(const QsaAttnPools& p) {
952    return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0));
953}
954
955// STRATA_ATTN_MERGE_V2: 1 merges with attn_merge_v2_kernel, 0 with attn_merge_kernel.  Unset it follows
956// STRATA_ATTN_DAILY (the Daily had it on by default on NVIDIA), so upstream's merger stays the default.
957int attn_merge_v2() {
958    static const int env = [] {
959        const char* v = std::getenv("STRATA_ATTN_MERGE_V2");
960        return v != nullptr && *v != '\0' ? (std::atoi(v) != 0 ? 1 : 0) : -1;
961    }();
962    return env >= 0 ? env : (daily_attn() ? 1 : 0);
963}
964
965// the merge of `n_q` queries' partials: v2 = 0 attn_merge_kernel, 1 attn_merge_v2_kernel (bitwise the same output)
966void launch_merge(int v2, const float* part_acc, const float* part_m, const float* part_l, int n_chunks,
967                  const int32_t* steps, float* attn, long long stride, unsigned n_head, unsigned n_q, cudaStream_t st) {
968    if (v2)
969        attn_merge_v2_kernel<kMergeU><<<dim3(n_head, n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, steps,
970                                                                         attn, stride);
971    else
972        attn_merge_kernel<<<dim3(n_head, n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn, stride);
973}
974
975// qsa_decode_attn_batch's chunk pass: `n_q` queries' partials into `scratch` (one stride each).  `kernel` < 0 is the
976// environment's choice (lane cell, gfx906 swizzle, STRATA_ATTN_DAILY / PR #540); 0 is attn_chunk_kernel and 1 PR #540's
977// kernel where it is built (the parity harness: never the environment).
978void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
979                         int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, cudaStream_t st, int kernel) {
980    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
981                        : (pools.k_q != nullptr ? 1 : 0));
982    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
983    // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride
984    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
985    float* part_acc = scratch;
986    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
987    float* part_l = part_m + (size_t) n_chunks * s.n_head;
988    const float scale = 1.0f / sqrtf((float) HD);
989    const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
990#if defined(STRATA_ATTN_PRE75_BUILT)
991    const bool pre = kernel < 0 ? pre75_attn() : kernel == 1;
992#endif
993    // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions)
994    const bool lane_cell = kernel < 0 && lane_cell_attn();
995#if defined(STRATA_HIP_GFX906)
996    static const bool query_swizzle = [] {
997        const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1';
998    }();
999    const bool use_query_swizzle = kernel < 0 && query_swizzle && !lane_cell && kv_mode == 1 &&
1000                                   query_swizzle_gfx906_device();
1001    static const bool query_swizzle_trace = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE_TRACE") != nullptr;
1002    static thread_local bool query_swizzle_said = false;
1003    if (query_swizzle_trace && !query_swizzle_said) {
1004        query_swizzle_said = true;
1005        std::fprintf(stderr, "strata attn-query-swizzle: active=%d nq=%lld cap=%lld kv_mode=%d lane_cell=%d\n",
1006                     use_query_swizzle, (long long) n_q, (long long) cap, kv_mode, lane_cell);
1007    }
1008#endif
1009#define STRATA_ATTN_LC(M) attn_chunk_kernel<M, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
1010    if (lane_cell) {
1011        if (kv_mode == 3) STRATA_ATTN_LC(3);
1012        else if (kv_mode == 2) STRATA_ATTN_LC(2);
1013        else if (kv_mode == 1) STRATA_ATTN_LC(1);
1014        else STRATA_ATTN_LC(0);
1015    } else
1016#undef STRATA_ATTN_LC
1017#if defined(STRATA_HIP_GFX906)
1018    // Opt-in INT8 batched attention: prefill, verification and MTP (including n_q=1).
1019    // Other pool formats and lane-cell scoring keep their paths; qsa_decode_attn_step is unchanged.
1020    // A k8v4 model's MTP drafter uses INT8 pools and can therefore take this path.
1021    if (use_query_swizzle) {
1022        // use_query_swizzle already requires INT8, warp scoring, and the calling
1023        // thread's current device to be exactly gfx906 with a 64-lane wavefront.
1024        static const bool reduce12 = [] {
1025            const char* v = std::getenv("STRATA_GFX906_ATTN_REDUCE12");
1026            return v && v[0] == '1' && v[1] == '\0';
1027        }();
1028        if (reduce12) {
1029            attn_chunk_kernel<1, false, true, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps,
1030                (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
1031            static const bool trace = [] {
1032                const char* v = std::getenv("STRATA_GFX906_ATTN_REDUCE12_TRACE");
1033                return v && v[0] == '1' && v[1] == '\0';
1034            }();
1035            static thread_local bool said = false;
1036            if (trace && !said) {
1037                said = true;
1038                std::fprintf(stderr, "strata attn-reduce12: selected=1 query_swizzle=1 kv_mode=1 nq=%lld cap=%lld\n",
1039                             (long long) n_q, (long long) cap);
1040            }
1041        } else {
1042            attn_chunk_kernel<1, false, true><<<grid, THREADS, 0, st>>>(q, pools, ids, steps,
1043                (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
1044        }
1045    } else
1046#endif
1047#if !defined(__HIPCC__)
1048    if (kernel < 0 && kv_mode == 1 && attn_v3_on())   // (the parity harness names its kernel: never the environment)
1049        attn_chunk_q8_v3_kernel<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
1050                                                          scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
1051    else
1052#endif
1053    if (kv_mode == 3)
1054        STRATA_ATTN_CHUNK_SEL(3, pre)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv,
1055                                                                (int) s.page_size, scale, part_acc, part_m, part_l,
1056                                                                n_chunks, (int) cap, stride);
1057    else if (kv_mode == 2)
1058        STRATA_ATTN_CHUNK_SEL(2, pre)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv,
1059                                                                (int) s.page_size, scale, part_acc, part_m, part_l,
1060                                                                n_chunks, (int) cap, stride);
1061    else if (kv_mode == 1)
1062        STRATA_ATTN_CHUNK_SEL(1, pre)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv,
1063                                                                (int) s.page_size, scale, part_acc, part_m, part_l,
1064                                                                n_chunks, (int) cap, stride);
1065    else
1066        STRATA_ATTN_CHUNK_SEL(0, pre)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv,
1067                                                                (int) s.page_size, scale, part_acc, part_m, part_l,
1068                                                                n_chunks, (int) cap, stride);
1069}
1070
1071// qsa_decode_attn_batch's merge pass over the partials launch_chunks_batch wrote; `v2` names the merge kernel
1072void launch_merge_batch(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch, float* attn,
1073                        int64_t n_q, int v2, cudaStream_t st) {
1074    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1075    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1076    const float* part_acc = scratch;
1077    const float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1078    const float* part_l = part_m + (size_t) n_chunks * s.n_head;
1079    launch_merge(v2, part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head, (unsigned) n_q, st);
1080}
1081
1082}  // namespace
1083
1084void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
1085                           int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1086    if (n_q <= 0) return;
1087    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps ||
1088        !pools.page_table || n_q > 65535) {
1089        std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n");
1090        std::exit(1);
1091    }
1092    cudaStream_t st = (cudaStream_t) stream;
1093    launch_chunks_batch(q, pools, ids, steps, cap, s, scratch, n_q, st, -1);
1094    launch_merge_batch(steps, cap, s, scratch, attn, n_q, attn_merge_v2(), st);
1095    const cudaError_t e = cudaGetLastError();
1096    if (e != cudaSuccess) {
1097        std::fprintf(stderr, "qsa_decode_attn_batch: %s\n", cudaGetErrorString(e));
1098        std::exit(1);
1099    }
1100}
1101
1102bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const int32_t* ids, const int32_t* steps,
1103                           int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1104    if (n_q <= 0) return true;
1105    if (n_q > kQsaAttnMaxSlots) return false;
1106    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps) {
1107        std::fprintf(stderr, "qsa_decode_attn_slots: unsupported geometry or missing buffers\n");
1108        std::exit(1);
1109    }
1110    const int kv_mode = attn_kv_mode(pools.p[0]);
1111    for (int64_t z = 0; z < n_q; ++z) {
1112        if (!pools.p[z].page_table) {
1113            std::fprintf(stderr, "qsa_decode_attn_slots: missing page table\n");
1114            std::exit(1);
1115        }
1116        if (attn_kv_mode(pools.p[z]) != kv_mode) return false;
1117    }
1118    const bool lane_cell = lane_cell_attn();
1119    // only where qsa_decode_attn_batch runs attn_chunk_kernel; its other variants keep the per-query calls
1120#if defined(STRATA_ATTN_PRE75_BUILT)
1121    if (!lane_cell && pre75_attn()) return false;
1122#endif
1123#if defined(STRATA_HIP_GFX906)
1124    static const bool query_swizzle = [] {
1125        const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1';
1126    }();
1127    if (query_swizzle && !lane_cell && kv_mode == 1 && query_swizzle_gfx906_device()) return false;
1128#endif
1129    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1130    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1131    float* part_acc = scratch;
1132    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1133    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1134    const float scale = 1.0f / sqrtf((float) HD);
1135    const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
1136    cudaStream_t st = (cudaStream_t) stream;
1137#define STRATA_ATTN_SLOTS(M, LC) attn_chunk_slots_kernel<M, LC><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
1138    if (lane_cell) {
1139        if (kv_mode == 3) STRATA_ATTN_SLOTS(3, true);
1140        else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, true);
1141        else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, true);
1142        else STRATA_ATTN_SLOTS(0, true);
1143    } else {
1144        if (kv_mode == 3) STRATA_ATTN_SLOTS(3, false);
1145        else if (kv_mode == 2) STRATA_ATTN_SLOTS(2, false);
1146        else if (kv_mode == 1) STRATA_ATTN_SLOTS(1, false);
1147        else STRATA_ATTN_SLOTS(0, false);
1148    }
1149#undef STRATA_ATTN_SLOTS
1150    launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head,
1151                 (unsigned) n_q, st);
1152    const cudaError_t e = cudaGetLastError();
1153    if (e != cudaSuccess) {
1154        std::fprintf(stderr, "qsa_decode_attn_slots: %s\n", cudaGetErrorString(e));
1155        std::exit(1);
1156    }
1157    return true;
1158}
1159
1160void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps,
1161                                int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1162    if (n_q <= 0) return;
1163    const QsaAttnPools& pools = rows.p[0];
1164    if (rows.n != n_q || n_q > kAttnRowsMax || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 ||
1165        !scratch || !ids || !steps) {
1166        std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n");
1167        std::exit(1);
1168    }
1169    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1170                        : (pools.k_q != nullptr ? 1 : 0));
1171    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1172    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1173    float* part_acc = scratch;
1174    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1175    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1176    const float scale = 1.0f / sqrtf((float) HD);
1177    const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
1178    cudaStream_t st = (cudaStream_t) stream;
1179    // The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the
1180    // pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row.
1181    static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }();
1182    bool per_row = lane_cell_rows;
1183#if defined(STRATA_ATTN_PRE75_BUILT)
1184    per_row = per_row || pre75_attn();
1185#endif
1186#if defined(STRATA_HIP_GFX906)
1187    per_row = true;
1188#endif
1189    if (per_row) {
1190        for (int64_t r = 0; r < n_q; ++r)
1191            qsa_decode_attn_batch(q + (size_t) r * s.n_head * HD, rows.p[r], ids + (size_t) r * cap,
1192                                  steps + (size_t) r * kStepCount, cap, s, scratch + (size_t) r * stride,
1193                                  attn + (size_t) r * s.n_head * HD, 1, stream);
1194        return;
1195    }
1196#define STRATA_ATTN_ROWS(M) attn_chunk_rows_kernel<M><<<grid, THREADS, 0, st>>>(q, rows, ids, steps, (int) s.n_head_kv, \
1197        (int) s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride)
1198    if (kv_mode == 3) STRATA_ATTN_ROWS(3);
1199    else if (kv_mode == 2) STRATA_ATTN_ROWS(2);
1200    else if (kv_mode == 1) STRATA_ATTN_ROWS(1);
1201    else STRATA_ATTN_ROWS(0);
1202#undef STRATA_ATTN_ROWS
1203    launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, steps, attn, stride, (unsigned) s.n_head,
1204                 (unsigned) n_q, st);
1205    const cudaError_t e = cudaGetLastError();
1206    if (e != cudaSuccess) {
1207        std::fprintf(stderr, "qsa_decode_attn_batch_rows: %s\n", cudaGetErrorString(e));
1208        std::exit(1);
1209    }
1210}
1211
1212uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
1213    const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
1214    return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
1215}
1216
1217void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step,
1218                          int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) {
1219    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step ||
1220        !pools.page_table) {
1221        std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n");
1222        std::exit(1);
1223    }
1224    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1225                        : (pools.k_q != nullptr ? 1 : 0));
1226    if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
1227                     : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale)
1228                                                                     : (!pools.k_pool || !pools.v_pool)))) {
1229        std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n");
1230        std::exit(1);
1231    }
1232    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1233    float* part_acc = scratch;
1234    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1235    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1236    const float scale = 1.0f / sqrtf((float) HD);
1237    const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv);
1238    cudaStream_t st = (cudaStream_t) stream;
1239#if !defined(__HIPCC__)
1240    if (kv_mode == 1 && attn_v3_on())
1241        attn_chunk_q8_v3_kernel<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
1242                                                          scale, part_acc, part_m, part_l, n_chunks, 0, 0);
1243    else
1244#endif
1245    if (kv_mode == 3)
1246        STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
1247                                                        scale, part_acc, part_m, part_l, n_chunks, 0, 0);
1248    else if (kv_mode == 2)
1249        STRATA_ATTN_CHUNK(2)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
1250                                                        scale, part_acc, part_m, part_l, n_chunks, 0, 0);
1251    else if (kv_mode == 1)
1252        STRATA_ATTN_CHUNK(1)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
1253                                                        scale, part_acc, part_m, part_l, n_chunks, 0, 0);
1254    else
1255        STRATA_ATTN_CHUNK(0)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
1256                                                        scale, part_acc, part_m, part_l, n_chunks, 0, 0);
1257    launch_merge(attn_merge_v2(), part_acc, part_m, part_l, n_chunks, step, attn, 0, (unsigned) s.n_head, 1u, st);
1258    const cudaError_t e = cudaGetLastError();
1259    if (e != cudaSuccess) {
1260        std::fprintf(stderr, "qsa_decode_attn: %s\n", cudaGetErrorString(e));
1261        std::exit(1);
1262    }
1263}
1264
1265// qsa_merge_daily_parity: qsa_decode_attn_batch's two passes apart, the chunk kernel and the merge named by the
1266// arguments (never the environment), so the Daily's kernels and upstream's can be run on the same inputs and the
1267// outputs compared bit for bit.  The engine never calls these.
1268void qsa_decode_attn_chunks_only(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
1269                                 int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, int daily_chunk,
1270                                 void* stream) {
1271    if (n_q <= 0 || n_q > 65535 || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch ||
1272        !q || !ids || !steps || !pools.page_table || (daily_chunk != 0 && daily_chunk != 1)) {
1273        std::fprintf(stderr, "qsa_decode_attn_chunks_only: unsupported geometry or missing buffers\n");
1274        std::exit(1);
1275    }
1276    launch_chunks_batch(q, pools, ids, steps, cap, s, scratch, n_q, (cudaStream_t) stream, daily_chunk);
1277    const cudaError_t e = cudaGetLastError();
1278    if (e != cudaSuccess) {
1279        std::fprintf(stderr, "qsa_decode_attn_chunks_only: %s\n", cudaGetErrorString(e));
1280        std::exit(1);
1281    }
1282}
1283
1284void qsa_decode_attn_merge_only(const int32_t* steps, int64_t cap, const QsaShapes& s, const float* scratch,
1285                                float* attn, int64_t n_q, int v2, void* stream) {
1286    if (n_q <= 0 || n_q > 65535 || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch ||
1287        (v2 != 0 && v2 != 1) || !steps || !attn) {
1288        std::fprintf(stderr, "qsa_decode_attn_merge_only: unsupported geometry or missing buffers\n");
1289        std::exit(1);
1290    }
1291    launch_merge_batch(steps, cap, s, scratch, attn, n_q, v2, (cudaStream_t) stream);
1292    const cudaError_t e = cudaGetLastError();
1293    if (e != cudaSuccess) {
1294        std::fprintf(stderr, "qsa_decode_attn_merge_only: %s\n", cudaGetErrorString(e));
1295        std::exit(1);
1296    }
1297}
1298
1299}  // namespace strata::kernels