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
132.3 KiB2571 linesraw
1// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp.
2#include "strata/core/emulate.hpp"
3#include "strata/core/sm120_series.hpp"
4#include "strata/core/defaults_026.hpp"
5#include "strata/core/sm75_series.hpp"
6#include "strata/core/geometry.hpp"
7#include "strata/core/gfx12_platform_defaults.hpp"
8#include <cstdlib>
9#include <cstring>
10#include "strata/kernels/qsa_prompt_attn.hpp"
11#include "strata/kernels/gfx_arch.hpp"
12#include "strata/kernels/kv_q8.hpp"
13#include "strata/kernels/kv_q4.hpp"
14
15#include <cuda_fp16.h>
16#include <cuda_runtime.h>
17#include <algorithm>
18#include <cmath>
19
20#include <atomic>
21#include <cstdio>
22#include <vector>
23#include <algorithm>
24#include <cstdlib>
25#include <cstring>
26#include <type_traits>
27
28namespace strata::kernels {
29namespace {
30
31constexpr int HD = 256;           // head_dim
32constexpr int G = strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv;   // query heads per KV head (12 for Flash-Next); the tiles pad the rows to 16, so G <= 16
33static_assert(G >= 1 && G <= 16, "qsa_prompt_attn: query heads per KV head must be 1..16 (one M16 tile)");
34static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_prompt_attn is compiled for core/geometry.hpp");
35#ifndef D1_CH
36#define D1_CH 32
37#endif
38constexpr int CH = D1_CH;         // cells per chunk
39constexpr int THREADS = 128;      // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group)
40constexpr int QS = HD + 8;        // q row stride in halves (bank-conflict-free fragment loads)
41
42// The MMA below needs sm_75 or newer (Turing runs it as two k=8 steps); cp.async needs sm_80. Builds for pre-sm_75
43// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs
44// there.  Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8.
45#if defined(__HIPCC__)          // AMD: no mma.sync / cp.async; the host keeps the old kernel (below)
46#define STRATA_PA_SM80 0
47#elif !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800
48#define STRATA_PA_SM80 1
49#else
50#define STRATA_PA_SM80 0
51#endif
52
53// m16n8k16 with f16 inputs needs sm_80.  Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the
54// k=16 step is two k=8 steps on the fragments as they are already laid out: a[0]/a[1] are rows gid/gid+8 at k columns
55// 2*tig..2*tig+1 (b[0]'s k rows), a[2]/a[3] the same rows at k columns 2*tig+8..2*tig+9 (b[1]'s k rows).  The
56// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16
57// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit.
58__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) {
59#if !STRATA_PA_SM80 && (defined(__HIPCC__) || !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 750)
60    __trap();   // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there)
61#elif !STRATA_PA_SM80
62    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
63                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
64                 : "r"(a[0]), "r"(a[1]), "r"(b[0]));
65    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
66                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
67                 : "r"(a[2]), "r"(a[3]), "r"(b[1]));
68#else
69    asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
70                 "{%0,%1,%2,%3};\n"
71                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
72                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
73#endif
74}
75
76// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152.
77__device__ __forceinline__ uint32_t i8x2_to_h2(uint32_t x) {
78    uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u;
79    y |= 0x64006400u;
80    __half2 h = *reinterpret_cast<__half2*>(&y);
81    h = __hsub2(h, __halves2half2(__float2half(1152.f), __float2half(1152.f)));
82    return *reinterpret_cast<uint32_t*>(&h);
83}
84
85__device__ __forceinline__ uint32_t pack_h2(float lo_k, float hi_k) {   // element k in the low half
86    __half2 h = __floats2half2_rn(lo_k, hi_k);
87    return *reinterpret_cast<uint32_t*>(&h);
88}
89
90// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1).
91// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at
92// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output.
93// KV_MODE 4 (Q4_0 K and V, `--kv q4_0`): mode 1 with a scale per 32 values - each q4_0 block's codes enter as exact
94// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the
95// output (kv_q4.hpp).
96template <int KV_MODE, bool PF = false>
97struct Smem {
98    using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
99    using VElem = typename std::conditional<KV_MODE == 1 || KV_MODE == 4, int8_t, __half>::type;
100    static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;   // elements; 16-byte aligned rows, banks spread
101    static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4) ? HD + 16 : HD + 8;
102    static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4;      // scale groups per row (q4_0: 8 of 32, else 4 of 64)
103    __half qh[16][QS];
104    __half ql[16][QS];
105    // int8 K/V (mode 1): K is read only by the scores and V only by p.v, so they share one buffer - V is stored over K
106    // after the scores (prompt_attn_kernel).  37.9 -> 29.2 KB: two blocks fit an SM's 64 KB on Turing instead of one.
107    struct Rows { KElem k[CH][KROW]; VElem v[CH][VROW]; };
108    struct SharedRows { union { KElem k[CH][KROW]; VElem v[CH][VROW]; }; };
109    typename std::conditional<KV_MODE == 1 && PF, SharedRows, Rows>::type kv;
110    float ks[CH][NG];
111    float vs[CH][NG];
112    float s[16][CH + 1];
113    float qmax[THREADS / 32];
114    float alpha[16];
115    float lsum[16];
116    float mrow[16];
117    long long row[CH];
118};
119
120template <int KV_MODE, bool PF = false>
121__global__ void __launch_bounds__(THREADS) prompt_attn_kernel(const float* __restrict__ q, QsaAttnPools p,
122                                                              const int32_t* __restrict__ ids,
123                                                              const int32_t* __restrict__ steps, int n_kv_heads,
124                                                              int page_size, float scale_log2, float* __restrict__ attn,
125                                                              int cap) {
126    extern __shared__ __align__(16) unsigned char smem_raw[];
127    Smem<KV_MODE, PF>& S = *reinterpret_cast<Smem<KV_MODE, PF>*>(smem_raw);
128    const int qi = blockIdx.x, kvh = blockIdx.y;
129    const int n_head = n_kv_heads * G;
130    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
131    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
132    ids += (size_t) qi * cap;
133    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
134    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
135    const int gid = lane >> 2, tig = lane & 3;
136
137    // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
138    // lo halves stay out of FP16's subnormal range), then split into hi + lo halves
139    float qm = 0.0f;
140    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
141#pragma unroll
142    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
143    if (lane == 0) S.qmax[warp] = qm;
144    __syncthreads();
145    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
146    int qe = 0;
147    if (qm > 0.0f) frexpf(qm, &qe);                 // qm < 2^qe
148    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
149    for (int i = t; i < 16 * HD; i += THREADS) {
150        const int h = i / HD, d = i % HD;
151        const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
152        const __half hi = __float2half_rn(x);
153        S.qh[h][d] = hi;
154        S.ql[h][d] = __float2half_rn(x - __half2float(hi));
155    }
156    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
157
158    float acc[8][4];
159#pragma unroll
160    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
161
162    // int8 K/V: the next chunk's rows are loaded into registers while this chunk computes (Turing has no cp.async, and
163    // at 1 block per SM the gather's latency was the kernel's largest stall), then stored to shared memory exactly as
164    // the gather below stores them: the same bytes in the same places, the same arithmetic after.
165    constexpr bool PREFETCH = KV_MODE == 1 && PF;
166    constexpr int KP = HD / 16;                               // 16-byte pieces per int8 row
167    constexpr int PPT = PREFETCH ? CH * KP / THREADS : 1;     // pieces per thread
168    static_assert(!PREFETCH || (CH * KP) % THREADS == 0 && CH * 4 == THREADS, "prefetch layout");
169    uint4 pk[PPT], pv[PPT];
170    float pa = 0.0f, pb = 0.0f;
171    auto row_of = [&](int c0, int c) -> long long {          // as S.row below; -1 past the chunk's cells
172        if (c >= min(CH, n - c0)) return -1;
173        const int cell = ids[c0 + c];
174        const long long page = (long long) p.page_table[cell / page_size];
175        return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
176    };
177    auto fetch = [&](int c0) {
178        if constexpr (PREFETCH) {
179#pragma unroll
180            for (int j = 0; j < PPT; ++j) {
181                const int i = t + j * THREADS, c = i / KP, pc = i % KP;
182                const long long r = row_of(c0, c);
183                pk[j] = r >= 0 ? __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc) : make_uint4(0, 0, 0, 0);
184                pv[j] = r >= 0 ? __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc) : make_uint4(0, 0, 0, 0);
185            }
186            const int c = t / 4, g = t % 4;
187            const long long r = row_of(c0, c);
188            pa = r >= 0 ? __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g])) : 0.0f;
189            pb = r >= 0 ? __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g])) : 0.0f;
190        }
191    };
192    if constexpr (PREFETCH) fetch(0);
193
194    for (int c0 = 0; c0 < n; c0 += CH) {
195        const int nh = min(CH, n - c0);
196        if constexpr (PREFETCH) {
197            __syncthreads();   // the previous chunk's p.v is done with k, v, s
198#pragma unroll
199            for (int j = 0; j < PPT; ++j) {
200                const int i = t + j * THREADS, c = i / KP, pc = i % KP;
201                *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.k[c][0]) + pc * 16) = pk[j];
202            }
203            S.ks[t / 4][t % 4] = pa;
204            S.vs[t / 4][t % 4] = pb;
205            __syncthreads();
206        } else {
207        if (t < CH) {
208            long long r = -1;
209            if (t < nh) {
210                const int cell = ids[c0 + t];
211                const long long page = (long long) p.page_table[cell / page_size];
212                r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
213            }
214            S.row[t] = r;
215        }
216        __syncthreads();   // rows ready; the previous chunk's p.v is done with k, v, s
217        // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
218        // and their scales
219        if constexpr (KV_MODE == 4) {
220            // q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight
221            // 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high
222            // one), its fp16 scale goes to ks/vs
223            constexpr int BLKS = HD / QK4_0;
224            constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
225            for (int i = t; i < 2 * CH * BLKS; i += THREADS) {
226                const int kv = i / (CH * BLKS), rem = i % (CH * BLKS), c = rem / BLKS, b = rem % BLKS;
227                const long long r = S.row[c];
228                uint4 lo = make_uint4(0, 0, 0, 0), hi = make_uint4(0, 0, 0, 0);
229                float d = 0.0f;
230                if (r >= 0) {
231                    const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((kv == 0 ? p.k_q4 : p.v_q4) + r * BYTES) + b;
232                    d = __half2float(__ushort_as_half(__ldg(&blk->d)));
233                    const uint16_t* q16 = reinterpret_cast<const uint16_t*>(blk->qs);
234                    uint32_t w[4];
235#pragma unroll
236                    for (int j = 0; j < 4; ++j)
237                        w[j] = (uint32_t) __ldg(q16 + 2 * j) | ((uint32_t) __ldg(q16 + 2 * j + 1) << 16);
238                    // per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16
239                    lo = make_uint4(__vsub4(w[0] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[1] & 0x0F0F0F0Fu, 0x08080808u),
240                                    __vsub4(w[2] & 0x0F0F0F0Fu, 0x08080808u), __vsub4(w[3] & 0x0F0F0F0Fu, 0x08080808u));
241                    hi = make_uint4(__vsub4((w[0] >> 4) & 0x0F0F0F0Fu, 0x08080808u),
242                                    __vsub4((w[1] >> 4) & 0x0F0F0F0Fu, 0x08080808u),
243                                    __vsub4((w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u),
244                                    __vsub4((w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u));
245                }
246                int8_t* dst = kv == 0 ? &S.kv.k[c][b * QK4_0] : &S.kv.v[c][b * QK4_0];
247                reinterpret_cast<uint4*>(dst)[0] = lo;
248                reinterpret_cast<uint4*>(dst)[1] = hi;
249                (kv == 0 ? S.ks : S.vs)[c][b] = d;
250            }
251        } else {
252            constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16;   // per K row
253            for (int i = t; i < CH * KPIECES; i += THREADS) {
254                const int c = i / KPIECES, pc = i % KPIECES;
255                const long long r = S.row[c];
256                uint4 kx = make_uint4(0, 0, 0, 0);
257                if (r >= 0) {
258                    if constexpr (KV_MODE == 0)
259                        kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
260                    else   // modes 1 and 3: the K side is INT8
261                        kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
262                }
263                *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.k[c][0]) + pc * 16) = kx;
264            }
265            if constexpr (KV_MODE == 3) {   // V: dequantize the row's q4_0 blocks straight into the fp16 V row
266                constexpr int BLKS = HD / QK4_0;
267                constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
268                for (int i = t; i < CH * BLKS; i += THREADS) {
269                    const int c = i / BLKS, b = i % BLKS;
270                    const long long r = S.row[c];
271#pragma unroll
272                    for (int j = 0; j < QK4_0; ++j) S.kv.v[c][b * QK4_0 + j] = __half(0);
273                    if (r >= 0) {
274                        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
275                        const float d = __half2float(__ushort_as_half(blk->d));
276#pragma unroll
277                        for (int j = 0; j < QK4_0 / 2; ++j) {
278                            S.kv.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
279                            S.kv.v[c][b * QK4_0 + j + QK4_0 / 2] =
280                                __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
281                        }
282                    }
283                }
284            } else {
285                constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16;   // per V row
286                for (int i = t; i < CH * VPIECES; i += THREADS) {
287                    const int c = i / VPIECES, pc = i % VPIECES;
288                    const long long r = S.row[c];
289                    uint4 vx = make_uint4(0, 0, 0, 0);
290                    if (r >= 0) {
291                        if constexpr (KV_MODE == 1)
292                            vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
293                        else
294                            vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
295                    }
296                    *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.v[c][0]) + pc * 16) = vx;
297                }
298            }
299            for (int i = t; i < CH * 4; i += THREADS) {
300                const int c = i / 4, g = i % 4;
301                const long long r = S.row[c];
302                float a = 0.0f, b = 0.0f;
303                if (r >= 0) {
304                    if constexpr (KV_MODE == 1) {
305                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
306                        b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
307                    } else if constexpr (KV_MODE == 3) {   // K as int8, V dequantized to fp16 (scale 1)
308                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
309                        b = 1.0f;
310                    } else {
311                        a = b = 1.0f;
312                    }
313                }
314                S.ks[c][g] = a;
315                S.vs[c][g] = b;
316            }
317        }
318        __syncthreads();
319        }
320        // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32)
321        constexpr int NG = Smem<KV_MODE>::NG, KPG = HD / 16 / NG;   // groups per row, 16-dim MMA steps per group
322#pragma unroll
323        for (int nt = 0; nt < CH / 32; ++nt) {
324            const int cb = (warp + 4 * nt) * 8;
325            float sc[4] = {0.f, 0.f, 0.f, 0.f};
326#pragma unroll
327            for (int g = 0; g < NG; ++g) {
328                float tg[4] = {0.f, 0.f, 0.f, 0.f};
329#pragma unroll
330                for (int kk = 0; kk < KPG; ++kk) {
331                    const int k0 = (g * KPG + kk) * 16;
332                    uint32_t ah[4], al[4], b[2];
333                    ah[0] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig]);
334                    ah[1] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig]);
335                    ah[2] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig + 8]);
336                    ah[3] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig + 8]);
337                    al[0] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig]);
338                    al[1] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig]);
339                    al[2] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig + 8]);
340                    al[3] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig + 8]);
341                    if constexpr (KV_MODE != 0) {   // modes 1 and 3: the K side is INT8 codes
342                        b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.kv.k[cb + gid][k0 + 2 * tig]));
343                        b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.kv.k[cb + gid][k0 + 2 * tig + 8]));
344                    } else {
345                        b[0] = *reinterpret_cast<const uint32_t*>(&S.kv.k[cb + gid][k0 + 2 * tig]);
346                        b[1] = *reinterpret_cast<const uint32_t*>(&S.kv.k[cb + gid][k0 + 2 * tig + 8]);
347                    }
348                    mma16816(tg, ah, b);
349#ifndef D1_NO_QLO
350                    mma16816(tg, al, b);
351#endif
352                }
353                const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g];
354                sc[0] = fmaf(tg[0], s0, sc[0]);
355                sc[1] = fmaf(tg[1], s1, sc[1]);
356                sc[2] = fmaf(tg[2], s0, sc[2]);
357                sc[3] = fmaf(tg[3], s1, sc[3]);
358            }
359            const int c = cb + 2 * tig;
360            S.s[gid][c] = c < nh ? sc[0] * qdown : -INFINITY;
361            S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -INFINITY;
362            S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -INFINITY;
363            S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -INFINITY;
364        }
365        __syncthreads();
366        if constexpr (PREFETCH) {   // the scores are done with K: V goes over it (read after the softmax's barrier)
367#pragma unroll
368            for (int j = 0; j < PPT; ++j) {
369                const int i = t + j * THREADS, c = i / KP, pc = i % KP;
370                *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.kv.v[c][0]) + pc * 16) = pv[j];
371            }
372            if (c0 + CH < n) fetch(c0 + CH);   // the next chunk's rows, in flight while this one finishes
373        }
374        // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
375        {
376            constexpr int PER = CH / 8;
377            const int r = t >> 3, sub = t & 7;
378            float x[PER], mx = -INFINITY;
379#pragma unroll
380            for (int j = 0; j < PER; ++j) { x[j] = S.s[r][sub * PER + j]; mx = fmaxf(mx, x[j]); }
381#pragma unroll
382            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
383            const float m_old = S.mrow[r];
384            const float m_new = fmaxf(m_old, mx);
385            float sum = 0.0f;
386#pragma unroll
387            for (int j = 0; j < PER; ++j) {
388                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
389                S.s[r][sub * PER + j] = e;
390                sum += e;
391            }
392#pragma unroll
393            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
394            __syncwarp();
395            if (sub == 0) {
396                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
397                S.alpha[r] = a;
398                S.lsum[r] = fmaf(S.lsum[r], a, sum);
399                S.mrow[r] = m_new;
400            }
401        }
402        __syncthreads();
403        // p.v: warp w owns dims [64w, 64w+64), which is int8 scale group w (q4_0: groups 2w and 2w+1, four n-tiles
404        // each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed:
405        // ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the
406        // chunk's sum is then added to the running one in FP32 with the factor taken back out
407        {
408            constexpr int GPW = NG / 4, JPG = 8 / GPW;   // scale groups per warp, n-tiles per group
409            float vdown_g[GPW];
410            float tmp[8][4];
411#pragma unroll
412            for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
413#pragma unroll
414            for (int gi = 0; gi < GPW; ++gi) {
415            const int vg = warp * GPW + gi;
416            float vmax = 0.0f;
417#pragma unroll
418            for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, fabsf(S.vs[c][vg]));
419#pragma unroll
420            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
421            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f;
422            vdown_g[gi] = vmax * (1.0f / 16384.0f);
423#pragma unroll
424            for (int ks = 0; ks < CH / 16; ++ks) {
425                const int cA = ks * 16 + 2 * tig, cB = cA + 8;
426                const float w0 = S.vs[cA][vg] * vup, w1 = S.vs[cA + 1][vg] * vup, w2 = S.vs[cB][vg] * vup,
427                            w3 = S.vs[cB + 1][vg] * vup;
428                const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1;
429                const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1;
430                const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3;
431                const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3;
432                uint32_t ah[4], al[4];
433                ah[0] = pack_h2(p00, p01);
434                ah[1] = pack_h2(p10, p11);
435                ah[2] = pack_h2(p02, p03);
436                ah[3] = pack_h2(p12, p13);
437                {
438                    const __half2* h = reinterpret_cast<const __half2*>(ah);
439                    float2 f;
440                    f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);
441                    f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);
442                    f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);
443                    f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);
444                }
445#pragma unroll
446                for (int jj = 0; jj < JPG; ++jj) {
447                    const int j = gi * JPG + jj;
448                    const int d = warp * 64 + j * 8 + gid;
449                    uint32_t b[2];
450                    if constexpr (KV_MODE == 1 || KV_MODE == 4) {
451                        const uint32_t x0 = (uint8_t) S.kv.v[cA][d] | ((uint32_t) (uint8_t) S.kv.v[cA + 1][d] << 8);
452                        const uint32_t x1 = (uint8_t) S.kv.v[cB][d] | ((uint32_t) (uint8_t) S.kv.v[cB + 1][d] << 8);
453                        b[0] = i8x2_to_h2(x0);
454                        b[1] = i8x2_to_h2(x1);
455                    } else {
456                        const __half2 h0 = __halves2half2(S.kv.v[cA][d], S.kv.v[cA + 1][d]);
457                        const __half2 h1 = __halves2half2(S.kv.v[cB][d], S.kv.v[cB + 1][d]);
458                        b[0] = *reinterpret_cast<const uint32_t*>(&h0);
459                        b[1] = *reinterpret_cast<const uint32_t*>(&h1);
460                    }
461                    mma16816(tmp[j], ah, b);
462#ifndef D1_NO_PLO
463                    mma16816(tmp[j], al, b);
464#endif
465                }
466            }
467            }
468            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
469#pragma unroll
470            for (int j = 0; j < 8; ++j) {
471                const float vdown = vdown_g[j / JPG];
472                acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);
473                acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);
474                acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);
475                acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);
476            }
477        }
478    }
479    __syncthreads();
480    const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
481    const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
482#pragma unroll
483    for (int j = 0; j < 8; ++j) {
484        const int d = warp * 64 + j * 8 + 2 * tig;
485        *reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
486        if (gid + 8 < G)
487            *reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
488    }
489}
490
491// ---- v2 (int8 KV): warp w owns dims [64w, 64w+64) for both q.k and p.v, which is also int8 scale group w. So a
492// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own
493// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums
494// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic.
495constexpr int CH2 = 32;
496
497struct Smem2 {
498    int8_t kv[2][4][2][CH2][64];   // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell
499    float sc[2][4][2][CH2];        // stage, warp, K/V scale of the cell for the warp's group
500    float part[4][16][CH2 + 1];    // q.k per dim group
501    float p[16][CH2 + 1];
502    float qmax[4];
503    float alpha[16];
504    float lsum[16];
505    float mrow[16];
506};
507// Turing (register staging): one stage - the next chunk's pieces wait in registers until this chunk's p.v is done -
508// and the q.k partials of cell group nt (8 cells) in the 512 bytes of the warp's own K slice that held those cells
509// (read by then), so a block takes ~19.7 KB and three fit a Turing SM (one did, at 45.6 KB: four warps on four
510// schedulers, every latency exposed)
511struct Smem2T {
512    int8_t kv[1][4][2][CH2][64];
513    float sc[1][4][2][CH2];
514    float p[16][CH2 + 1];
515    float qmax[4];
516    float alpha[16];
517    float lsum[16];
518    float mrow[16];
519};
520
521__device__ __forceinline__ int swz(int cell, int byte) {   // byte offset of (cell, byte) in a stage slice
522    return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15);
523}
524__device__ __forceinline__ void cp_async16(void* smem, const void* gmem, bool valid) {
525#if !STRATA_PA_SM80
526    (void) smem; (void) gmem; (void) valid;
527    __trap();   // not reached on Turing (the register-staged pipeline replaces it there)
528#else
529    const unsigned sa = (unsigned) __cvta_generic_to_shared(smem);
530    asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa), "l"(gmem), "r"(valid ? 16 : 0));
531#endif
532}
533__device__ __forceinline__ void cp_async_commit() {
534#if STRATA_PA_SM80
535    asm volatile("cp.async.commit_group;\n" ::);
536#endif
537}
538__device__ __forceinline__ void cp_async_wait1() {
539#if STRATA_PA_SM80
540    asm volatile("cp.async.wait_group 1;\n" ::);
541#endif
542}
543
544__global__ void __launch_bounds__(THREADS) prompt_attn_i8_kernel(const float* __restrict__ q, QsaAttnPools p,
545                                                                 const int32_t* __restrict__ ids,
546                                                                 const int32_t* __restrict__ steps, int n_kv_heads,
547                                                                 int page_size, float scale_log2,
548                                                                 float* __restrict__ attn, int cap) {
549    extern __shared__ __align__(16) unsigned char smem_raw[];
550#if STRATA_PA_SM80
551    Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);
552#define PA2_PART(w, r, c) S.part[w][r][c]
553#else
554    Smem2T& S = *reinterpret_cast<Smem2T*>(smem_raw);
555    // the partial of (row r, cell c) of warp w: cell group c / 8's 512 bytes of w's K slice, [row][cell % 8]
556#define PA2_PART(w, r, c) reinterpret_cast<const float*>(&S.kv[0][w][0][0][0])[((c) >> 3) * 128 + (r) * 8 + ((c) & 7)]
557#endif
558    const int qi = blockIdx.x, kvh = blockIdx.y;
559    const int n_head = n_kv_heads * G;
560    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
561    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
562    ids += (size_t) qi * cap;
563    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
564    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
565    const int gid = lane >> 2, tig = lane & 3;
566    const int dim0 = warp * 64;
567
568    // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments
569    float qm = 0.0f;
570    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
571#pragma unroll
572    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
573    if (lane == 0) S.qmax[warp] = qm;
574    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
575    __syncthreads();
576    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
577    int qe = 0;
578    if (qm > 0.0f) frexpf(qm, &qe);
579    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
580    uint32_t qh[4][4], ql[4][4];
581#pragma unroll
582    for (int kk = 0; kk < 4; ++kk) {
583#pragma unroll
584        for (int r = 0; r < 4; ++r) {
585            const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8;
586            float2 x = make_float2(0.f, 0.f);
587            if (row < G) x = *reinterpret_cast<const float2*>(q + (size_t) row * HD + col);
588            x.x *= qup;
589            x.y *= qup;
590            const __half2 hi = __floats2half2_rn(x.x, x.y);
591            const float2 hf = __half22float2(hi);
592            const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y);
593            qh[kk][r] = *reinterpret_cast<const uint32_t*>(&hi);
594            ql[kk][r] = *reinterpret_cast<const uint32_t*>(&lo);
595        }
596    }
597
598    // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead
599    const int n_chunks = (n + CH2 - 1) / CH2;
600    auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };
601    auto row_of = [&](int cell) -> long long {
602        if (cell < 0) return -1;
603        const long long page = (long long) __ldg(p.page_table + cell / page_size);
604        return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
605    };
606#if !STRATA_PA_SM80
607    // Turing (no cp.async): the warp's next pieces wait in registers and are stored into their stage after this
608    // chunk's p.v (store_stage) - the same bytes in the same places as the cp.async pipeline
609    uint4 rk[4], rv[4];
610    auto store_stage = [&](int st) {
611#pragma unroll
612        for (int j = 0; j < 4; ++j) {
613            const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
614            *reinterpret_cast<uint4*>(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16)) = rk[j];
615            *reinterpret_cast<uint4*>(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16)) = rv[j];
616        }
617    };
618#endif
619    auto issue = [&](long long r, int st, float& ksr, float& vsr) {
620#pragma unroll
621        for (int j = 0; j < 4; ++j) {
622            const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
623            const long long rr = __shfl_sync(0xffffffffu, r, cell);
624            const bool ok = rr >= 0;
625            const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
626#if STRATA_PA_SM80
627            cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);
628            cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);
629#else
630            (void) st;
631            rk[j] = ok ? __ldg(reinterpret_cast<const uint4*>(p.k_q + off)) : make_uint4(0, 0, 0, 0);
632            rv[j] = ok ? __ldg(reinterpret_cast<const uint4*>(p.v_q + off)) : make_uint4(0, 0, 0, 0);
633#endif
634        }
635        ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
636        vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
637    };
638    float ksn, vsn;
639    issue(row_of(cell_of(lane)), 0, ksn, vsn);
640    cp_async_commit();
641#if !STRATA_PA_SM80
642    store_stage(0);
643#endif
644    S.sc[0][warp][0][lane] = ksn;
645    S.sc[0][warp][1][lane] = vsn;
646    long long r_next = row_of(cell_of(CH2 + lane));
647    int cell_next2 = cell_of(2 * CH2 + lane);
648
649    float acc[8][4];
650#pragma unroll
651    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
652
653    for (int ci = 0; ci < n_chunks; ++ci) {
654#if STRATA_PA_SM80
655        const int st = ci & 1, nst = st ^ 1, c0 = ci * CH2;
656#else
657        const int st = 0, nst = 0, c0 = ci * CH2;
658#endif
659        const bool more = ci + 1 < n_chunks;
660        if (more) issue(r_next, nst, ksn, vsn);
661        cp_async_commit();
662        r_next = row_of(cell_next2);
663        cell_next2 = cell_of((ci + 3) * CH2 + lane);
664        cp_async_wait1();
665        __syncwarp();
666        const int8_t* K = &S.kv[st][warp][0][0][0];
667        const int8_t* V = &S.kv[st][warp][1][0][0];
668        // q.k over this warp's 64 dims, times the cell's K scale for this group
669#pragma unroll
670        for (int nt = 0; nt < CH2 / 8; ++nt) {
671            float tg[4] = {0.f, 0.f, 0.f, 0.f};
672            const int cell = nt * 8 + gid;
673#pragma unroll
674            for (int kk = 0; kk < 4; ++kk) {
675                uint32_t b[2];
676                b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig)));
677                b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig + 8)));
678                mma16816(tg, qh[kk], b);
679                mma16816(tg, ql[kk], b);
680            }
681            const int c = nt * 8 + 2 * tig;
682            const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];
683#if STRATA_PA_SM80
684            S.part[warp][gid][c] = tg[0] * s0;
685            S.part[warp][gid][c + 1] = tg[1] * s1;
686            S.part[warp][gid + 8][c] = tg[2] * s0;
687            S.part[warp][gid + 8][c + 1] = tg[3] * s1;
688#else
689            __syncwarp();   // every lane has read the group's cells: their 512 bytes take its partials
690            float* pp = reinterpret_cast<float*>(&S.kv[0][warp][0][0][0]) + nt * 128;
691            pp[gid * 8 + 2 * tig] = tg[0] * s0;
692            pp[gid * 8 + 2 * tig + 1] = tg[1] * s1;
693            pp[(gid + 8) * 8 + 2 * tig] = tg[2] * s0;
694            pp[(gid + 8) * 8 + 2 * tig + 1] = tg[3] * s1;
695#endif
696        }
697        __syncthreads();
698        // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
699        {
700            const int r = t >> 3, sub = t & 7;
701            float x[4], mx = -INFINITY;
702#pragma unroll
703            for (int j = 0; j < 4; ++j) {
704                const int c = sub * 4 + j;
705                x[j] = c0 + c < n ? (((PA2_PART(0, r, c) + PA2_PART(1, r, c)) + PA2_PART(2, r, c)) + PA2_PART(3, r, c)) * qdown
706                                  : -INFINITY;
707                mx = fmaxf(mx, x[j]);
708            }
709#pragma unroll
710            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
711            const float m_old = S.mrow[r];
712            const float m_new = fmaxf(m_old, mx);
713            float sum = 0.0f;
714#pragma unroll
715            for (int j = 0; j < 4; ++j) {
716                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
717                S.p[r][sub * 4 + j] = e;
718                sum += e;
719            }
720#pragma unroll
721            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
722            __syncwarp();
723            if (sub == 0) {
724                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
725                S.alpha[r] = a;
726                S.lsum[r] = fmaf(S.lsum[r], a, sum);
727                S.mrow[r] = m_new;
728            }
729        }
730        __syncthreads();
731        // p.v over this warp's 64 dims (as v1)
732        {
733            float vmax = S.sc[st][warp][1][lane];
734#pragma unroll
735            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
736            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
737            float tmp[8][4];
738#pragma unroll
739            for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
740#pragma unroll
741            for (int ks = 0; ks < CH2 / 16; ++ks) {
742                const int cA = ks * 16 + 2 * tig, cB = cA + 8;
743                const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup,
744                            w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup;
745                const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1;
746                const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1;
747                const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3;
748                const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3;
749                uint32_t ah[4], al[4];
750                ah[0] = pack_h2(p00, p01);
751                ah[1] = pack_h2(p10, p11);
752                ah[2] = pack_h2(p02, p03);
753                ah[3] = pack_h2(p12, p13);
754                {
755                    const __half2* h = reinterpret_cast<const __half2*>(ah);
756                    float2 f;
757                    f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);
758                    f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);
759                    f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);
760                    f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);
761                }
762#pragma unroll
763                for (int j = 0; j < 8; ++j) {
764                    const int d = j * 8 + gid;
765                    const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8);
766                    const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8);
767                    uint32_t b[2];
768                    b[0] = i8x2_to_h2(x0);
769                    b[1] = i8x2_to_h2(x1);
770                    mma16816(tmp[j], ah, b);
771                    mma16816(tmp[j], al, b);
772                }
773            }
774            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
775#pragma unroll
776            for (int j = 0; j < 8; ++j) {
777                acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);
778                acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);
779                acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);
780                acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);
781            }
782        }
783        if (more) {
784            S.sc[nst][warp][0][lane] = ksn;
785            S.sc[nst][warp][1][lane] = vsn;
786#if !STRATA_PA_SM80
787            store_stage(nst);
788#endif
789        }
790        __syncwarp();
791    }
792    __syncthreads();
793    const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
794    const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
795#pragma unroll
796    for (int j = 0; j < 8; ++j) {
797        const int d = dim0 + j * 8 + 2 * tig;
798        *reinterpret_cast<float2*>(attn + (size_t) gid * HD + d) = make_float2(acc[j][0] * i0, acc[j][1] * i0);
799        if (gid + 8 < G)
800            *reinterpret_cast<float2*>(attn + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2] * i1, acc[j][3] * i1);
801    }
802}
803
804#undef PA2_PART
805__global__ void __launch_bounds__(THREADS) decode_attn_i8_split_kernel(const float* __restrict__ q, QsaAttnPools p,
806                                                                 const int32_t* __restrict__ ids,
807                                                                 const int32_t* __restrict__ steps, int n_kv_heads,
808                                                                 int page_size, float scale_log2,
809                                                                 float* __restrict__ part, int cap) {
810    extern __shared__ __align__(16) unsigned char smem_raw[];
811    Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);
812    const int qi = blockIdx.x, kvh = blockIdx.y, sp = blockIdx.z, nsp = gridDim.z;
813    const int n_head = n_kv_heads * G;
814    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
815    // partials of (query, split): acc [n_head][HD] unnormalized, then m / l [n_head][2]
816    float* pacc = part + (size_t) (qi * nsp + sp) * n_head * (HD + 2) + (size_t) kvh * G * HD;
817    float* pml = part + (size_t) (qi * nsp + sp) * n_head * (HD + 2) + (size_t) n_head * HD + (size_t) kvh * G * 2;
818    ids += (size_t) qi * cap;
819    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
820    // this split's chunks: [ci0, ci1) of the query's ceil(n / CH2)
821    const int n_all = (n + CH2 - 1) / CH2, per = (n_all + nsp - 1) / nsp;
822    const int ci0 = sp * per, ci1 = min(n_all, ci0 + per);
823    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
824    const int gid = lane >> 2, tig = lane & 3;
825    const int dim0 = warp * 64;
826
827    // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments
828    float qm = 0.0f;
829    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
830#pragma unroll
831    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
832    if (lane == 0) S.qmax[warp] = qm;
833    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
834    __syncthreads();
835    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
836    int qe = 0;
837    if (qm > 0.0f) frexpf(qm, &qe);
838    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
839    uint32_t qh[4][4], ql[4][4];
840#pragma unroll
841    for (int kk = 0; kk < 4; ++kk) {
842#pragma unroll
843        for (int r = 0; r < 4; ++r) {
844            const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8;
845            float2 x = make_float2(0.f, 0.f);
846            if (row < G) x = *reinterpret_cast<const float2*>(q + (size_t) row * HD + col);
847            x.x *= qup;
848            x.y *= qup;
849            const __half2 hi = __floats2half2_rn(x.x, x.y);
850            const float2 hf = __half22float2(hi);
851            const __half2 lo = __floats2half2_rn(x.x - hf.x, x.y - hf.y);
852            qh[kk][r] = *reinterpret_cast<const uint32_t*>(&hi);
853            ql[kk][r] = *reinterpret_cast<const uint32_t*>(&lo);
854        }
855    }
856
857    if (ci0 >= ci1) {   // an empty split: m = -inf, l = 0, acc = 0
858        for (int i = t; i < G * HD; i += THREADS) pacc[(size_t) (i / HD) * HD + i % HD] = 0.0f;
859        if (t < G) { pml[2 * t] = -INFINITY; pml[2 * t + 1] = 0.0f; }
860        return;
861    }
862    // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead
863    auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };
864    auto row_of = [&](int cell) -> long long {
865        if (cell < 0) return -1;
866        const long long page = (long long) __ldg(p.page_table + cell / page_size);
867        return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
868    };
869    auto issue = [&](long long r, int st, float& ksr, float& vsr) {
870#pragma unroll
871        for (int j = 0; j < 4; ++j) {
872            const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
873            const long long rr = __shfl_sync(0xffffffffu, r, cell);
874            const bool ok = rr >= 0;
875            const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
876            cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);
877            cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);
878        }
879        ksr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.k_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
880        vsr = r >= 0 ? __half2float(__ushort_as_half(__ldg(p.v_scale + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
881    };
882    float ksn, vsn;
883    issue(row_of(cell_of(ci0 * CH2 + lane)), 0, ksn, vsn);
884    cp_async_commit();
885    S.sc[0][warp][0][lane] = ksn;
886    S.sc[0][warp][1][lane] = vsn;
887    long long r_next = row_of(cell_of((ci0 + 1) * CH2 + lane));
888    int cell_next2 = cell_of((ci0 + 2) * CH2 + lane);
889
890    float acc[8][4];
891#pragma unroll
892    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
893
894    for (int ci = ci0; ci < ci1; ++ci) {
895        const int st = (ci - ci0) & 1, c0 = ci * CH2;
896        const bool more = ci + 1 < ci1;
897        if (more) issue(r_next, st ^ 1, ksn, vsn);
898        cp_async_commit();
899        r_next = row_of(cell_next2);
900        cell_next2 = cell_of((ci + 3) * CH2 + lane);
901        cp_async_wait1();
902        __syncwarp();
903        const int8_t* K = &S.kv[st][warp][0][0][0];
904        const int8_t* V = &S.kv[st][warp][1][0][0];
905        // q.k over this warp's 64 dims, times the cell's K scale for this group
906#pragma unroll
907        for (int nt = 0; nt < CH2 / 8; ++nt) {
908            float tg[4] = {0.f, 0.f, 0.f, 0.f};
909            const int cell = nt * 8 + gid;
910#pragma unroll
911            for (int kk = 0; kk < 4; ++kk) {
912                uint32_t b[2];
913                b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig)));
914                b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig + 8)));
915                mma16816(tg, qh[kk], b);
916                mma16816(tg, ql[kk], b);
917            }
918            const int c = nt * 8 + 2 * tig;
919            const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];
920            S.part[warp][gid][c] = tg[0] * s0;
921            S.part[warp][gid][c + 1] = tg[1] * s1;
922            S.part[warp][gid + 8][c] = tg[2] * s0;
923            S.part[warp][gid + 8][c + 1] = tg[3] * s1;
924        }
925        __syncthreads();
926        // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
927        {
928            const int r = t >> 3, sub = t & 7;
929            float x[4], mx = -INFINITY;
930#pragma unroll
931            for (int j = 0; j < 4; ++j) {
932                const int c = sub * 4 + j;
933                x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown
934                                  : -INFINITY;
935                mx = fmaxf(mx, x[j]);
936            }
937#pragma unroll
938            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
939            const float m_old = S.mrow[r];
940            const float m_new = fmaxf(m_old, mx);
941            float sum = 0.0f;
942#pragma unroll
943            for (int j = 0; j < 4; ++j) {
944                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
945                S.p[r][sub * 4 + j] = e;
946                sum += e;
947            }
948#pragma unroll
949            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
950            __syncwarp();
951            if (sub == 0) {
952                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
953                S.alpha[r] = a;
954                S.lsum[r] = fmaf(S.lsum[r], a, sum);
955                S.mrow[r] = m_new;
956            }
957        }
958        __syncthreads();
959        // p.v over this warp's 64 dims (as v1)
960        {
961            float vmax = S.sc[st][warp][1][lane];
962#pragma unroll
963            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
964            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
965            float tmp[8][4];
966#pragma unroll
967            for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
968#pragma unroll
969            for (int ks = 0; ks < CH2 / 16; ++ks) {
970                const int cA = ks * 16 + 2 * tig, cB = cA + 8;
971                const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup,
972                            w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup;
973                const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1;
974                const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1;
975                const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3;
976                const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3;
977                uint32_t ah[4], al[4];
978                ah[0] = pack_h2(p00, p01);
979                ah[1] = pack_h2(p10, p11);
980                ah[2] = pack_h2(p02, p03);
981                ah[3] = pack_h2(p12, p13);
982                {
983                    const __half2* h = reinterpret_cast<const __half2*>(ah);
984                    float2 f;
985                    f = __half22float2(h[0]); al[0] = pack_h2(p00 - f.x, p01 - f.y);
986                    f = __half22float2(h[1]); al[1] = pack_h2(p10 - f.x, p11 - f.y);
987                    f = __half22float2(h[2]); al[2] = pack_h2(p02 - f.x, p03 - f.y);
988                    f = __half22float2(h[3]); al[3] = pack_h2(p12 - f.x, p13 - f.y);
989                }
990#pragma unroll
991                for (int j = 0; j < 8; ++j) {
992                    const int d = j * 8 + gid;
993                    const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8);
994                    const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8);
995                    uint32_t b[2];
996                    b[0] = i8x2_to_h2(x0);
997                    b[1] = i8x2_to_h2(x1);
998                    mma16816(tmp[j], ah, b);
999                    mma16816(tmp[j], al, b);
1000                }
1001            }
1002            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
1003#pragma unroll
1004            for (int j = 0; j < 8; ++j) {
1005                acc[j][0] = fmaf(acc[j][0], a0, tmp[j][0] * vdown);
1006                acc[j][1] = fmaf(acc[j][1], a0, tmp[j][1] * vdown);
1007                acc[j][2] = fmaf(acc[j][2], a1, tmp[j][2] * vdown);
1008                acc[j][3] = fmaf(acc[j][3], a1, tmp[j][3] * vdown);
1009            }
1010        }
1011        if (more) {
1012            S.sc[st ^ 1][warp][0][lane] = ksn;
1013            S.sc[st ^ 1][warp][1][lane] = vsn;
1014        }
1015        __syncwarp();
1016    }
1017    __syncthreads();
1018    // the split's unnormalized sums and each head row's maximum and sum (the merge rescales and divides)
1019#pragma unroll
1020    for (int j = 0; j < 8; ++j) {
1021        const int d = dim0 + j * 8 + 2 * tig;
1022        *reinterpret_cast<float2*>(pacc + (size_t) gid * HD + d) = make_float2(acc[j][0], acc[j][1]);
1023        if (gid + 8 < G)
1024            *reinterpret_cast<float2*>(pacc + (size_t) (gid + 8) * HD + d) = make_float2(acc[j][2], acc[j][3]);
1025    }
1026    if (t < G) { pml[2 * t] = S.mrow[t]; pml[2 * t + 1] = S.lsum[t]; }
1027}
1028
1029// the splits of each (query, head) merged with the log-sum-exp rescale (base 2, as the kernel's online softmax), in
1030// split order; a block per (query, head), a thread per dimension
1031__global__ void __launch_bounds__(HD) decode_attn_merge_kernel(const float* __restrict__ part, int n_head, int nsp,
1032                                                               float* __restrict__ attn) {
1033    const int qi = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
1034    const size_t qs = (size_t) qi * nsp * n_head * (HD + 2);
1035    float M = -INFINITY;
1036    for (int s = 0; s < nsp; ++s) M = fmaxf(M, part[qs + (size_t) s * n_head * (HD + 2) + (size_t) n_head * HD + 2 * h]);
1037    float L = 0.0f, o = 0.0f;
1038    for (int s = 0; s < nsp; ++s) {
1039        const float* ps = part + qs + (size_t) s * n_head * (HD + 2);
1040        const float m = ps[(size_t) n_head * HD + 2 * h], l = ps[(size_t) n_head * HD + 2 * h + 1];
1041        const float w = m == -INFINITY ? 0.0f : exp2f(m - M);
1042        L = fmaf(l, w, L);
1043        o = fmaf(ps[(size_t) h * HD + d], w, o);
1044    }
1045    attn[((size_t) qi * n_head + h) * HD + d] = L > 0.0f ? o * (1.0f / L) : 0.0f;
1046}
1047
1048
1049
1050bool launch_i8(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1051               const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1052    static bool attr[64] = {};   // the shared-memory opt-in is per device (a layer split runs this on several)
1053    static int t75[64] = {};     // 1: Turing (the kernel's single-stage layout, Smem2T), 2: not
1054    int dev = 0;
1055    cudaGetDevice(&dev);
1056    if (dev < 0 || dev >= 64) return false;
1057    if (!t75[dev]) {
1058        int major = 0;
1059        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
1060        t75[dev] = strata::cc_major_of(major) < 8 ? 1 : 2;   // STRATA_EMULATE_CC counts
1061    }
1062    const int bytes = (int) (t75[dev] == 1 ? sizeof(Smem2T) : sizeof(Smem2));
1063    if (!attr[dev]) {
1064        if (cudaFuncSetAttribute(prompt_attn_i8_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
1065            cudaSuccess) {
1066            cudaGetLastError();
1067            return false;
1068        }
1069        attr[dev] = true;
1070    }
1071    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1072    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1073        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1074        prompt_attn_i8_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
1075            q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1076            (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1077    }
1078    const cudaError_t e = cudaGetLastError();
1079    if (e != cudaSuccess) {
1080        std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));
1081        std::exit(1);
1082    }
1083    return true;
1084}
1085
1086// ---- v3 (int8 KV, opt-in STRATA_PROMPT_ATTN_IMMA=1): v2's block, pipeline and online softmax, with both products on
1087// INT8 tensor cores (mma m16n8k32 s8, int32 accumulation).  K and V enter as the int8 codes they are - no int8 -> fp16
1088// conversion - and the other operand as THREE 8-bit parts: q per (head, 64-dim group) and p * v_scale per (head, chunk)
1089// scaled to 127, then X = rint(x * 65536) split exactly into h (signed), l (signed) and m (unsigned) bytes - 24 bits,
1090// as fine as FP32 itself and finer than the FP16 hi + lo split v2 uses (~22 bits).  Each part's int32 sum is exact; the three meet in
1091// FP32 as h + (l * 256 + m) / 65536 (m unsigned: a u8 x s8 MMA).  INT8 MMA runs ~3.1x FP16's rate on sm_120 (732 vs 233 measured), so three INT8
1092// MMAs cost about one FP16 MMA where v2 spends two.  p.v takes each thread's 8 consecutive dims across the 8 n-tiles
1093// (n-tile j, column n = dim n * 8 + j), so a thread reads 8 bytes of a V row per cell and byte-transposes 4 cells.
1094__device__ __forceinline__ void imma16832(int* c, const uint32_t* a, const uint32_t* b) {
1095#if !STRATA_PA_SM80
1096    __trap();
1097#else
1098    asm volatile("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
1099                 "{%0,%1,%2,%3};\n"
1100                 : "+r"(c[0]), "+r"(c[1]), "+r"(c[2]), "+r"(c[3])
1101                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
1102#endif
1103}
1104// the low part's MMA: unsigned A (m in 0..255), signed B
1105__device__ __forceinline__ void imma16832_us(int* c, const uint32_t* a, const uint32_t* b) {
1106#if !STRATA_PA_SM80
1107    __trap();
1108#else
1109    asm volatile("mma.sync.aligned.m16n8k32.row.col.s32.u8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
1110                 "{%0,%1,%2,%3};\n"
1111                 : "+r"(c[0]), "+r"(c[1]), "+r"(c[2]), "+r"(c[3])
1112                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
1113#endif
1114}
1115// x (|x| <= 127) as X = rint(x * 65536) = h * 65536 + l * 256 + m exactly: h, l signed bytes, m an unsigned one
1116__device__ __forceinline__ void split3(float x, int& h, int& l, int& m) {
1117    const int X = __float2int_rn(x * 65536.0f);
1118    h = (X + 32768) >> 16;
1119    const int r = X - (h << 16);   // -32768 .. 32767
1120    l = r >> 8;                    // -128 .. 127
1121    m = r & 255;                   // 0 .. 255
1122}
1123__device__ __forceinline__ uint32_t pack4(int a, int b, int c, int d) {
1124    return (uint32_t) (a & 0xff) | ((uint32_t) (b & 0xff) << 8) | ((uint32_t) (c & 0xff) << 16) | ((uint32_t) (d & 0xff) << 24);
1125}
1126__device__ __forceinline__ float join3(int h, int l, int m) {   // the parts' exact int32 sums -> h + (l*256 + m)/65536
1127    return (float) h + (float) ((l << 8) + m) * (1.0f / 65536.0f);
1128}
1129// four words of four bytes each (word i = cell i) -> four words of the same byte position across the cells
1130__device__ __forceinline__ void tr4x4(uint32_t w0, uint32_t w1, uint32_t w2, uint32_t w3, uint32_t* o) {
1131    const uint32_t t0 = __byte_perm(w0, w1, 0x5140), t1 = __byte_perm(w0, w1, 0x7362);
1132    const uint32_t t2 = __byte_perm(w2, w3, 0x5140), t3 = __byte_perm(w2, w3, 0x7362);
1133    o[0] = __byte_perm(t0, t2, 0x5410);
1134    o[1] = __byte_perm(t0, t2, 0x7632);
1135    o[2] = __byte_perm(t1, t3, 0x5410);
1136    o[3] = __byte_perm(t1, t3, 0x7632);
1137}
1138
1139// v3's shared memory: ONE stage of K and one of V per warp (a warp gathers and reads only its own 64-dim slices, so
1140// reusing a buffer needs only that warp's own order): K(c + 1) is gathered while the block runs softmax(c) and
1141// p.v(c), V(c + 1) while it runs q.k(c + 1) and softmax(c + 1); and only the 12 real head rows of the partial sums
1142// and p.  25.5 KB instead of v2's 45.6 KB: three blocks an SM instead of two (one block an SM ran 1.54x slower than
1143// two - this kernel waits on latency, not on its MMAs).
1144struct Smem3 {
1145    int8_t kv[4][2][CH2][64];   // warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell
1146    float sc[4][2][CH2];        // warp, K/V scale of the cell for the warp's group
1147    float part[4][G][CH2 + 1];  // q.k per dim group (the 12 head rows)
1148    float p[G][CH2 + 1];
1149    float alpha[16];
1150    float lsum[16];
1151    float mrow[16];
1152};
1153
1154__global__ void __launch_bounds__(THREADS, 3) prompt_attn_i8v3_kernel(const float* __restrict__ q, QsaAttnPools p,
1155                                                                      const int32_t* __restrict__ ids,
1156                                                                      const int32_t* __restrict__ steps, int n_kv_heads,
1157                                                                      int page_size, float scale_log2,
1158                                                                      float* __restrict__ attn, int cap) {
1159    extern __shared__ __align__(16) unsigned char smem_raw[];
1160    Smem3& S = *reinterpret_cast<Smem3*>(smem_raw);
1161    const int qi = blockIdx.x, kvh = blockIdx.y;
1162    const int n_head = n_kv_heads * G;
1163    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1164    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1165    ids += (size_t) qi * cap;
1166    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
1167    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1168    const int gid = lane >> 2, tig = lane & 3;
1169    const int dim0 = warp * 64;
1170    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; S.alpha[t] = 0.0f; }
1171
1172    // q: rows gid / gid + 8 (heads; 12..15 are pad), this warp's 64 dims as the A fragments of two k-steps of 32,
1173    // three 8-bit parts with a scale per (row, 64-dim group)
1174    uint32_t qa[3][2][4];
1175    float qinv[2];
1176    {
1177        float x[2][2][2][4];   // [row half][k-step][k half][4 dims]
1178        float mx[2] = {0.0f, 0.0f};
1179#pragma unroll
1180        for (int rh = 0; rh < 2; ++rh) {
1181            const int row = gid + rh * 8;
1182#pragma unroll
1183            for (int ks = 0; ks < 2; ++ks)
1184#pragma unroll
1185                for (int kh = 0; kh < 2; ++kh) {
1186                    float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
1187                    if (row < G) v = *reinterpret_cast<const float4*>(q + (size_t) row * HD + dim0 + ks * 32 + kh * 16 + tig * 4);
1188                    x[rh][ks][kh][0] = v.x; x[rh][ks][kh][1] = v.y; x[rh][ks][kh][2] = v.z; x[rh][ks][kh][3] = v.w;
1189                    mx[rh] = fmaxf(mx[rh], fmaxf(fmaxf(fabsf(v.x), fabsf(v.y)), fmaxf(fabsf(v.z), fabsf(v.w))));
1190                }
1191#pragma unroll
1192            for (int o = 1; o < 4; o <<= 1) mx[rh] = fmaxf(mx[rh], __shfl_xor_sync(0xffffffffu, mx[rh], o));
1193        }
1194        float up[2];
1195#pragma unroll
1196        for (int rh = 0; rh < 2; ++rh) {
1197            up[rh] = mx[rh] > 0.0f ? 127.0f / mx[rh] : 0.0f;
1198            qinv[rh] = mx[rh] * (1.0f / 127.0f);
1199        }
1200#pragma unroll
1201        for (int ks = 0; ks < 2; ++ks)
1202#pragma unroll
1203            for (int r = 0; r < 4; ++r) {   // a0: row gid, k 0..15 half; a1: row gid + 8; a2: row gid, k 16..31; a3
1204                const int rh = r & 1, kh = r >> 1;
1205                int hh[4], ll[4], mm[4];
1206#pragma unroll
1207                for (int e = 0; e < 4; ++e) split3(x[rh][ks][kh][e] * up[rh], hh[e], ll[e], mm[e]);
1208                qa[0][ks][r] = pack4(hh[0], hh[1], hh[2], hh[3]);
1209                qa[1][ks][r] = pack4(ll[0], ll[1], ll[2], ll[3]);
1210                qa[2][ks][r] = pack4(mm[0], mm[1], mm[2], mm[3]);
1211            }
1212    }
1213
1214    const int n_chunks = (n + CH2 - 1) / CH2;
1215    auto cell_of = [&](int c) -> int { return c < n ? __ldg(ids + c) : -1; };
1216    auto row_of = [&](int cell) -> long long {
1217        if (cell < 0) return -1;
1218        const long long page = (long long) __ldg(p.page_table + cell / page_size);
1219        return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1220    };
1221    // this warp's 64-dim slice of K (kv = 0) or V (1) of the chunk whose rows the lanes hold, and the cells' scales
1222    auto issue = [&](long long r, int kv) {
1223        const int8_t* pool = kv == 0 ? p.k_q : p.v_q;
1224#pragma unroll
1225        for (int j = 0; j < 4; ++j) {
1226            const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
1227            const long long rr = __shfl_sync(0xffffffffu, r, cell);
1228            const bool ok = rr >= 0;
1229            const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
1230            cp_async16(&S.kv[warp][kv][0][0] + swz(cell, pc * 16), pool + off, ok);
1231        }
1232        const uint16_t* sc = kv == 0 ? p.k_scale : p.v_scale;
1233        S.sc[warp][kv][lane] = r >= 0 ? __half2float(__ushort_as_half(__ldg(sc + r * (HD / KV_Q8_GROUP) + warp))) : 0.0f;
1234    };
1235    long long r_nxt = row_of(cell_of(lane));   // chunk 0
1236    issue(r_nxt, 0);
1237    cp_async_commit();
1238    issue(r_nxt, 1);
1239    cp_async_commit();
1240    r_nxt = row_of(cell_of(CH2 + lane));       // chunk 1
1241    int cell_nn = cell_of(2 * CH2 + lane);     // chunk 2
1242    __syncthreads();
1243
1244    float acc[8][4];
1245#pragma unroll
1246    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
1247    const int8_t* K = &S.kv[warp][0][0][0];
1248    const int8_t* V = &S.kv[warp][1][0][0];
1249
1250    for (int ci = 0; ci < n_chunks; ++ci) {
1251        const int c0 = ci * CH2;
1252        const bool more = ci + 1 < n_chunks;
1253        cp_async_wait1();   // K(ci) is in (pending: V(ci))
1254        __syncwarp();
1255        // q.k over this warp's 64 dims: n-tile nt holds cells nt * 8 .. + 7 (column n = cell nt * 8 + n)
1256#pragma unroll
1257        for (int nt = 0; nt < CH2 / 8; ++nt) {
1258            int ch[4] = {0, 0, 0, 0}, cl[4] = {0, 0, 0, 0}, cm[4] = {0, 0, 0, 0};
1259            const int cell = nt * 8 + gid;
1260#pragma unroll
1261            for (int ks = 0; ks < 2; ++ks) {
1262                uint32_t b[2];
1263                b[0] = *reinterpret_cast<const uint32_t*>(K + swz(cell, ks * 32 + tig * 4));
1264                b[1] = *reinterpret_cast<const uint32_t*>(K + swz(cell, ks * 32 + 16 + tig * 4));
1265                imma16832(ch, qa[0][ks], b);
1266                imma16832(cl, qa[1][ks], b);
1267                imma16832_us(cm, qa[2][ks], b);
1268            }
1269            const int c = nt * 8 + 2 * tig;
1270            const float s0 = S.sc[warp][0][c], s1 = S.sc[warp][0][c + 1];
1271            S.part[warp][gid][c] = join3(ch[0], cl[0], cm[0]) * qinv[0] * s0;
1272            S.part[warp][gid][c + 1] = join3(ch[1], cl[1], cm[1]) * qinv[0] * s1;
1273            if (gid + 8 < G) {
1274                S.part[warp][gid + 8][c] = join3(ch[2], cl[2], cm[2]) * qinv[1] * s0;
1275                S.part[warp][gid + 8][c + 1] = join3(ch[3], cl[3], cm[3]) * qinv[1] * s1;
1276            }
1277        }
1278        __syncwarp();   // every lane has read K(ci) and its scales
1279        if (more) issue(r_nxt, 0);
1280        cp_async_commit();
1281        __syncthreads();
1282        // online softmax over the four groups' sum (fixed order): rows 0..11, 8 threads a row (warp 3 idles)
1283        if (t < G * 8) {
1284            const int r = t >> 3, sub = t & 7;
1285            float x[4], mx = -INFINITY;
1286#pragma unroll
1287            for (int j = 0; j < 4; ++j) {
1288                const int c = sub * 4 + j;
1289                x[j] = c0 + c < n ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * scale_log2
1290                                  : -INFINITY;
1291                mx = fmaxf(mx, x[j]);
1292            }
1293#pragma unroll
1294            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
1295            const float m_old = S.mrow[r];
1296            const float m_new = fmaxf(m_old, mx);
1297            float sum = 0.0f;
1298#pragma unroll
1299            for (int j = 0; j < 4; ++j) {
1300                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
1301                S.p[r][sub * 4 + j] = e;
1302                sum += e;
1303            }
1304#pragma unroll
1305            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
1306            __syncwarp();
1307            if (sub == 0) {
1308                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
1309                S.alpha[r] = a;
1310                S.lsum[r] = fmaf(S.lsum[r], a, sum);
1311                S.mrow[r] = m_new;
1312            }
1313        }
1314        __syncthreads();
1315        cp_async_wait1();   // V(ci) is in (pending: K(ci + 1))
1316        __syncwarp();
1317        // p.v over this warp's 64 dims: A = p * v_scale (rows gid / gid + 8, k = the chunk's 32 cells) in three parts
1318        // scaled per row; B = V (k = cells, n-tile j column n = dim n * 8 + j)
1319        {
1320            uint32_t pa[3][4];
1321            float pinv[2];
1322            {   // a scale per row: a chunk whose p are all small still gets its 24 bits (one per warp and chunk lost
1323                // ~3x of the accuracy against FP64)
1324                float a[4][4], mx[2] = {0.0f, 0.0f};
1325#pragma unroll
1326                for (int r = 0; r < 4; ++r) {   // a0: row gid, cells tig * 4 ..; a1: row gid + 8; a2 / a3: cells 16 + ...
1327                    const int row = gid + (r & 1) * 8, cb = (r >> 1) * 16 + tig * 4;
1328#pragma unroll
1329                    for (int e = 0; e < 4; ++e) {
1330                        a[r][e] = row < G ? S.p[row][cb + e] * S.sc[warp][1][cb + e] : 0.0f;
1331                        mx[r & 1] = fmaxf(mx[r & 1], a[r][e]);
1332                    }
1333                }
1334                float up[2];
1335#pragma unroll
1336                for (int rh = 0; rh < 2; ++rh) {
1337#pragma unroll
1338                    for (int o = 1; o < 4; o <<= 1) mx[rh] = fmaxf(mx[rh], __shfl_xor_sync(0xffffffffu, mx[rh], o));
1339                    up[rh] = mx[rh] > 0.0f ? 127.0f / mx[rh] : 0.0f;
1340                    pinv[rh] = mx[rh] * (1.0f / 127.0f);
1341                }
1342#pragma unroll
1343                for (int r = 0; r < 4; ++r) {
1344                    int hh[4], ll[4], mm[4];
1345#pragma unroll
1346                    for (int e = 0; e < 4; ++e) split3(a[r][e] * up[r & 1], hh[e], ll[e], mm[e]);
1347                    pa[0][r] = pack4(hh[0], hh[1], hh[2], hh[3]);
1348                    pa[1][r] = pack4(ll[0], ll[1], ll[2], ll[3]);
1349                    pa[2][r] = pack4(mm[0], mm[1], mm[2], mm[3]);
1350                }
1351            }
1352            // B: this thread's 8 dims (gid * 8 .. + 7) of cells tig * 4 .. + 3 (b0) and 16 + tig * 4 .. + 3 (b1)
1353            uint32_t bv[2][8];   // [k half][dim j]
1354#pragma unroll
1355            for (int kh = 0; kh < 2; ++kh) {
1356                uint32_t lo[4], hi[4];
1357#pragma unroll
1358                for (int e = 0; e < 4; ++e) {
1359                    const uint2 w = *reinterpret_cast<const uint2*>(V + swz(kh * 16 + tig * 4 + e, gid * 8));
1360                    lo[e] = w.x;
1361                    hi[e] = w.y;
1362                }
1363                tr4x4(lo[0], lo[1], lo[2], lo[3], &bv[kh][0]);
1364                tr4x4(hi[0], hi[1], hi[2], hi[3], &bv[kh][4]);
1365            }
1366            __syncwarp();   // every lane has read V(ci) and its scales
1367            if (more) issue(r_nxt, 1);
1368            cp_async_commit();
1369            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
1370#pragma unroll
1371            for (int j = 0; j < 8; ++j) {
1372                int ch[4] = {0, 0, 0, 0}, cl[4] = {0, 0, 0, 0}, cm[4] = {0, 0, 0, 0};
1373                const uint32_t b[2] = {bv[0][j], bv[1][j]};
1374                imma16832(ch, pa[0], b);
1375                imma16832(cl, pa[1], b);
1376                imma16832_us(cm, pa[2], b);
1377                acc[j][0] = fmaf(acc[j][0], a0, join3(ch[0], cl[0], cm[0]) * pinv[0]);
1378                acc[j][1] = fmaf(acc[j][1], a0, join3(ch[1], cl[1], cm[1]) * pinv[0]);
1379                acc[j][2] = fmaf(acc[j][2], a1, join3(ch[2], cl[2], cm[2]) * pinv[1]);
1380                acc[j][3] = fmaf(acc[j][3], a1, join3(ch[3], cl[3], cm[3]) * pinv[1]);
1381            }
1382        }
1383        r_nxt = row_of(cell_nn);
1384        cell_nn = cell_of((ci + 3) * CH2 + lane);
1385    }
1386    __syncthreads();
1387    const float l0 = S.lsum[gid], l1 = gid + 8 < G ? S.lsum[gid + 8] : 0.0f;
1388    const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
1389#pragma unroll
1390    for (int j = 0; j < 8; ++j) {   // column 2 * tig is dim 16 * tig + j, column 2 * tig + 1 dim 16 * tig + 8 + j
1391        const int d0 = dim0 + 16 * tig + j, d1 = d0 + 8;
1392        attn[(size_t) gid * HD + d0] = acc[j][0] * i0;
1393        attn[(size_t) gid * HD + d1] = acc[j][1] * i0;
1394        if (gid + 8 < G) {
1395            attn[(size_t) (gid + 8) * HD + d0] = acc[j][2] * i1;
1396            attn[(size_t) (gid + 8) * HD + d1] = acc[j][3] * i1;
1397        }
1398    }
1399}
1400
1401bool launch_i8v3(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1402                 const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1403    static bool attr[64] = {};
1404    int dev = 0;
1405    cudaGetDevice(&dev);
1406    const int bytes = (int) sizeof(Smem3);
1407    if (dev < 0 || dev >= 64) return false;
1408    if (!attr[dev]) {
1409        if (cudaFuncSetAttribute(prompt_attn_i8v3_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
1410            cudaSuccess) {
1411            cudaGetLastError();
1412            return false;
1413        }
1414        // the shared-memory side of the L1 split as large as it goes, so three blocks fit an SM
1415        cudaFuncSetAttribute(prompt_attn_i8v3_kernel, cudaFuncAttributePreferredSharedMemoryCarveout, 100);
1416        cudaGetLastError();
1417        attr[dev] = true;
1418    }
1419    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1420    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1421        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1422        prompt_attn_i8v3_kernel<<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
1423            q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1424            (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1425    }
1426    const cudaError_t e = cudaGetLastError();
1427    if (e != cudaSuccess) {
1428        std::fprintf(stderr, "qsa_prompt_attn_batch (v3): %s\n", cudaGetErrorString(e));
1429        std::exit(1);
1430    }
1431    return true;
1432}
1433
1434template <int KV_MODE, bool PF = false>
1435bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1436            const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1437    static bool attr[64] = {};   // per device, as above
1438    int dev = 0;
1439    cudaGetDevice(&dev);
1440    const int bytes = (int) sizeof(Smem<KV_MODE, PF>);
1441    if (dev < 0 || dev >= 64) return false;
1442    if (!attr[dev]) {
1443        if (cudaFuncSetAttribute(prompt_attn_kernel<KV_MODE, PF>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
1444            cudaSuccess) {
1445            cudaGetLastError();
1446            return false;
1447        }
1448        attr[dev] = true;
1449    }
1450    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1451    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1452        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1453        prompt_attn_kernel<KV_MODE, PF><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
1454            q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1455            (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1456    }
1457    const cudaError_t e = cudaGetLastError();
1458    if (e != cudaSuccess) {
1459        std::fprintf(stderr, "qsa_prompt_attn_batch: %s\n", cudaGetErrorString(e));
1460        std::exit(1);
1461    }
1462    return true;
1463}
1464
1465
1466// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a
1467// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before).
1468#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
1469// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------
1470// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per
1471// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on
1472// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two
1473// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1),
1474// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile.
1475//   q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps
1476//        of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the
1477//        cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic).
1478//   p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in
1479//        steps of 4; p carries the V scale (as v1) and is split into hi + lo halves.
1480#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750
1481#define STRATA_PA_VOLTA 1
1482#else
1483#define STRATA_PA_VOLTA 0
1484#endif
1485
1486__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) {
1487#if STRATA_PA_VOLTA
1488    asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, "
1489                 "{%0,%1,%2,%3,%4,%5,%6,%7};\n"
1490                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7])
1491                 : "r"(a0), "r"(a1), "r"(b0), "r"(b1));
1492#else
1493    __trap();   // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70
1494#endif
1495}
1496
1497template <int KV_MODE>
1498struct Smem70 {
1499    using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
1500    using VElem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;
1501    static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;
1502    static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;
1503    __half qh[16][QS];
1504    __half ql[16][QS];
1505    KElem k[CH][KROW];
1506    VElem v[CH][VROW];
1507    float ks[CH][4];
1508    float vs[CH][4];
1509    float part[4][16][CH + 4];   // q.k per dim group (scaled by the cell's K scale)
1510    float s[16][CH + 4];         // the chunk's probabilities
1511    float qmax[THREADS / 32];
1512    float alpha[16];
1513    float lsum[16];
1514    float mrow[16];
1515    long long row[2][CH];        // double-buffered pool rows: the next chunk's lookups hide under p.v
1516};
1517
1518template <int KV_MODE>
1519__global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* __restrict__ q, QsaAttnPools p,
1520                                                                  const int32_t* __restrict__ ids,
1521                                                                  const int32_t* __restrict__ steps, int n_kv_heads,
1522                                                                  int page_size, float scale_log2,
1523                                                                  float* __restrict__ attn, int cap) {
1524    extern __shared__ __align__(16) unsigned char smem_raw[];
1525    Smem70<KV_MODE>& S = *reinterpret_cast<Smem70<KV_MODE>*>(smem_raw);
1526    const int qi = blockIdx.x, kvh = blockIdx.y;
1527    const int n_head = n_kv_heads * G;
1528    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1529    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1530    ids += (size_t) qi * cap;
1531    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
1532    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1533    const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4);   // quad-pair, thread within it
1534    const int crow = (lane & 1) + 4 * (lane >> 4);                        // C row of register 0 (+2 per register pair)
1535    const int ccol = lane & 2;                                           // C column of register 0 (+4 per half, +1 per reg)
1536
1537    // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
1538    // lo halves stay out of FP16's subnormal range), then split into hi + lo halves
1539    float qm = 0.0f;
1540    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
1541#pragma unroll
1542    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
1543    if (lane == 0) S.qmax[warp] = qm;
1544    __syncthreads();
1545    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
1546    int qe = 0;
1547    if (qm > 0.0f) frexpf(qm, &qe);                 // qm < 2^qe
1548    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
1549    for (int i = t; i < 16 * HD; i += THREADS) {
1550        const int h = i / HD, d = i % HD;
1551        const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
1552        const __half hi = __float2half_rn(x);
1553        S.qh[h][d] = hi;
1554        S.ql[h][d] = __float2half_rn(x - __half2float(hi));
1555    }
1556    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
1557
1558    float acc[2][2][8];
1559#pragma unroll
1560    for (int rb = 0; rb < 2; ++rb)
1561#pragma unroll
1562        for (int nt = 0; nt < 2; ++nt)
1563#pragma unroll
1564            for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;
1565
1566    // the pool rows of a chunk: -1 past the selection and for a page the KV streaming left non-resident (the
1567    // decode kernel masks those, so this kernel does too).  Chunk 0's rows fill one buffer here; every later
1568    // chunk's lookups fill the other just before the previous p.v, where their global latency hides.
1569    int rbuf = 0;
1570    if (t < CH) {
1571        long long r = -1;
1572        if (t < min(CH, n)) {
1573            const int cell = ids[t];
1574            const long long page = (long long) p.page_table[cell / page_size];
1575            r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1576        }
1577        S.row[0][t] = r;
1578    }
1579    for (int c0 = 0; c0 < n; c0 += CH, rbuf ^= 1) {
1580        const int nh = min(CH, n - c0);
1581        __syncthreads();   // rows ready; the previous chunk's p.v is done with k, v
1582        // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
1583        // and their scales
1584        {
1585            constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16;   // per K row
1586            constexpr int KPT = (CH * KPIECES + THREADS - 1) / THREADS;
1587            static_assert((CH * KPIECES) % THREADS == 0, "the staging pieces divide evenly");
1588            // issue every global load of a thread before any of its stores: they then overlap each other instead
1589            // of paying the HBM latency one at a time
1590            uint4 kx[KPT];
1591            int kc[KPT], kp[KPT];
1592#pragma unroll
1593            for (int s = 0; s < KPT; ++s) {
1594                const int i = t + s * THREADS;
1595                kc[s] = i / KPIECES; kp[s] = i % KPIECES;
1596                const long long r = S.row[rbuf][kc[s]];
1597                kx[s] = make_uint4(0, 0, 0, 0);
1598                if (r >= 0) {
1599                    if constexpr (KV_MODE == 0)
1600                        kx[s] = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + kp[s]);
1601                    else   // modes 1 and 3: the K side is INT8
1602                        kx[s] = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + kp[s]);
1603                }
1604            }
1605#pragma unroll
1606            for (int s = 0; s < KPT; ++s)
1607                *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[kc[s]][0]) + kp[s] * 16) = kx[s];
1608            if constexpr (KV_MODE == 3) {   // V: dequantize the row's q4_0 blocks straight into the fp16 V row
1609                constexpr int BLKS = HD / QK4_0;
1610                constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
1611                for (int i = t; i < CH * BLKS; i += THREADS) {
1612                    const int c = i / BLKS, b = i % BLKS;
1613                    const long long r = S.row[rbuf][c];
1614#pragma unroll
1615                    for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);
1616                    if (r >= 0) {
1617                        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
1618                        const float d = __half2float(__ushort_as_half(blk->d));
1619#pragma unroll
1620                        for (int j = 0; j < QK4_0 / 2; ++j) {
1621                            S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
1622                            S.v[c][b * QK4_0 + j + QK4_0 / 2] =
1623                                __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
1624                        }
1625                    }
1626                }
1627            } else {
1628                constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16;   // per V row
1629                constexpr int VPT = (CH * VPIECES + THREADS - 1) / THREADS;
1630                static_assert((CH * VPIECES) % THREADS == 0, "the staging pieces divide evenly");
1631                uint4 vx[VPT];
1632                int vc[VPT], vp[VPT];
1633#pragma unroll
1634                for (int s = 0; s < VPT; ++s) {
1635                    const int i = t + s * THREADS;
1636                    vc[s] = i / VPIECES; vp[s] = i % VPIECES;
1637                    const long long r = S.row[rbuf][vc[s]];
1638                    vx[s] = make_uint4(0, 0, 0, 0);
1639                    if (r >= 0) {
1640                        if constexpr (KV_MODE == 1)
1641                            vx[s] = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + vp[s]);
1642                        else
1643                            vx[s] = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + vp[s]);
1644                    }
1645                }
1646#pragma unroll
1647                for (int s = 0; s < VPT; ++s)
1648                    *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[vc[s]][0]) + vp[s] * 16) = vx[s];
1649            }
1650            for (int i = t; i < CH * 4; i += THREADS) {
1651                const int c = i / 4, g = i % 4;
1652                const long long r = S.row[rbuf][c];
1653                float a = 0.0f, b = 0.0f;
1654                if (r >= 0) {
1655                    if constexpr (KV_MODE == 1) {
1656                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
1657                        b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
1658                    } else if constexpr (KV_MODE == 3) {   // K as int8, V dequantized to fp16 (scale 1)
1659                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
1660                        b = 1.0f;
1661                    } else {
1662                        a = b = 1.0f;
1663                    }
1664                }
1665                S.ks[c][g] = a;
1666                S.vs[c][g] = b;
1667            }
1668        }
1669        __syncthreads();
1670        // scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7. The hi and lo halves of q accumulate in
1671        // separate m8n8k4 chains (tg, tgl), added in FP32 at the end: Volta's tensor cores truncate as they
1672        // accumulate, and in one chain behind the hi products most of the lo half was lost (error vs FP64 at 32K
1673        // 5.1e-6 -> 2.3e-6, the FP32 kernel's level). The same for p.v below.
1674        {
1675            float tg[2][8], tgl[2][8];
1676#pragma unroll
1677            for (int rb = 0; rb < 2; ++rb)
1678#pragma unroll
1679                for (int i = 0; i < 8; ++i) tg[rb][i] = tgl[rb][i] = 0.0f;
1680            const int cell_b = qp * 8 + jj;
1681#pragma unroll
1682            for (int ks = 0; ks < 16; ++ks) {
1683                const int d0 = warp * 64 + ks * 4;
1684                uint32_t b0, b1;
1685                if constexpr (KV_MODE != 0) {   // modes 1 and 3: the K side is INT8 codes, exact in FP16
1686                    const uint32_t raw = *reinterpret_cast<const uint32_t*>(&S.k[cell_b][d0]);
1687                    b0 = i8x2_to_h2(raw & 0xffffu);
1688                    b1 = i8x2_to_h2(raw >> 16);
1689                } else {
1690                    const uint2 raw = *reinterpret_cast<const uint2*>(&S.k[cell_b][d0]);
1691                    b0 = raw.x;
1692                    b1 = raw.y;
1693                }
1694#pragma unroll
1695                for (int rb = 0; rb < 2; ++rb) {
1696                    const uint2 ah = *reinterpret_cast<const uint2*>(&S.qh[rb * 8 + jj][d0]);
1697                    const uint2 al = *reinterpret_cast<const uint2*>(&S.ql[rb * 8 + jj][d0]);
1698                    mma884(tg[rb], ah.x, ah.y, b0, b1);
1699                    mma884(tgl[rb], al.x, al.y, b0, b1);
1700                }
1701            }
1702#pragma unroll
1703            for (int rb = 0; rb < 2; ++rb)
1704#pragma unroll
1705                for (int i = 0; i < 8; ++i) {
1706                    const int row = rb * 8 + crow + 2 * ((i >> 1) & 1);
1707                    const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1);
1708                    S.part[warp][row][cell] = (tg[rb][i] + tgl[rb][i]) * S.ks[cell][warp];
1709                }
1710        }
1711        __syncthreads();
1712        // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
1713        {
1714            constexpr int PER = CH / 8;
1715            const int r = t >> 3, sub = t & 7;
1716            float x[PER], mx = -INFINITY;
1717#pragma unroll
1718            for (int j = 0; j < PER; ++j) {
1719                const int c = sub * PER + j;
1720                const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c];
1721                x[j] = c < nh ? sum4 * qdown : -INFINITY;
1722                mx = fmaxf(mx, x[j]);
1723            }
1724#pragma unroll
1725            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
1726            const float m_old = S.mrow[r];
1727            const float m_new = fmaxf(m_old, mx);
1728            float sum = 0.0f;
1729#pragma unroll
1730            for (int j = 0; j < PER; ++j) {
1731                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
1732                S.s[r][sub * PER + j] = e;
1733                sum += e;
1734            }
1735#pragma unroll
1736            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
1737            __syncwarp();
1738            if (sub == 0) {
1739                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
1740                S.alpha[r] = a;
1741                S.lsum[r] = fmaf(S.lsum[r], a, sum);
1742                S.mrow[r] = m_new;
1743            }
1744        }
1745        __syncthreads();
1746        __syncthreads();
1747        // p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded
1748        // into p relative to the chunk's largest, times 2^14 (as v1)
1749        {
1750            float vmax = 0.0f;
1751#pragma unroll
1752            for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);
1753#pragma unroll
1754            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
1755            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
1756            float tmp[2][2][8], tmpl[2][2][8];   // the hi and lo halves of p in separate chains (see the scores)
1757#pragma unroll
1758            for (int rb = 0; rb < 2; ++rb)
1759#pragma unroll
1760                for (int nt = 0; nt < 2; ++nt)
1761#pragma unroll
1762                    for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = tmpl[rb][nt][i] = 0.0f;
1763#pragma unroll
1764            for (int ks = 0; ks < CH / 4; ++ks) {
1765                const int c0 = ks * 4;
1766                float w[4];
1767#pragma unroll
1768                for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup;
1769                uint2 ah[2], al[2];
1770#pragma unroll
1771                for (int rb = 0; rb < 2; ++rb) {
1772                    const float4 pv = *reinterpret_cast<const float4*>(&S.s[rb * 8 + jj][c0]);
1773                    const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3];
1774                    ah[rb].x = pack_h2(p0, p1);
1775                    ah[rb].y = pack_h2(p2, p3);
1776                    const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].x));
1777                    const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].y));
1778                    al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y);
1779                    al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y);
1780                }
1781#pragma unroll
1782                for (int nt = 0; nt < 2; ++nt) {
1783                    const int d = warp * 64 + qp * 16 + nt * 8 + jj;
1784                    uint32_t b0, b1;
1785                    if constexpr (KV_MODE == 1) {
1786                        const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8);
1787                        const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8);
1788                        b0 = i8x2_to_h2(x0);
1789                        b1 = i8x2_to_h2(x1);
1790                    } else {
1791                        const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]);
1792                        const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]);
1793                        b0 = *reinterpret_cast<const uint32_t*>(&h0);
1794                        b1 = *reinterpret_cast<const uint32_t*>(&h1);
1795                    }
1796#pragma unroll
1797                    for (int rb = 0; rb < 2; ++rb) {
1798                        mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1);
1799                        mma884(tmpl[rb][nt], al[rb].x, al[rb].y, b0, b1);
1800                    }
1801                }
1802            }
1803#pragma unroll
1804            for (int rb = 0; rb < 2; ++rb) {
1805                float a_[2];
1806                a_[0] = S.alpha[rb * 8 + crow];
1807                a_[1] = S.alpha[rb * 8 + crow + 2];
1808#pragma unroll
1809                for (int nt = 0; nt < 2; ++nt)
1810#pragma unroll
1811                    for (int i = 0; i < 8; ++i)
1812                        acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], (tmp[rb][nt][i] + tmpl[rb][nt][i]) * vdown);
1813            }
1814        }
1815        // the next chunk's pool rows, into the other buffer: the two global lookups per cell hide under p.v
1816        if (c0 + CH < n && t < CH) {
1817            long long r = -1;
1818            const int idx = c0 + CH + t;
1819            if (idx < n) {
1820                const int cell = ids[idx];
1821                const long long page = (long long) p.page_table[cell / page_size];
1822                r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1823            }
1824            S.row[rbuf ^ 1][t] = r;
1825        }
1826    }
1827    __syncthreads();
1828#pragma unroll
1829    for (int rb = 0; rb < 2; ++rb)
1830#pragma unroll
1831        for (int h = 0; h < 2; ++h) {
1832            const int row = rb * 8 + crow + 2 * h;
1833            if (row >= G) continue;
1834            const float l = S.lsum[row];
1835            const float inv = l > 0.0f ? 1.0f / l : 0.0f;
1836#pragma unroll
1837            for (int nt = 0; nt < 2; ++nt)
1838#pragma unroll
1839                for (int hh = 0; hh < 2; ++hh) {
1840                    const int i = hh * 4 + h * 2;               // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1}
1841                    const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh;
1842                    *reinterpret_cast<float2*>(attn + (size_t) row * HD + d) =
1843                        make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv);
1844                }
1845        }
1846}
1847
1848template <int KV_MODE>
1849bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1850              const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1851    static bool attr[64] = {};
1852    int dev = 0;
1853    cudaGetDevice(&dev);
1854    const int bytes = (int) sizeof(Smem70<KV_MODE>);
1855    if (dev < 0 || dev >= 64) return false;
1856    if (!attr[dev]) {
1857        if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
1858            cudaSuccess) {
1859            cudaGetLastError();
1860            return false;
1861        }
1862        attr[dev] = true;
1863    }
1864    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1865    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1866        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1867        prompt_attn_v70_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
1868            q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1869            (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1870    }
1871    const cudaError_t e = cudaGetLastError();
1872    if (e != cudaSuccess) {
1873        std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e));
1874        std::exit(1);
1875    }
1876    return true;
1877}
1878#else   // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)
1879template <int KV_MODE>
1880bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*,
1881              int64_t, cudaStream_t) {
1882    return false;
1883}
1884#endif  // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60
1885
1886#if defined(__HIPCC__)
1887// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of
1888// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims
1889// [64w, 64w+64) (int8 scale group w) for q.k and p.v; q and p are split into FP16 hi + lo parts, the int8 codes enter
1890// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order.
1891// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order).
1892// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds
1893// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7.
1894// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of
1895// row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l all 16 k of column l % 16, and C/D lane l holds
1896// D[2 * i + l / 16][l % 16]. PA_KL is the k values per lane (8 or 16), PA_KOFF(half) the first one, PA_ROW the C row.
1897#if defined(__gfx1200__) || defined(__gfx1201__)
1898#define STRATA_PA_WMMA 1
1899#define STRATA_PA_GFX11 0
1900#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || \
1901    defined(__gfx1151__)
1902#define STRATA_PA_WMMA 1
1903#define STRATA_PA_GFX11 1
1904#else
1905#define STRATA_PA_WMMA 0
1906#define STRATA_PA_GFX11 0
1907#endif
1908#if STRATA_PA_GFX11
1909constexpr int PA_KL = 16;
1910#define PA_KOFF(half) 0
1911#define PA_ROW(i, half) (2 * (i) + (half))
1912#else
1913constexpr int PA_KL = 8;
1914#define PA_KOFF(half) ((half) * 8)
1915#define PA_ROW(i, half) ((half) * 8 + (i))
1916#endif
1917typedef _Float16 wh8 __attribute__((ext_vector_type(PA_KL)));
1918typedef float wf8 __attribute__((ext_vector_type(8)));
1919constexpr int WCH = 32;          // cells per chunk (two 16-cell tiles)
1920constexpr int WVS = 80;          // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread)
1921// TR (STRATA_PA_TRIM, experiment): rows = G (12) instead of 16 in part and p. The WMMA's rows 12..15 are zero queries whose scores
1922// nothing reads; the kernel never stores or reads them then, and the 12 real rows see the same values in the same order.
1923// Less LDS a block = more blocks resident (LDS, not VGPRs, limits the occupancy here: 5 waves a SIMD).
1924template <int R, int VS = WVS>
1925struct alignas(16) SmemWT {
1926    float part[4][R][WCH + 1];   // q.k per dim group
1927    float p[R][WCH + 1];
1928    float vs[4][WCH];            // V scale per (group, cell)
1929    int valid[WCH];              // the cell has a resident pool row
1930    uint8_t v[4][WCH][VS];       // per wave: the chunk's V codes of its group, one row per cell
1931    float qmax[4];
1932    float alpha[16];
1933    float lsum[16];
1934    float mrow[16];
1935};
1936using SmemW = SmemWT<16>;
1937
1938__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) {
1939#if STRATA_PA_WMMA && STRATA_PA_GFX11
1940    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
1941#elif STRATA_PA_WMMA
1942    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
1943#else
1944    __builtin_trap();
1945    return c;
1946#endif
1947}
1948
1949__device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) {   // PA_KL codes, exact: |code| <= 128
1950    wh8 h;
1951#pragma unroll
1952    for (int i = 0; i < PA_KL; ++i) h[i] = (_Float16) (int) (int8_t) (x[i / 4] >> (8 * (i % 4)));
1953    return h;
1954}
1955
1956// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in
1957// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the
1958// usual flash-attention kernels), quality-gated
1959// GATE = true (STRATA_QSA_FUSE_GATE): the attention output gate of the QSA layer in the epilogue - o16[qi * ld16 + h * HD + d] =
1960// half(a * (1 / (1 + expf(-qf[qi * n_head * 2 * HD + h * 2 * HD + HD + d])))) with a the value `attn` would have held: the
1961// expressions of the prefill's gate_attn_kernel, so the FP16 image is the same bits and `attn` is neither written nor read back.
1962// RPF (STRATA_PA_RPF, experiment): chunk ci + 1's id and page-table reads are issued before chunk ci's compute.  The kernel
1963// body is shared by prompt_attn_wmma_kernel and the VGPR-capped copies prompt_attn_wmma_nv<N> (STRATA_PA_NV, experiment:
1964// amdgpu_num_vgpr(N) needs a literal, so one stamped kernel per cap).  They only move loads and registers around: the
1965// arithmetic, its order and the output bits are the same.
1966template <bool SPLIT, bool GATE, bool RPF, int TR>
1967__device__ __forceinline__ void prompt_attn_wmma_body(const float* __restrict__ q, QsaAttnPools p,
1968                                                                   const int32_t* __restrict__ ids,
1969                                                                   const int32_t* __restrict__ steps, int n_kv_heads,
1970                                                                   int page_size, float scale_log2,
1971                                                                   float* __restrict__ attn, int cap,
1972                                                                   const float* __restrict__ qf,
1973                                                                   uint16_t* __restrict__ o16, int64_t ld16) {
1974#if STRATA_PA_WMMA
1975    __shared__ SmemWT<TR ? G : 16, TR >= 2 ? 72 : WVS> S;
1976    const int qi = blockIdx.x, kvh = blockIdx.y;
1977    const int n_head = n_kv_heads * G;
1978    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1979    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1980    ids += (size_t) qi * cap;
1981    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
1982    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1983    const int col = lane & 15, half = lane >> 4;   // fragment column / k half
1984    const int dim0 = warp * 64;
1985
1986    float qm = 0.0f;
1987    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
1988#pragma unroll
1989    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
1990    if (lane == 0) S.qmax[warp] = qm;
1991    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
1992    __syncthreads();
1993    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
1994    int qe = 0;
1995    if (qm > 0.0f) frexpf(qm, &qe);
1996    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
1997    // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + i
1998    wh8 qh[4], ql[4];
1999#pragma unroll
2000    for (int kk = 0; kk < 4; ++kk) {
2001        float x[PA_KL];
2002        if (col < G) {
2003            const float4* src = reinterpret_cast<const float4*>(q + (size_t) col * HD + dim0 + kk * 16 + PA_KOFF(half));
2004#pragma unroll
2005            for (int j = 0; j < PA_KL / 4; ++j) {
2006                const float4 a = src[j];
2007                x[4 * j] = a.x; x[4 * j + 1] = a.y; x[4 * j + 2] = a.z; x[4 * j + 3] = a.w;
2008            }
2009        } else {
2010#pragma unroll
2011            for (int i = 0; i < PA_KL; ++i) x[i] = 0.0f;
2012        }
2013#pragma unroll
2014        for (int i = 0; i < PA_KL; ++i) {
2015            const float v = x[i] * qup;
2016            const _Float16 hi = (_Float16) v;
2017            qh[kk][i] = hi;
2018            ql[kk][i] = (_Float16) (v - (float) hi);
2019        }
2020    }
2021
2022    wf8 acc[4];
2023#pragma unroll
2024    for (int j = 0; j < 4; ++j) acc[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
2025
2026    const int n_chunks = (n + WCH - 1) / WCH;
2027    // chunk ci's cell for this lane (lane = cell index): its pool row, or -1 (past the selection, or a block the KV
2028    // streaming left non-resident: masked as in the decode kernel)
2029    auto row_of = [&](int ci) -> long long {
2030        const int c0 = ci * WCH;
2031        long long r = -1;
2032        if (c0 + lane < n) {
2033            const int cell = __ldg(ids + c0 + lane);
2034            const long long page = (long long) __ldg(p.page_table + cell / page_size);
2035            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
2036        }
2037        return r;
2038    };
2039    // a chunk's global reads: this wave's V slice (64 bytes of each row) and V scale, and the K fragments (8 or 16
2040    // consecutive codes per lane) and K scales of its two 16-cell tiles
2041    struct Chunk {
2042        long long row;
2043        uint4 v[4];
2044        float vsc, ksc[2];
2045        uint32_t kx[2][4][PA_KL / 4];
2046    };
2047    auto fetch = [&](long long row, Chunk& d) {
2048        d.row = row;
2049        d.v[0] = d.v[1] = d.v[2] = d.v[3] = make_uint4(0, 0, 0, 0);
2050        d.vsc = 0.0f;
2051        if (row >= 0) {
2052            const uint4* src = reinterpret_cast<const uint4*>(p.v_q + row * HD + dim0);
2053            d.v[0] = __ldg(src); d.v[1] = __ldg(src + 1); d.v[2] = __ldg(src + 2); d.v[3] = __ldg(src + 3);
2054            d.vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + row * (HD / KV_Q8_GROUP) + warp)));
2055        }
2056#pragma unroll
2057        for (int nt = 0; nt < 2; ++nt) {
2058            const long long rr = __shfl(row, nt * 16 + col);
2059            d.ksc[nt] = 0.0f;
2060            if (rr >= 0) d.ksc[nt] = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp)));
2061#pragma unroll
2062            for (int kk = 0; kk < 4; ++kk) {
2063#pragma unroll
2064                for (int i = 0; i < PA_KL / 4; ++i) d.kx[nt][kk][i] = 0;
2065                if (rr >= 0) {
2066                    const uint32_t* src = reinterpret_cast<const uint32_t*>(p.k_q + rr * HD + dim0 + kk * 16 + PA_KOFF(half));
2067#if STRATA_PA_GFX11
2068                    const uint4 v = __ldg(reinterpret_cast<const uint4*>(src));
2069                    d.kx[nt][kk][0] = v.x; d.kx[nt][kk][1] = v.y; d.kx[nt][kk][2] = v.z; d.kx[nt][kk][3] = v.w;
2070#else
2071                    const uint2 v = __ldg(reinterpret_cast<const uint2*>(src));
2072                    d.kx[nt][kk][0] = v.x; d.kx[nt][kk][1] = v.y;
2073#endif
2074                }
2075            }
2076        }
2077    };
2078    auto chunk = [&](const Chunk& cd) {
2079        // stage this wave's V slice and scale
2080        {
2081            if constexpr (TR >= 2) {   // 72-byte rows (8-byte aligned): 1,024 bytes less LDS a block
2082                uint2* dst = reinterpret_cast<uint2*>(&S.v[warp][lane][0]);
2083                dst[0] = make_uint2(cd.v[0].x, cd.v[0].y); dst[1] = make_uint2(cd.v[0].z, cd.v[0].w);
2084                dst[2] = make_uint2(cd.v[1].x, cd.v[1].y); dst[3] = make_uint2(cd.v[1].z, cd.v[1].w);
2085                dst[4] = make_uint2(cd.v[2].x, cd.v[2].y); dst[5] = make_uint2(cd.v[2].z, cd.v[2].w);
2086                dst[6] = make_uint2(cd.v[3].x, cd.v[3].y); dst[7] = make_uint2(cd.v[3].z, cd.v[3].w);
2087            } else {
2088                uint4* dst = reinterpret_cast<uint4*>(&S.v[warp][lane][0]);
2089                dst[0] = cd.v[0]; dst[1] = cd.v[1]; dst[2] = cd.v[2]; dst[3] = cd.v[3];
2090            }
2091            S.vs[warp][lane] = cd.vsc;
2092            if (warp == 0) S.valid[lane] = cd.row >= 0;
2093        }
2094        // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group
2095#pragma unroll
2096        for (int nt = 0; nt < 2; ++nt) {
2097            wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
2098#pragma unroll
2099            for (int kk = 0; kk < 4; ++kk) {
2100                const wh8 b = i8_to_h(cd.kx[nt][kk]);
2101                s = wmma_f16(qh[kk], b, s);
2102                if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s);
2103            }
2104#pragma unroll
2105            for (int i = 0; i < 8; ++i) if (!TR || PA_ROW(i, half) < G) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * cd.ksc[nt];
2106        }
2107        __syncthreads();
2108        // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
2109        if (!TR || t < G * 8) {   // (TR: the 4th wave has only the padding rows 12..15 and skips: a whole wave, so the shuffles stay uniform)
2110            const int r = t >> 3, sub = t & 7;
2111            float x[4], mx = -INFINITY;
2112#pragma unroll
2113            for (int j = 0; j < 4; ++j) {
2114                const int c = sub * 4 + j;
2115                // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight
2116                x[j] = S.valid[c] ? (((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c]) * qdown
2117                                  : -INFINITY;
2118                mx = fmaxf(mx, x[j]);
2119            }
2120#pragma unroll
2121            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
2122            const float m_old = S.mrow[r];
2123            const float m_new = fmaxf(m_old, mx);
2124            float sum = 0.0f;
2125#pragma unroll
2126            for (int j = 0; j < 4; ++j) {
2127                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
2128                S.p[r][sub * 4 + j] = e;
2129                sum += e;
2130            }
2131#pragma unroll
2132            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
2133            if (sub == 0) {
2134                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
2135                S.alpha[r] = a;
2136                S.lsum[r] = fmaf(S.lsum[r], a, sum);
2137                S.mrow[r] = m_new;
2138            }
2139        }
2140        __syncthreads();
2141        // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells
2142        {
2143            float vmax = S.vs[warp][lane];
2144#pragma unroll
2145            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
2146            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
2147            wf8 tmp[4];
2148#pragma unroll
2149            for (int j = 0; j < 4; ++j) tmp[j] = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
2150#pragma unroll
2151            for (int ks = 0; ks < 2; ++ks) {
2152                const int cb = ks * 16 + PA_KOFF(half);   // this lane's PA_KL cells
2153                wh8 ah, al;
2154#pragma unroll
2155                for (int i = 0; i < PA_KL; ++i) {
2156                    const float pv = (!TR || col < G ? S.p[col][cb + i] : 0.0f) * (S.vs[warp][cb + i] * vup);
2157                    const _Float16 hi = (_Float16) pv;
2158                    ah[i] = hi;
2159                    al[i] = (_Float16) (pv - (float) hi);
2160                }
2161#pragma unroll
2162                for (int j = 0; j < 4; ++j) {
2163                    const int d = j * 16 + col;
2164                    wh8 b;
2165#pragma unroll
2166                    for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d];
2167                    tmp[j] = wmma_f16(ah, b, tmp[j]);
2168                    if constexpr (SPLIT) tmp[j] = wmma_f16(al, b, tmp[j]);
2169                }
2170            }
2171            float a[8];
2172#pragma unroll
2173            for (int i = 0; i < 8; ++i) a[i] = S.alpha[PA_ROW(i, half)];
2174#pragma unroll
2175            for (int j = 0; j < 4; ++j)
2176#pragma unroll
2177                for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown);
2178        }
2179        // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next
2180        // chunk's first barrier (which every wave reaches after its p.v)
2181    };
2182    // all of a chunk's reads are issued before its compute (they were interleaved with the q.k WMMAs and the V
2183    // staging): 32K context, 2,048 queries, gfx1151, STRATA_PA_FAST=1: 12.49 -> 11.27 ms; the same bits
2184    if constexpr (RPF) {
2185        long long nrow = n_chunks > 0 ? row_of(0) : -1;
2186        for (int ci = 0; ci < n_chunks; ++ci) {
2187            Chunk d;
2188            fetch(nrow, d);
2189            if (ci + 1 < n_chunks) nrow = row_of(ci + 1);
2190            chunk(d);
2191        }
2192    } else {
2193        for (int ci = 0; ci < n_chunks; ++ci) {
2194            Chunk d;
2195            fetch(row_of(ci), d);
2196            chunk(d);
2197        }
2198    }
2199    float inv[8];
2200#pragma unroll
2201    for (int i = 0; i < 8; ++i) {
2202        const float l = S.lsum[PA_ROW(i, half)];
2203        inv[i] = l > 0.0f ? 1.0f / l : 0.0f;
2204    }
2205#pragma unroll
2206    for (int j = 0; j < 4; ++j)
2207#pragma unroll
2208        for (int i = 0; i < 8; ++i) {
2209            const int row = PA_ROW(i, half);
2210            if (row < G) {
2211                if constexpr (GATE) {
2212                    const int h = kvh * G + row, d = dim0 + j * 16 + col;
2213                    const float a = acc[j][i] * inv[i];
2214                    o16[(size_t) qi * ld16 + (size_t) h * HD + d] =
2215                        __half_as_ushort(__float2half_rn(a * (1.0f / (1.0f + expf(-qf[(size_t) qi * n_head * 2 * HD + (size_t) h * 2 * HD + HD + d])))));
2216                } else {
2217                    attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i];
2218                }
2219            }
2220        }
2221#else
2222    __builtin_trap();
2223#endif
2224}
2225template <bool SPLIT, bool GATE = false, bool RPF = false, int TR = 0>
2226__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p,
2227                                                                   const int32_t* __restrict__ ids,
2228                                                                   const int32_t* __restrict__ steps, int n_kv_heads,
2229                                                                   int page_size, float scale_log2,
2230                                                                   float* __restrict__ attn, int cap,
2231                                                                   const float* __restrict__ qf = nullptr,
2232                                                                   uint16_t* __restrict__ o16 = nullptr, int64_t ld16 = 0) {
2233    prompt_attn_wmma_body<SPLIT, GATE, RPF, TR>(q, p, ids, steps, n_kv_heads, page_size, scale_log2, attn, cap, qf, o16, ld16);
2234}
2235
2236// gfx12 (RDNA4): on by default on Linux (148-amd; STRATA_HIP_WMMA=0 turns it off; Windows: opt-in with =1 until tested there).  gfx11 (RDNA3 / RDNA3.5): only on request
2237// (STRATA_HIP_WMMA=1).  STRATA_HIP_WMMA=auto (151-amd) takes the matrix-core kernel on a gfx12 card for a batch of
2238// STRATA_HIP_WMMA_MIN_Q (64) or more queries and keeps the FP32 kernel for smaller calls.  The output differs from the
2239// old kernel's in its last bits (FP32-level accuracy, another summation order): teacher-forced KL against the old kernel
2240// 0.0003 (28 prompts) / 0.0014 (8 long documents) on an R9700.  A launch that fails switches the path off for the rest of
2241// the process (the caller then runs the FP32 kernel) instead of ending it.
2242int hip_wmma_mode_env() {   // -1 unset (the arch default), 0 off, 1 forced, 2 auto
2243    static const int mode = [] {
2244        const char* e = std::getenv("STRATA_HIP_WMMA");
2245        if (e == nullptr || e[0] == '\0') return -1;
2246        if (e[0] == '1') return 1;
2247        if (!std::strcmp(e, "auto")) return 2;
2248        return 0;
2249    }();
2250    return mode;
2251}
2252std::atomic<bool> g_wmma_failed{false};
2253// the device's class: 1 gfx11 matrix-core part, 2 gfx12 (RDNA4), 3 anything else
2254int hip_wmma_arch(int dev) {
2255    static int arch[64] = {};
2256    if (dev < 0 || dev >= 64) return 3;
2257    if (arch[dev] == 0) {
2258        hipDeviceProp_t prop{};
2259        if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return 3; }
2260        arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 ? 2
2261                    : strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName) ? 1 : 3;
2262        const int mode = hip_wmma_mode_env();
2263        static bool told = false;
2264        if (!told && (mode >= 1 || arch[dev] == 2)) {
2265            told = true;
2266            const bool on = (arch[dev] == 2 && (mode >= 1 || strata::core::kGfx12PromptDefaultsOn)) || (arch[dev] == 1 && mode >= 1);
2267            if (mode >= 1 || on)
2268                std::fprintf(stderr, "strata: %sthe prompt attention on matrix cores %s (%s)%s\n", mode >= 1 ? "STRATA_HIP_WMMA: " : "",
2269                             !on ? "unavailable" : (mode == 2 ? "chosen per call" : "on"), prop.gcnArchName,
2270                             mode >= 1 ? "" : " by default; STRATA_HIP_WMMA=0 turns it off");
2271            else
2272                std::fprintf(stderr, "strata: the prompt attention on matrix cores is off by default on Windows (opt-in until tested on Windows); "
2273                                     "STRATA_HIP_WMMA=1 turns it on (%s)\n", prop.gcnArchName);
2274        }
2275    }
2276    return arch[dev];
2277}
2278// auto: where the matrix-core kernel beats the FP32 one.  Measured on the R9700 (gfx1201) only; the gfx11 parts take
2279// it only when forced with =1.
2280bool hip_wmma_auto_pick(int arch, int64_t n_q, int64_t cap) {
2281    if (arch != 2) return false;
2282    static const int64_t min_q = [] { const char* e = std::getenv("STRATA_HIP_WMMA_MIN_Q"); return e ? (int64_t) std::atoll(e) : (int64_t) 64; }();
2283    static const int64_t min_cap = [] { const char* e = std::getenv("STRATA_HIP_WMMA_MIN_CAP"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
2284    return n_q >= min_q && cap >= min_cap;
2285}
2286bool hip_wmma_usable(int64_t n_q, int64_t cap) {
2287    const int mode = hip_wmma_mode_env();
2288    if (mode == 0 || g_wmma_failed.load(std::memory_order_relaxed)) return false;
2289    int dev = 0;
2290    if (hipGetDevice(&dev) != hipSuccess) { (void) hipGetLastError(); return false; }
2291    const int arch = hip_wmma_arch(dev);
2292    if (arch == 3) return false;
2293    if (mode == 1) return true;
2294    if (mode == 2) return hip_wmma_auto_pick(arch, n_q, cap);
2295    return arch == 2 && strata::core::kGfx12PromptDefaultsOn;   // unset: the gfx12 default (Linux; Windows is opt-in until tested there)
2296}
2297
2298// STRATA_PA_TRIM (0 off, 1 padding rows out of LDS, 2 also 72-byte V rows; default PA_TRIM_DEFAULT) and STRATA_PA_RPF (0/1; default on):
2299// the kernel's LDS and load-order variants.  The same arithmetic in the same order: the output bits are the same (the
2300// checksum of hip_prompt_attn_wmma is equal across them), only the blocks resident a WGP and the load timing change.
2301constexpr int PA_TRIM_DEFAULT = 2;
2302template <bool SPLIT, bool GATE>
2303void pa_launch(dim3 grid, cudaStream_t st, const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
2304               int n_kv_heads, int page_size, float scale_log2, float* attn, int cap, const float* qf, uint16_t* o16, int64_t ld16) {
2305    static const int trim = [] { const char* e = std::getenv("STRATA_PA_TRIM"); return e != nullptr && e[0] != '\0' ? std::atoi(e) : PA_TRIM_DEFAULT; }();
2306    static const bool rpf = [] { const char* e = std::getenv("STRATA_PA_RPF"); return !(e != nullptr && e[0] == '0'); }();
2307#define STRATA_PA_L(R, T) prompt_attn_wmma_kernel<SPLIT, GATE, R, T><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, n_kv_heads, page_size, scale_log2, attn, cap, qf, o16, ld16)
2308    if (trim >= 2) { if (rpf) STRATA_PA_L(true, 2); else STRATA_PA_L(false, 2); }
2309    else if (trim == 1) { if (rpf) STRATA_PA_L(true, 1); else STRATA_PA_L(false, 1); }
2310    else { if (rpf) STRATA_PA_L(true, 0); else STRATA_PA_L(false, 0); }
2311#undef STRATA_PA_L
2312}
2313
2314bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
2315                 const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st, const float* gate_qf = nullptr,
2316                 uint16_t* gate_o16 = nullptr, int64_t gate_ld = 0) {
2317    {   // STRATA_QSA_STAT=1 (diagnostic): how much consecutive queries' selections overlap (the row-union attention's sharing factor)
2318        static const bool stat_on = std::getenv("STRATA_QSA_STAT") != nullptr;
2319        static int stat_calls = 0;
2320        if (stat_on && n_q >= 2048 && stat_calls < 4) {
2321            ++stat_calls;
2322            cudaStreamSynchronize(st);
2323            std::vector<int32_t> h((size_t) (n_q * cap)), hs((size_t) (n_q * kStepCount));
2324            cudaMemcpy(h.data(), ids, h.size() * 4, cudaMemcpyDeviceToHost);
2325            cudaMemcpy(hs.data(), steps, hs.size() * 4, cudaMemcpyDeviceToHost);
2326            for (int R : {4, 8, 16, 32}) {
2327                double mean_n = 0, mean_u = 0; int64_t groups = 0;
2328                for (int64_t g0 = n_q / 2; g0 + R <= n_q; g0 += 4 * R) {   // the second half of the chunk (longer contexts)
2329                    std::vector<int32_t> all;
2330                    int64_t sum_n = 0;
2331                    for (int r = 0; r < R; ++r) {
2332                        const int n = hs[(size_t) (g0 + r) * kStepCount + kStepWidth];
2333                        sum_n += n;
2334                        all.insert(all.end(), h.begin() + (size_t) (g0 + r) * cap, h.begin() + (size_t) (g0 + r) * cap + n);
2335                    }
2336                    std::sort(all.begin(), all.end());
2337                    const int64_t u = std::unique(all.begin(), all.end()) - all.begin();
2338                    mean_n += (double) sum_n / R; mean_u += (double) u; ++groups;
2339                }
2340                if (groups) std::fprintf(stderr, "strata qsa stat: call %d n_q %lld cap %lld rows/group %d: mean selection %.0f, mean union %.0f (x%.2f; K/V reads per row %.2fx lower)\n",
2341                                         stat_calls, (long long) n_q, (long long) cap, R, mean_n / groups, mean_u / groups, mean_u / mean_n, R * mean_n / mean_u);
2342            }
2343        }
2344    }
2345    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
2346    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
2347        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
2348        static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }();
2349        static const int64_t min_t = [] { const char* e = std::getenv("STRATA_PF_SWITCH_MIN_T"); return e ? (int64_t) std::atoll(e) : (int64_t) 0; }();
2350        const dim3 grid((unsigned) nb, (unsigned) s.n_head_kv);
2351        const float* qq = q + q0 * s.n_head * HD;
2352        const int32_t* idq = ids + q0 * cap;
2353        const int32_t* stq = steps + q0 * kStepCount;
2354        if (gate_qf != nullptr) {   // STRATA_QSA_FUSE_GATE: the gated FP16 image straight from the epilogue (the same SPLIT choice)
2355            const float* qfq = gate_qf + (size_t) q0 * s.n_head * 2 * HD;
2356            uint16_t* o16q = gate_o16 + (size_t) q0 * gate_ld;
2357            if (fast && n_q >= min_t)
2358                pa_launch<false, true>(grid, st, qq, pools, idq, stq, (int) s.n_head_kv, (int) s.page_size, scale_log2, nullptr, (int) cap, qfq, o16q, gate_ld);
2359            else
2360                pa_launch<true, true>(grid, st, qq, pools, idq, stq, (int) s.n_head_kv, (int) s.page_size, scale_log2, nullptr, (int) cap, qfq, o16q, gate_ld);
2361        } else if (fast && n_q >= min_t)
2362            pa_launch<false, false>(grid, st, qq, pools, idq, stq, (int) s.n_head_kv, (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap, nullptr, nullptr, 0);
2363        else
2364            pa_launch<true, false>(grid, st, qq, pools, idq, stq, (int) s.n_head_kv, (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap, nullptr, nullptr, 0);
2365    }
2366    const cudaError_t e = cudaGetLastError();
2367    if (e != cudaSuccess) {
2368        std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s; the FP32 prompt attention runs from here on\n", cudaGetErrorString(e));
2369        g_wmma_failed.store(true);
2370        return false;
2371    }
2372    return true;
2373}
2374#endif
2375
2376int g_pa_imma = -1;   // STRATA_PROMPT_ATTN_IMMA: -1 not read yet; qsa_prompt_attn_set_imma (tests) overrides it
2377}  // namespace
2378
2379// STRATA_QSA_SPLIT_ATTN=1 (the idea of fork Eddoursul fd23d91): the decode attention through the
2380// prompt path's int8 tensor-core kernel with each query's cells split among up to 20 blocks (one wave), merged with the
2381// log-sum-exp rescale.  int8 KV on sm_80+ only (false otherwise: the caller keeps qsa_decode_attn_batch).  The
2382// partials live in the decode scratch (n_q x splits x n_head x (HD + 2) floats, within qsa_decode_attn_scratch_floats).
2383bool qsa_decode_attn_split(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
2384                           int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q,
2385                           void* stream) {
2386#if defined(__HIPCC__)
2387    return false;
2388#else
2389    if (n_q <= 0) return true;
2390    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table ||
2391        pools.k_q == nullptr || pools.v_q == nullptr || pools.k_scale == nullptr || pools.v_scale == nullptr ||
2392        pools.k_q4 != nullptr || pools.v_q4 != nullptr)
2393        return false;
2394    static int cc[64] = {}, sms[64] = {};
2395    int dev = 0;
2396    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2397    if (cc[dev] == 0) {
2398        int major = 0, minor = 0;
2399        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
2400        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
2401        cudaDeviceGetAttribute(&sms[dev], cudaDevAttrMultiProcessorCount, dev);
2402        cc[dev] = 10 * major + minor;
2403    }
2404    if (cc[dev] < 80) return false;
2405    static bool attr[64] = {};
2406    const int bytes = (int) sizeof(Smem2);
2407    if (!attr[dev]) {
2408        if (cudaFuncSetAttribute(decode_attn_i8_split_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) != cudaSuccess) {
2409            cudaGetLastError();
2410            return false;
2411        }
2412        attr[dev] = true;
2413    }
2414    // splits: up to 20, about two blocks per SM in one wave, never more than the capacity's chunks (the scratch)
2415    const int64_t chunks_cap = (cap + CH2 - 1) / CH2;
2416    int64_t nsp = (2 * (int64_t) sms[dev] + n_q * s.n_head_kv - 1) / (n_q * s.n_head_kv);
2417    nsp = std::max<int64_t>(1, std::min<int64_t>({nsp, 20, chunks_cap}));
2418    if ((uint64_t) (n_q * nsp * s.n_head * (HD + 2)) > scratch_floats) return false;   // the caller's scratch
2419    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
2420    cudaStream_t st = (cudaStream_t) stream;
2421    decode_attn_i8_split_kernel<<<dim3((unsigned) n_q, (unsigned) s.n_head_kv, (unsigned) nsp), THREADS, bytes, st>>>(
2422        q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale_log2, scratch, (int) cap);
2423    decode_attn_merge_kernel<<<dim3((unsigned) n_q, (unsigned) s.n_head), HD, 0, st>>>(scratch, (int) s.n_head, (int) nsp, attn);
2424    const cudaError_t e = cudaGetLastError();
2425    if (e != cudaSuccess) {
2426        std::fprintf(stderr, "qsa_decode_attn_split: %s\n", cudaGetErrorString(e));
2427        std::exit(1);
2428    }
2429    return true;
2430#endif
2431}
2432void qsa_prompt_attn_set_imma(int on) { g_pa_imma = on < 0 ? -1 : (on ? 1 : 0); }
2433bool qsa_prompt_attn_matrix_cores_requested() {
2434#if defined(__HIPCC__)
2435    int dev = 0;
2436    if (hipGetDevice(&dev) != hipSuccess) { (void) hipGetLastError(); return false; }
2437    const int mode = hip_wmma_mode_env(), arch = hip_wmma_arch(dev);
2438    return mode != 0 && arch != 3 && !g_wmma_failed.load(std::memory_order_relaxed) && (mode >= 1 || (arch == 2 && strata::core::kGfx12PromptDefaultsOn));
2439#else
2440    return false;
2441#endif
2442}
2443
2444bool qsa_prompt_attn_matrix_cores_gfx12() {
2445#if defined(__HIPCC__)
2446    int dev = 0;
2447    if (hipGetDevice(&dev) != hipSuccess) { (void) hipGetLastError(); return false; }
2448    return qsa_prompt_attn_matrix_cores_requested() && hip_wmma_arch(dev) == 2;
2449#else
2450    return false;
2451#endif
2452}
2453
2454bool qsa_hip_wmma_active() { return qsa_prompt_attn_matrix_cores_requested(); }
2455
2456bool qsa_prompt_attn_batch_gated(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
2457                                 int64_t cap, const QsaShapes& s, const float* qf, uint16_t* o16, int64_t ld16, int64_t n_q,
2458                                 void* stream) {
2459#if defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
2460    if (n_q <= 0 || qf == nullptr || o16 == nullptr || ld16 < s.n_head * HD) return false;
2461    if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
2462        pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
2463        cap > 0 && ids && steps && pools.page_table && hip_wmma_usable(n_q, cap))
2464        return launch_wmma(q, pools, ids, steps, cap, s, nullptr, n_q, (cudaStream_t) stream, qf, o16, ld16);
2465#else
2466    (void) q; (void) pools; (void) ids; (void) steps; (void) cap; (void) s; (void) qf; (void) o16; (void) ld16; (void) n_q; (void) stream;
2467#endif
2468    return false;
2469}
2470
2471bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
2472                           int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
2473    if (n_q <= 0) return true;
2474    bool volta = false, turing = false, t75 = false;   // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
2475    {   // sm_75 or newer: the MMA above compiles for both.  sm_80+ runs the cp.async kernel (launch_i8); Turing has
2476        // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order).  An older card
2477        // keeps the old kernel.
2478        // #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75)
2479#if defined(STRATA_HIP_GFX906)
2480        return false;   // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs
2481#endif
2482        static int cc[64] = {};
2483        int dev = 0;
2484        if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
2485        if (cc[dev] == 0) {
2486            int major = 0, minor = 0;
2487            if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
2488                cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
2489                cudaGetLastError();
2490                return false;
2491            }
2492            // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card that has the Turing MMA (sm_75
2493            // and newer), as RTX 20 runs them.  A card below sm_75 has no m16n8k8: its builds hold a __trap() in those
2494            // kernels, so forcing them there killed the engine ("prefill copy_i32: unspecified launch failure" on a
2495            // Tesla P100); such a card ignores the switch and keeps the kernel it runs without it.
2496            const char* w = std::getenv("STRATA_QSA_WARP");
2497            const int real_cc = 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
2498            cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) && real_cc >= 75 ? 75 : real_cc;
2499        }
2500        if (cc[dev] < 70) return false;
2501        volta = cc[dev] < 75;     // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one
2502        turing = cc[dev] < 80;
2503        t75 = cc[dev] == 75;      // a Turing card, or one run as such (STRATA_EMULATE_CC=75, STRATA_QSA_WARP=1)
2504    }
2505#if defined(__HIPCC__)
2506    // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
2507    // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
2508    (void) turing; (void) volta;
2509    if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
2510        pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
2511        cap > 0 && ids && steps && pools.page_table && hip_wmma_usable(n_q, cap))
2512        return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
2513    return false;
2514#endif
2515    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table)
2516        return false;
2517    cudaStream_t st = (cudaStream_t) stream;
2518    if (pools.k_q4 != nullptr) {   // Q4_0 K and V (--kv q4_0): mode 4.  STRATA_PROMPT_ATTN_Q4=0: the old kernel (A/B)
2519        static const bool q4_off = [] {
2520            const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
2521            return v != nullptr && v[0] == '0';
2522        }();
2523        // Turing runs mode 4 as pairs of m16n8k8 MMAs (another summation order than the FP32 kernel it replaces): manual
2524        // opt-in STRATA_PROMPT_ATTN_Q4_TC=1 (#1581, c3c: qsa_prompt_attn_parity at 4096/512 and 1500/512 on an RTX 2080 Super).
2525        static const bool q4_tc = [] {
2526            const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4_TC");
2527            return v != nullptr && v[0] == '1';
2528        }();
2529        if (q4_off || volta || (turing && !q4_tc) || pools.v_q4 == nullptr) return false;
2530        return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st);
2531    }
2532    if (pools.k_q != nullptr && pools.v_q4 != nullptr) {   // hybrid K8V4: int8 K + dequantized-q4 V
2533        if (!pools.k_scale) return false;
2534        if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
2535        return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
2536    }
2537    if (pools.k_q != nullptr) {
2538        if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
2539        // STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
2540        // for how far the model amplifies an FP32-level change.  Turing always takes it: v2's cp.async does not
2541        // exist before sm_80.
2542        static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
2543        if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
2544        // Turing: v2 with register staging instead of cp.async, opt-in (STRATA_PA_V2T=1) until measured
2545        static const bool v2t = [] { const char* e = std::getenv("STRATA_PA_V2T"); return e != nullptr && e[0] == '1'; }();
2546        if (v1 || (turing && !v2t)) {
2547            // #1821 (xrip): v1 with the next chunk's rows prefetched in registers and K/V sharing one buffer (two blocks an
2548            // SM), the same bits.  STRATA_PA_V1_PREFETCH=0 / 1 forces it off / on; unset: a Turing card with
2549            // STRATA_SM75_PERF=1.
2550            static const int pf_env = [] { const char* e = std::getenv("STRATA_PA_V1_PREFETCH"); return e ? (std::atoi(e) != 0 ? 1 : 0) : -1; }();
2551            if (pf_env == 1 || (pf_env < 0 && t75 && strata::sm75_series())) return launch<1, true>(q, pools, ids, steps, cap, s, attn, n_q, st);
2552            return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
2553        }
2554        // STRATA_PROMPT_ATTN_IMMA (sm_80+): both products on INT8 tensor cores (prompt_attn_i8v3_kernel).  ON by default since 0.2.7 on every
2555        // card that has them (Ampere and newer, CUDA builds; not Turing, Volta or Pascal, which have no int8 m16n8k32 MMA this kernel needs):
2556        // +1.6% / +1.8% prompt at 8K / 16K on the RTX PRO 5000 (sm_120) and +1.1% / +1.3% at 8K / 16K on 2x RTX A4000 (sm_86), decode unchanged,
2557        // 5 pairs each; another summation order (~1e-7), so a near-tie can flip a prompt's first token.  Sm_80, 8.9, 9.0 and the datacentre
2558        // Blackwells run the same kernel unmeasured.  STRATA_PROMPT_ATTN_IMMA=0 is the off switch (the v2 i8 kernel of 0.2.6), =1 as the default.
2559        if (g_pa_imma < 0) {
2560            const char* v = std::getenv("STRATA_PROMPT_ATTN_IMMA");
2561            g_pa_imma = v == nullptr ? 2 : (v[0] == '1' ? 1 : 0);   // 2: the default (on where the kernel can run)
2562        }
2563        if (!turing && (g_pa_imma == 1 || (g_pa_imma == 2 && strata::prompt_attn_imma_default(false, 80, strata::qwen_defaults_026())))) return launch_i8v3(q, pools, ids, steps, cap, s, attn, n_q, st);
2564        return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
2565    }
2566    if (!pools.k_pool || !pools.v_pool) return false;
2567    if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
2568    return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
2569}
2570
2571}  // namespace strata::kernels