okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
98.8 KiB2060 linesraw
1// src/kernels/cuda/qsa_prompt_attn.cu - see include/strata/kernels/qsa_prompt_attn.hpp.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include "strata/core/geometry.hpp"
6#include <dpct/dpct.hpp>
7#include "strata/sycl_queue.hpp"
8#include "strata/core/emulate.hpp"
9#include <cstdlib>
10#include <cstring>
11#include "strata/kernels/qsa_prompt_attn.hpp"
12#include "strata/kernels/qsa_prompt_attn_xmx.hpp"
13#include "strata/kernels/qsa_prompt_attn_esimd.hpp"
14#include "strata/kernels/gfx_arch.hpp"
15#include "strata/kernels/kv_q8.hpp"
16#include "strata/kernels/kv_q4.hpp"
17
18#include <cmath>
19
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <type_traits>
24
25namespace strata::kernels {
26namespace {
27
28constexpr int HD = 256;           // head_dim
29constexpr 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
30static_assert(G >= 1 && G <= 16, "qsa_prompt_attn: query heads per KV head must be 1..16 (one M16 tile)");
31static_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");
32#ifndef D1_CH
33#define D1_CH 32
34#endif
35constexpr int CH = D1_CH;         // cells per chunk
36constexpr int THREADS = 128;      // 4 warps: scores by cell (8 each), p.v by dimension (64 each = one int8 scale group)
37constexpr int QS = HD + 8;        // q row stride in halves (bank-conflict-free fragment loads)
38
39// 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
40// cards compile the MMA to a trap; qsa_prompt_attn_batch refuses such a device at run time, so the old kernel runs
41// there.  Turing compiles cp_async16 to a trap as well and takes the v1 kernel instead of launch_i8.
42#if defined(__HIPCC__)          // AMD: no mma.sync / cp.async; the host keeps the old kernel (below)
43#define STRATA_PA_SM80 0
44#elif 0   // SYCL: inline PTX (mma/ldmatrix/cp.async) - the XMX port is pending; see tools/fixups.py
45#define STRATA_PA_SM80 1
46#else
47#define STRATA_PA_SM80 0
48#endif
49
50// m16n8k16 with f16 inputs needs sm_80.  Turing (sm_75) has m16n8k8 with the SAME A/B/C register mapping, so the
51// 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
52// 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
53// products then add into the same FP32 C registers in the order hi-part-0, hi-part-1, which is the order the k16
54// instruction accumulates in as well - but the sum now rounds twice, so the two paths do not agree bit for bit.
55__dpct_inline__ void mma16816(float *c, const uint32_t *a, const uint32_t *b) {
56#if !STRATA_PA_SM80 &&                                                         \
57    (defined(__HIPCC__) || !defined(DPCT_COMPATIBILITY_TEMP) ||                \
58     DPCT_COMPATIBILITY_TEMP < 750)
59    /* unreachable on SYCL: the launcher refuses this device */   // AMD and pre-Turing builds: no mma.sync (the host keeps the old kernel there)
60#elif 0   // SYCL: Turing's m16n8k8 PTX (unreachable: the launcher refuses this device)
61    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
62                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
63                 : "r"(a[0]), "r"(a[1]), "r"(b[0]));
64    asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
65                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
66                 : "r"(a[2]), "r"(a[3]), "r"(b[1]));
67#else
68#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
69    asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
70                 "{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, "
71                 "{%0,%1,%2,%3};\n"
72                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
73                 : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]),
74                   "r"(b[1]));
75#else
76    {
77        volatile void *d_mat_frag_ct1[4] = {&c[0], &c[1], &c[2], &c[3]};
78        sycl::vec<uint32_t, 4> a_mat_frag_ct1(a[0], a[1], a[2], a[3]);
79        sycl::vec<uint32_t, 2> b_mat_frag_ct1(b[0], b[1]);
80        sycl::vec<float, 4> c_mat_frag_ct1(c[0], c[1], c[2], c[3]);
81        dpct::experimental::matrix::mma<16, 8, 16, sycl::half, float>(
82            reinterpret_cast<volatile void **>(d_mat_frag_ct1), &a_mat_frag_ct1,
83            &b_mat_frag_ct1, &c_mat_frag_ct1);
84    }
85#endif
86#endif
87}
88
89// Two int8 codes (low byte first) as an exact half2: 1024 + (c + 128) built in the mantissa, minus 1152.
90__dpct_inline__ uint32_t i8x2_to_h2(uint32_t x) {
91    uint32_t y = ((x & 0xffu) | ((x & 0xff00u) << 8)) ^ 0x00800080u;
92    y |= 0x64006400u;
93    sycl::half2 h = *reinterpret_cast<sycl::half2 *>(&y);
94    h = h - sycl::half2(
95                sycl::vec<float, 1>(1152.f)
96                    .convert<sycl::half, sycl::rounding_mode::automatic>()[0],
97                sycl::vec<float, 1>(1152.f)
98                    .convert<sycl::half, sycl::rounding_mode::automatic>()[0]);
99    return *reinterpret_cast<uint32_t*>(&h);
100}
101
102__dpct_inline__ uint32_t pack_h2(float lo_k,
103                                 float hi_k) { // element k in the low half
104    sycl::half2 h = sycl::float2(lo_k, hi_k)
105                        .convert<sycl::half, sycl::rounding_mode::rte>();
106    return *reinterpret_cast<uint32_t*>(&h);
107}
108
109// KV_MODE 1: int8 codes + fp16 scale per 64 values. KV_MODE 0: fp16 values (scales 1).
110// KV_MODE 3 (hybrid K8V4): K as mode 1, V as mode 0 - the row's q4_0 blocks are dequantized to fp16 at
111// gather, so everything downstream of the load is the mode-0 V path; the caller un-rotates the output.
112// 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
113// int8 (code - 8) and its fp16 scale is applied in FP32, as mode 1's are; the caller rotates q and un-rotates the
114// output (kv_q4.hpp).
115template <int KV_MODE>
116struct Smem {
117    using KElem =
118        typename std::conditional<KV_MODE == 0, sycl::half, int8_t>::type;
119    using VElem = typename std::conditional<KV_MODE == 1 || KV_MODE == 4,
120                                            int8_t, sycl::half>::type;
121    static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;   // elements; 16-byte aligned rows, banks spread
122    static constexpr int VROW = (KV_MODE == 1 || KV_MODE == 4) ? HD + 16 : HD + 8;
123    static constexpr int NG = KV_MODE == 4 ? HD / QK4_0 : 4;      // scale groups per row (q4_0: 8 of 32, else 4 of 64)
124    sycl::half qh[16][QS];
125    sycl::half ql[16][QS];
126    KElem k[CH][KROW];
127    VElem v[CH][VROW];
128    float ks[CH][NG];
129    float vs[CH][NG];
130    float s[16][CH + 1];
131    float qmax[THREADS / 32];
132    float alpha[16];
133    float lsum[16];
134    float mrow[16];
135    long long row[CH];
136};
137
138template <int KV_MODE>
139/*
140DPCT1110: The total declared local variable size in device function
141prompt_attn_kernel exceeds 128 bytes and may cause high register pressure.
142Consult with your hardware vendor to find the total register size available and
143adjust the code, or use smaller sub-group size to avoid high register pressure.
144*/
145__dpct_inline__ void
146prompt_attn_kernel(const float *__restrict__ q, QsaAttnPools p,
147                   const int32_t *__restrict__ ids,
148                   const int32_t *__restrict__ steps, int n_kv_heads,
149                   int page_size, float scale_log2, float *__restrict__ attn,
150                   int cap, uint8_t *dpct_local) {
151    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
152    auto smem_raw = (unsigned char *)dpct_local;
153    Smem<KV_MODE>& S = *reinterpret_cast<Smem<KV_MODE>*>(smem_raw);
154    const int qi = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
155    const int n_head = n_kv_heads * G;
156    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
157    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
158    ids += (size_t) qi * cap;
159    /*
160    DPCT1098: The '*' expression is used instead of the __ldg call. These
161    two expressions do not provide the exact same functionality. Check the
162    generated code for potential precision and/or performance issues.
163    */
164    const int n = *(steps + (size_t)qi * kStepCount + kStepWidth);
165    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
166    const int gid = lane >> 2, tig = lane & 3;
167
168    // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
169    // lo halves stay out of FP16's subnormal range), then split into hi + lo halves
170    float qm = 0.0f;
171#pragma unroll
172    for (int i = t; i < G * HD; i += THREADS)
173        qm = sycl::fmax(qm, sycl::fabs(q[i]));
174#pragma unroll
175    /*
176    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
177    masked sub_group function which may not be supported by all compilers or
178    runtimes. You may need to adjust the code.
179    */
180    for (int o = 16; o > 0; o >>= 1) qm = sycl::fmax(
181        qm, dpct::experimental::permute_sub_group_by_xor(
182                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
183                qm, o));
184    if (lane == 0) S.qmax[warp] = qm;
185    /*
186    DPCT1065: Consider replacing sycl::nd_item::barrier() with
187    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
188    performance if there is no access to global memory.
189    */
190    item_ct1.barrier();
191    qm = sycl::fmax(sycl::fmax(S.qmax[0], S.qmax[1]),
192                    sycl::fmax(S.qmax[2], S.qmax[3]));
193    int qe = 0;
194    /*
195    DPCT1017: The sycl::frexp call is used instead of the frexpf call.
196    These two calls do not provide exactly the same functionality. Check the
197    potential precision and/or performance issues for the generated code.
198    */
199    if (qm > 0.0f) sycl::frexp(
200        qm, sycl::address_space_cast<sycl::access::address_space::generic_space,
201                                     sycl::access::decorated::yes>(
202                &qe)); // qm < 2^qe
203    const float qup = sycl::ldexp(1.0f, 14 - qe),
204                qdown = sycl::ldexp(scale_log2, qe - 14);
205    for (int i = t; i < 16 * HD; i += THREADS) {
206        const int h = i / HD, d = i % HD;
207        const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
208        const sycl::half hi =
209            sycl::vec<float, 1>(x)
210                .convert<sycl::half, sycl::rounding_mode::rte>()[0];
211        S.qh[h][d] = hi;
212        S.ql[h][d] =
213            sycl::vec<float, 1>(
214                x - sycl::vec<sycl::half, 1>(hi)
215                        .convert<float, sycl::rounding_mode::automatic>()[0])
216                .convert<sycl::half, sycl::rounding_mode::rte>()[0];
217    }
218    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
219
220    float acc[8][4];
221#pragma unroll
222    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
223
224    for (int c0 = 0; c0 < n; c0 += CH) {
225        const int nh = sycl::min(CH, n - c0);
226        if (t < CH) {
227            long long r = -1;
228            if (t < nh) {
229                const int cell = ids[c0 + t];
230                const long long page = (long long) p.page_table[cell / page_size];
231                r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
232            }
233            S.row[t] = r;
234        }
235        /*
236        DPCT1118: SYCL group functions and algorithms must be encountered in
237        converged control flow. You may need to adjust the code.
238        */
239        /*
240        DPCT1065: Consider replacing sycl::nd_item::barrier() with
241        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
242        better performance if there is no access to global memory.
243        */
244        item_ct1.barrier(); // rows ready; the previous chunk's p.v is done with
245                            // k, v, s
246        // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
247        // and their scales
248        if constexpr (KV_MODE == 4) {
249            // q4_0 K and V: one (K or V, cell, block) per item - the block's 16 code bytes (2-byte aligned: eight
250            // 16-bit loads) become 32 exact int8 codes (element j in the low nibble of byte j, j + 16 in the high
251            // one), its fp16 scale goes to ks/vs
252            constexpr int BLKS = HD / QK4_0;
253            constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
254            for (int i = t; i < 2 * CH * BLKS; i += THREADS) {
255                const int kv = i / (CH * BLKS), rem = i % (CH * BLKS), c = rem / BLKS, b = rem % BLKS;
256                const long long r = S.row[c];
257                sycl::uint4 lo = sycl::uint4(0, 0, 0, 0),
258                            hi = sycl::uint4(0, 0, 0, 0);
259                float d = 0.0f;
260                if (r >= 0) {
261                    const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((kv == 0 ? p.k_q4 : p.v_q4) + r * BYTES) + b;
262                    /*
263                    DPCT1098: The '*' expression is used instead of the
264                    __ldg call. These two expressions do not provide the exact
265                    same functionality. Check the generated code for potential
266                    precision and/or performance issues.
267                    */
268                    d = sycl::vec<sycl::half, 1>(
269                            sycl::bit_cast<sycl::half, unsigned short>(blk->d))
270                            .convert<float,
271                                     sycl::rounding_mode::automatic>()[0];
272                    const uint16_t* q16 = reinterpret_cast<const uint16_t*>(blk->qs);
273                    uint32_t w[4];
274#pragma unroll
275                    for (int j = 0; j < 4; ++j)
276                        /*
277                        DPCT1098: The '*' expression is used instead of the
278                        __ldg call. These two expressions do not provide the
279                        exact same functionality. Check the generated code for
280                        potential precision and/or performance issues.
281                        */
282                        w[j] = (uint32_t)*(q16 + 2 * j) |
283                               ((uint32_t)*(q16 + 2 * j + 1) << 16);
284                    // per byte: the low nibble minus 8 is element j, the high one minus 8 element j + 16
285                    lo = sycl::uint4(
286                        dpct::vectorized_binary<sycl::uchar4>(
287                            w[0] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
288                        dpct::vectorized_binary<sycl::uchar4>(
289                            w[1] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
290                        dpct::vectorized_binary<sycl::uchar4>(
291                            w[2] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()),
292                        dpct::vectorized_binary<sycl::uchar4>(
293                            w[3] & 0x0F0F0F0Fu, 0x08080808u, std::minus<>()));
294                    hi = sycl::uint4(dpct::vectorized_binary<sycl::uchar4>(
295                                         (w[0] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
296                                         std::minus<>()),
297                                     dpct::vectorized_binary<sycl::uchar4>(
298                                         (w[1] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
299                                         std::minus<>()),
300                                     dpct::vectorized_binary<sycl::uchar4>(
301                                         (w[2] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
302                                         std::minus<>()),
303                                     dpct::vectorized_binary<sycl::uchar4>(
304                                         (w[3] >> 4) & 0x0F0F0F0Fu, 0x08080808u,
305                                         std::minus<>()));
306                }
307                int8_t* dst = kv == 0 ? &S.k[c][b * QK4_0] : &S.v[c][b * QK4_0];
308                reinterpret_cast<sycl::uint4 *>(dst)[0] = lo;
309                reinterpret_cast<sycl::uint4 *>(dst)[1] = hi;
310                (kv == 0 ? S.ks : S.vs)[c][b] = d;
311            }
312        } else {
313            constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16;   // per K row
314            for (int i = t; i < CH * KPIECES; i += THREADS) {
315                const int c = i / KPIECES, pc = i % KPIECES;
316                const long long r = S.row[c];
317                sycl::uint4 kx = sycl::uint4(0, 0, 0, 0);
318                if (r >= 0) {
319                    if constexpr (KV_MODE == 0)
320                        /*
321                        DPCT1098: The '*' expression is used instead of the
322                        __ldg call. These two expressions do not provide the
323                        exact same functionality. Check the generated code for
324                        potential precision and/or performance issues.
325                        */
326                        kx = *(reinterpret_cast<const sycl::uint4 *>(p.k_pool +
327                                                                     r * HD) +
328                               pc);
329                    else   // modes 1 and 3: the K side is INT8
330                        /*
331                        DPCT1098: The '*' expression is used instead of the
332                        __ldg call. These two expressions do not provide the
333                        exact same functionality. Check the generated code for
334                        potential precision and/or performance issues.
335                        */
336                        kx = *(reinterpret_cast<const sycl::uint4 *>(p.k_q +
337                                                                     r * HD) +
338                               pc);
339                }
340                *reinterpret_cast<sycl::uint4 *>(
341                    reinterpret_cast<unsigned char *>(&S.k[c][0]) + pc * 16) =
342                    kx;
343            }
344            if constexpr (KV_MODE == 3) {   // V: dequantize the row's q4_0 blocks straight into the fp16 V row
345                constexpr int BLKS = HD / QK4_0;
346                constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
347                for (int i = t; i < CH * BLKS; i += THREADS) {
348                    const int c = i / BLKS, b = i % BLKS;
349                    const long long r = S.row[c];
350#pragma unroll
351                    for (int j = 0; j < QK4_0; ++j)
352                        S.v[c][b * QK4_0 + j] = sycl::half(0);
353                    if (r >= 0) {
354                        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
355                        const float d =
356                            sycl::vec<sycl::half, 1>(
357                                sycl::bit_cast<sycl::half, unsigned short>(
358                                    blk->d))
359                                .convert<float,
360                                         sycl::rounding_mode::automatic>()[0];
361#pragma unroll
362                        for (int j = 0; j < QK4_0 / 2; ++j) {
363                            S.v[c][b * QK4_0 + j] =
364                                sycl::vec<float, 1>(
365                                    (float)((int)(blk->qs[j] & 0x0F) - 8) * d)
366                                    .convert<sycl::half,
367                                             sycl::rounding_mode::rte>()[0];
368                            S.v[c][b * QK4_0 + j + QK4_0 / 2] =
369                                sycl::vec<float, 1>(
370                                    (float)((int)(blk->qs[j] >> 4) - 8) * d)
371                                    .convert<sycl::half,
372                                             sycl::rounding_mode::rte>()[0];
373                        }
374                    }
375                }
376            } else {
377                constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16;   // per V row
378                for (int i = t; i < CH * VPIECES; i += THREADS) {
379                    const int c = i / VPIECES, pc = i % VPIECES;
380                    const long long r = S.row[c];
381                    sycl::uint4 vx = sycl::uint4(0, 0, 0, 0);
382                    if (r >= 0) {
383                        if constexpr (KV_MODE == 1)
384                            /*
385                            DPCT1098: The '*' expression is used instead of
386                            the __ldg call. These two expressions do not provide
387                            the exact same functionality. Check the generated
388                            code for potential precision and/or performance
389                            issues.
390                            */
391                            vx = *(reinterpret_cast<const sycl::uint4 *>(
392                                       p.v_q + r * HD) +
393                                   pc);
394                        else
395                            /*
396                            DPCT1098: The '*' expression is used instead of
397                            the __ldg call. These two expressions do not provide
398                            the exact same functionality. Check the generated
399                            code for potential precision and/or performance
400                            issues.
401                            */
402                            vx = *(reinterpret_cast<const sycl::uint4 *>(
403                                       p.v_pool + r * HD) +
404                                   pc);
405                    }
406                    *reinterpret_cast<sycl::uint4 *>(
407                        reinterpret_cast<unsigned char *>(&S.v[c][0]) +
408                        pc * 16) = vx;
409                }
410            }
411            for (int i = t; i < CH * 4; i += THREADS) {
412                const int c = i / 4, g = i % 4;
413                const long long r = S.row[c];
414                float a = 0.0f, b = 0.0f;
415                if (r >= 0) {
416                    if constexpr (KV_MODE == 1) {
417                        a = sycl::vec<sycl::half, 1>(
418                                sycl::bit_cast<sycl::half, unsigned short>(
419                                    p.k_scale[r * (HD / KV_Q8_GROUP) + g]))
420                                .convert<float,
421                                         sycl::rounding_mode::automatic>()[0];
422                        b = sycl::vec<sycl::half, 1>(
423                                sycl::bit_cast<sycl::half, unsigned short>(
424                                    p.v_scale[r * (HD / KV_Q8_GROUP) + g]))
425                                .convert<float,
426                                         sycl::rounding_mode::automatic>()[0];
427                    } else if constexpr (KV_MODE == 3) {   // K as int8, V dequantized to fp16 (scale 1)
428                        a = sycl::vec<sycl::half, 1>(
429                                sycl::bit_cast<sycl::half, unsigned short>(
430                                    p.k_scale[r * (HD / KV_Q8_GROUP) + g]))
431                                .convert<float,
432                                         sycl::rounding_mode::automatic>()[0];
433                        b = 1.0f;
434                    } else {
435                        a = b = 1.0f;
436                    }
437                }
438                S.ks[c][g] = a;
439                S.vs[c][g] = b;
440            }
441        }
442        /*
443        DPCT1118: SYCL group functions and algorithms must be encountered in
444        converged control flow. You may need to adjust the code.
445        */
446        /*
447        DPCT1065: Consider replacing sycl::nd_item::barrier() with
448        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
449        better performance if there is no access to global memory.
450        */
451        item_ct1.barrier();
452        // scores: warp w takes cells 8w..8w+7 (one n-tile) over all 256 dims, per scale group (64 dims; q4_0's 32)
453        constexpr int NG = Smem<KV_MODE>::NG, KPG = HD / 16 / NG;   // groups per row, 16-dim MMA steps per group
454#pragma unroll
455        for (int nt = 0; nt < CH / 32; ++nt) {
456            const int cb = (warp + 4 * nt) * 8;
457            float sc[4] = {0.f, 0.f, 0.f, 0.f};
458#pragma unroll
459            for (int g = 0; g < NG; ++g) {
460                float tg[4] = {0.f, 0.f, 0.f, 0.f};
461#pragma unroll
462                for (int kk = 0; kk < KPG; ++kk) {
463                    const int k0 = (g * KPG + kk) * 16;
464                    uint32_t ah[4], al[4], b[2];
465                    ah[0] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig]);
466                    ah[1] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig]);
467                    ah[2] = *reinterpret_cast<const uint32_t*>(&S.qh[gid][k0 + 2 * tig + 8]);
468                    ah[3] = *reinterpret_cast<const uint32_t*>(&S.qh[gid + 8][k0 + 2 * tig + 8]);
469                    al[0] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig]);
470                    al[1] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig]);
471                    al[2] = *reinterpret_cast<const uint32_t*>(&S.ql[gid][k0 + 2 * tig + 8]);
472                    al[3] = *reinterpret_cast<const uint32_t*>(&S.ql[gid + 8][k0 + 2 * tig + 8]);
473                    if constexpr (KV_MODE != 0) {   // modes 1 and 3: the K side is INT8 codes
474                        b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig]));
475                        b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]));
476                    } else {
477                        b[0] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig]);
478                        b[1] = *reinterpret_cast<const uint32_t*>(&S.k[cb + gid][k0 + 2 * tig + 8]);
479                    }
480                    mma16816(tg, ah, b);
481#ifndef D1_NO_QLO
482                    mma16816(tg, al, b);
483#endif
484                }
485                const float s0 = S.ks[cb + 2 * tig][g], s1 = S.ks[cb + 2 * tig + 1][g];
486                sc[0] = sycl::fma(tg[0], (float)s0, sc[0]);
487                sc[1] = sycl::fma(tg[1], (float)s1, sc[1]);
488                sc[2] = sycl::fma(tg[2], (float)s0, sc[2]);
489                sc[3] = sycl::fma(tg[3], (float)s1, sc[3]);
490            }
491            const int c = cb + 2 * tig;
492            S.s[gid][c] = c < nh ? sc[0] * qdown : -INFINITY;
493            S.s[gid][c + 1] = c + 1 < nh ? sc[1] * qdown : -INFINITY;
494            S.s[gid + 8][c] = c < nh ? sc[2] * qdown : -INFINITY;
495            S.s[gid + 8][c + 1] = c + 1 < nh ? sc[3] * qdown : -INFINITY;
496        }
497        /*
498        DPCT1118: SYCL group functions and algorithms must be encountered in
499        converged control flow. You may need to adjust the code.
500        */
501        /*
502        DPCT1065: Consider replacing sycl::nd_item::barrier() with
503        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
504        better performance if there is no access to global memory.
505        */
506        item_ct1.barrier();
507        // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
508        {
509            constexpr int PER = CH / 8;
510            const int r = t >> 3, sub = t & 7;
511            float x[PER], mx = -INFINITY;
512#pragma unroll
513            for (int j = 0; j < PER; ++j) {
514                x[j] = S.s[r][sub * PER + j]; mx = sycl::fmax(mx, x[j]);
515            }
516#pragma unroll
517            /*
518            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
519            feature masked sub_group function which may not be supported by all
520            compilers or runtimes. You may need to adjust the code.
521            */
522            for (int o = 1; o < 8; o <<= 1) mx = sycl::fmax(
523                mx,
524                dpct::experimental::permute_sub_group_by_xor(
525                    0xffffffffu,
526                    sycl::ext::oneapi::this_work_item::get_sub_group(), mx, o));
527            const float m_old = S.mrow[r];
528            const float m_new = sycl::fmax(m_old, mx);
529            float sum = 0.0f;
530#pragma unroll
531            for (int j = 0; j < PER; ++j) {
532                const float e =
533                    x[j] == -INFINITY ? 0.0f : sycl::exp2(x[j] - m_new);
534                S.s[r][sub * PER + j] = e;
535                sum += e;
536            }
537#pragma unroll
538            /*
539            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
540            feature masked sub_group function which may not be supported by all
541            compilers or runtimes. You may need to adjust the code.
542            */
543            for (int o = 1; o < 8; o <<= 1) sum +=
544                dpct::experimental::permute_sub_group_by_xor(
545                    0xffffffffu,
546                    sycl::ext::oneapi::this_work_item::get_sub_group(), sum, o);
547            sycl::group_barrier(
548                sycl::ext::oneapi::this_work_item::get_sub_group());
549            if (sub == 0) {
550                const float a =
551                    m_old == -INFINITY ? 0.0f : sycl::exp2(m_old - m_new);
552                S.alpha[r] = a;
553                S.lsum[r] = sycl::fma(S.lsum[r], (float)a, sum);
554                S.mrow[r] = m_new;
555            }
556        }
557        /*
558        DPCT1118: SYCL group functions and algorithms must be encountered in
559        converged control flow. You may need to adjust the code.
560        */
561        /*
562        DPCT1065: Consider replacing sycl::nd_item::barrier() with
563        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
564        better performance if there is no access to global memory.
565        */
566        item_ct1.barrier();
567        // 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
568        // each). A group's scale is folded into p relative to the chunk's largest magnitude (q4_0's scales are signed:
569        // ggml's d = max / -8), times 2^14 (|p'| <= 2^14: inside FP16's range, its lo half out of the subnormals); the
570        // chunk's sum is then added to the running one in FP32 with the factor taken back out
571        {
572            constexpr int GPW = NG / 4, JPG = 8 / GPW;   // scale groups per warp, n-tiles per group
573            float vdown_g[GPW];
574            float tmp[8][4];
575#pragma unroll
576            for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
577#pragma unroll
578            for (int gi = 0; gi < GPW; ++gi) {
579            const int vg = warp * GPW + gi;
580            float vmax = 0.0f;
581#pragma unroll
582            for (int c = lane; c < CH; c += 32)
583                vmax = sycl::fmax(vmax, sycl::fabs(S.vs[c][vg]));
584#pragma unroll
585            /*
586            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
587            feature masked sub_group function which may not be supported by all
588            compilers or runtimes. You may need to adjust the code.
589            */
590            for (int o = 16; o > 0; o >>= 1) vmax = sycl::fmax(
591                vmax, dpct::experimental::permute_sub_group_by_xor(
592                          0xffffffffu,
593                          sycl::ext::oneapi::this_work_item::get_sub_group(),
594                          vmax, o));
595            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f;
596            vdown_g[gi] = vmax * (1.0f / 16384.0f);
597#pragma unroll
598            for (int ks = 0; ks < CH / 16; ++ks) {
599                const int cA = ks * 16 + 2 * tig, cB = cA + 8;
600                const float w0 = S.vs[cA][vg] * vup, w1 = S.vs[cA + 1][vg] * vup, w2 = S.vs[cB][vg] * vup,
601                            w3 = S.vs[cB + 1][vg] * vup;
602                const float p00 = S.s[gid][cA] * w0, p01 = S.s[gid][cA + 1] * w1;
603                const float p10 = S.s[gid + 8][cA] * w0, p11 = S.s[gid + 8][cA + 1] * w1;
604                const float p02 = S.s[gid][cB] * w2, p03 = S.s[gid][cB + 1] * w3;
605                const float p12 = S.s[gid + 8][cB] * w2, p13 = S.s[gid + 8][cB + 1] * w3;
606                uint32_t ah[4], al[4];
607                ah[0] = pack_h2(p00, p01);
608                ah[1] = pack_h2(p10, p11);
609                ah[2] = pack_h2(p02, p03);
610                ah[3] = pack_h2(p12, p13);
611                {
612                    const sycl::half2 *h =
613                        reinterpret_cast<const sycl::half2 *>(ah);
614                    sycl::float2 f;
615                    f = h[0].template convert<float,
616                                              sycl::rounding_mode::automatic>();
617                        al[0] = pack_h2(p00 - f.x(), p01 - f.y());
618                    f = h[1].template convert<float,
619                                              sycl::rounding_mode::automatic>();
620                        al[1] = pack_h2(p10 - f.x(), p11 - f.y());
621                    f = h[2].template convert<float,
622                                              sycl::rounding_mode::automatic>();
623                        al[2] = pack_h2(p02 - f.x(), p03 - f.y());
624                    f = h[3].template convert<float,
625                                              sycl::rounding_mode::automatic>();
626                        al[3] = pack_h2(p12 - f.x(), p13 - f.y());
627                }
628#pragma unroll
629                for (int jj = 0; jj < JPG; ++jj) {
630                    const int j = gi * JPG + jj;
631                    const int d = warp * 64 + j * 8 + gid;
632                    uint32_t b[2];
633                    if constexpr (KV_MODE == 1 || KV_MODE == 4) {
634                        const uint32_t x0 = (uint8_t) S.v[cA][d] | ((uint32_t) (uint8_t) S.v[cA + 1][d] << 8);
635                        const uint32_t x1 = (uint8_t) S.v[cB][d] | ((uint32_t) (uint8_t) S.v[cB + 1][d] << 8);
636                        b[0] = i8x2_to_h2(x0);
637                        b[1] = i8x2_to_h2(x1);
638                    } else {
639                        const sycl::half2 h0 =
640                            sycl::half2(S.v[cA][d], S.v[cA + 1][d]);
641                        const sycl::half2 h1 =
642                            sycl::half2(S.v[cB][d], S.v[cB + 1][d]);
643                        b[0] = *reinterpret_cast<const uint32_t*>(&h0);
644                        b[1] = *reinterpret_cast<const uint32_t*>(&h1);
645                    }
646                    mma16816(tmp[j], ah, b);
647#ifndef D1_NO_PLO
648                    mma16816(tmp[j], al, b);
649#endif
650                }
651            }
652            }
653            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
654#pragma unroll
655            for (int j = 0; j < 8; ++j) {
656                const float vdown = vdown_g[j / JPG];
657                acc[j][0] = sycl::fma(acc[j][0], (float)a0, tmp[j][0] * vdown);
658                acc[j][1] = sycl::fma(acc[j][1], (float)a0, tmp[j][1] * vdown);
659                acc[j][2] = sycl::fma(acc[j][2], (float)a1, tmp[j][2] * vdown);
660                acc[j][3] = sycl::fma(acc[j][3], (float)a1, tmp[j][3] * vdown);
661            }
662        }
663    }
664    /*
665    DPCT1065: Consider replacing sycl::nd_item::barrier() with
666    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
667    performance if there is no access to global memory.
668    */
669    item_ct1.barrier();
670    const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
671    const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
672#pragma unroll
673    for (int j = 0; j < 8; ++j) {
674        const int d = warp * 64 + j * 8 + 2 * tig;
675        *reinterpret_cast<sycl::float2 *>(attn + (size_t)gid * HD + d) =
676            sycl::float2(acc[j][0] * i0, acc[j][1] * i0);
677        if (gid + 8 < G)
678            *reinterpret_cast<sycl::float2 *>(attn + (size_t)(gid + 8) * HD +
679                                              d) =
680                sycl::float2(acc[j][2] * i1, acc[j][3] * i1);
681    }
682}
683
684// ---- 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
685// warp needs only its own 64-byte slice of each K and V row: it gathers it itself with cp.async into its own
686// double-buffered stage while it computes the previous chunk, and q stays in registers. Only the q.k partial sums
687// (one per dim group) cross warps, and they are added in a fixed order: the result is deterministic.
688constexpr int CH2 = 32;
689
690struct Smem2 {
691    int8_t kv[2][4][2][CH2][64];   // stage, warp, K/V, cell, 64 dims in 16-byte pieces XOR-swizzled by the cell
692    float sc[2][4][2][CH2];        // stage, warp, K/V scale of the cell for the warp's group
693    float part[4][16][CH2 + 1];    // q.k per dim group
694    float p[16][CH2 + 1];
695    float qmax[4];
696    float alpha[16];
697    float lsum[16];
698    float mrow[16];
699};
700
701__dpct_inline__ int
702swz(int cell, int byte) { // byte offset of (cell, byte) in a stage slice
703    return cell * 64 + ((((byte >> 4) ^ (cell >> 1)) & 3) << 4) + (byte & 15);
704}
705__dpct_inline__ void cp_async16(void *smem, const void *gmem, bool valid) {
706#if !STRATA_PA_SM80
707    /* unreachable on SYCL: the launcher refuses this device */
708#else
709    auto sa = smem;
710    /*
711    DPCT1053: Migration of device assembly code is not supported.
712    */
713    asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"(sa),
714                 "l"(gmem), "r"(valid ? 16 : 0));
715#endif
716}
717__dpct_inline__ void cp_async_commit() {
718#if STRATA_PA_SM80
719#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
720    asm volatile("cp.async.commit_group;\n" ::);
721#else
722
723#endif
724#endif
725}
726__dpct_inline__ void cp_async_wait1() {
727#if STRATA_PA_SM80
728#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
729    asm volatile("cp.async.wait_group 1;\n" ::);
730#else
731
732#endif
733#endif
734}
735
736/*
737DPCT1110: The total declared local variable size in device function
738prompt_attn_i8_kernel exceeds 128 bytes and may cause high register pressure.
739Consult with your hardware vendor to find the total register size available and
740adjust the code, or use smaller sub-group size to avoid high register pressure.
741*/
742__dpct_inline__ void
743prompt_attn_i8_kernel(const float *__restrict__ q, QsaAttnPools p,
744                      const int32_t *__restrict__ ids,
745                      const int32_t *__restrict__ steps, int n_kv_heads,
746                      int page_size, float scale_log2, float *__restrict__ attn,
747                      int cap, uint8_t *dpct_local) {
748    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
749    auto smem_raw = (unsigned char *)dpct_local;
750    Smem2& S = *reinterpret_cast<Smem2*>(smem_raw);
751    const int qi = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
752    const int n_head = n_kv_heads * G;
753    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
754    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
755    ids += (size_t) qi * cap;
756    /*
757    DPCT1098: The '*' expression is used instead of the __ldg call. These
758    two expressions do not provide the exact same functionality. Check the
759    generated code for potential precision and/or performance issues.
760    */
761    const int n = *(steps + (size_t)qi * kStepCount + kStepWidth);
762    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
763    const int gid = lane >> 2, tig = lane & 3;
764    const int dim0 = warp * 64;
765
766    // q: the power-of-two prescale over all 12 heads (as v1), then this warp's 64 dims as hi/lo A fragments
767    float qm = 0.0f;
768#pragma unroll
769    for (int i = t; i < G * HD; i += THREADS)
770        qm = sycl::fmax(qm, sycl::fabs(q[i]));
771#pragma unroll
772    /*
773    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
774    masked sub_group function which may not be supported by all compilers or
775    runtimes. You may need to adjust the code.
776    */
777    for (int o = 16; o > 0; o >>= 1) qm = sycl::fmax(
778        qm, dpct::experimental::permute_sub_group_by_xor(
779                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
780                qm, o));
781    if (lane == 0) S.qmax[warp] = qm;
782    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
783    /*
784    DPCT1065: Consider replacing sycl::nd_item::barrier() with
785    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
786    performance if there is no access to global memory.
787    */
788    item_ct1.barrier();
789    qm = sycl::fmax(sycl::fmax(S.qmax[0], S.qmax[1]),
790                    sycl::fmax(S.qmax[2], S.qmax[3]));
791    int qe = 0;
792    /*
793    DPCT1017: The sycl::frexp call is used instead of the frexpf call.
794    These two calls do not provide exactly the same functionality. Check the
795    potential precision and/or performance issues for the generated code.
796    */
797    if (qm > 0.0f) sycl::frexp(
798        qm, sycl::address_space_cast<sycl::access::address_space::generic_space,
799                                     sycl::access::decorated::yes>(&qe));
800    const float qup = sycl::ldexp(1.0f, 14 - qe),
801                qdown = sycl::ldexp(scale_log2, qe - 14);
802    uint32_t qh[4][4], ql[4][4];
803#pragma unroll
804    for (int kk = 0; kk < 4; ++kk) {
805#pragma unroll
806        for (int r = 0; r < 4; ++r) {
807            const int row = gid + (r & 1) * 8, col = dim0 + kk * 16 + 2 * tig + (r >> 1) * 8;
808            sycl::float2 x = sycl::float2(0.f, 0.f);
809            if (row < G) x = *reinterpret_cast<const sycl::float2 *>(
810                q + (size_t)row * HD + col);
811            x.x() *= qup;
812            x.y() *= qup;
813            const sycl::half2 hi =
814                sycl::float2(x.x(), x.y())
815                    .convert<sycl::half, sycl::rounding_mode::rte>();
816            const sycl::float2 hf =
817                hi.template convert<float, sycl::rounding_mode::automatic>();
818            const sycl::half2 lo =
819                sycl::float2(x.x() - hf.x(), x.y() - hf.y())
820                    .convert<sycl::half, sycl::rounding_mode::rte>();
821            qh[kk][r] = *reinterpret_cast<const uint32_t*>(&hi);
822            ql[kk][r] = *reinterpret_cast<const uint32_t*>(&lo);
823        }
824    }
825
826    // the chunk pipeline: cells two chunks ahead, their pool rows one chunk ahead, the data (cp.async) one ahead
827    const int n_chunks = (n + CH2 - 1) / CH2;
828    /*
829    DPCT1098: The '*' expression is used instead of the __ldg call. These
830    two expressions do not provide the exact same functionality. Check the
831    generated code for potential precision and/or performance issues.
832    */
833    auto cell_of = [&](int c) -> int {
834                                       return c < n ? *(ids + c) : -1;
835    };
836    auto row_of = [&](int cell) -> long long {
837        if (cell < 0) return -1;
838        /*
839        DPCT1098: The '*' expression is used instead of the __ldg call.
840        These two expressions do not provide the exact same functionality. Check
841        the generated code for potential precision and/or performance issues.
842        */
843        const long long page = (long long)*(p.page_table + cell / page_size);
844        return (page * n_kv_heads + kvh) * page_size + (cell % page_size);
845    };
846    auto issue = [&](long long r, int st, float& ksr, float& vsr) {
847#pragma unroll
848        for (int j = 0; j < 4; ++j) {
849            const int idx = lane + 32 * j, cell = idx >> 2, pc = idx & 3;
850            /*
851            DPCT1108: '__shfl_sync' was migrated with the experimental
852            feature masked sub_group function which may not be supported by all
853            compilers or runtimes. You may need to adjust the code.
854            */
855            /*
856            DPCT1121: Make sure that the "r" which is used in the SYCL group
857            function/algorithm is initialized.
858            */
859            const long long rr = dpct::experimental::select_from_sub_group(
860                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
861                r, cell);
862            const bool ok = rr >= 0;
863            const size_t off = ok ? (size_t) rr * HD + dim0 + pc * 16 : 0;
864            cp_async16(&S.kv[st][warp][0][0][0] + swz(cell, pc * 16), p.k_q + off, ok);
865            cp_async16(&S.kv[st][warp][1][0][0] + swz(cell, pc * 16), p.v_q + off, ok);
866        }
867        /*
868        DPCT1098: The '*' expression is used instead of the __ldg call.
869        These two expressions do not provide the exact same functionality. Check
870        the generated code for potential precision and/or performance issues.
871        */
872        ksr = r >= 0 ? sycl::vec<sycl::half, 1>(
873                           sycl::bit_cast<sycl::half, unsigned short>(
874                               *(p.k_scale + r * (HD / KV_Q8_GROUP) + warp)))
875                           .convert<float, sycl::rounding_mode::automatic>()[0]
876                     : 0.0f;
877        /*
878        DPCT1098: The '*' expression is used instead of the __ldg call.
879        These two expressions do not provide the exact same functionality. Check
880        the generated code for potential precision and/or performance issues.
881        */
882        vsr = r >= 0 ? sycl::vec<sycl::half, 1>(
883                           sycl::bit_cast<sycl::half, unsigned short>(
884                               *(p.v_scale + r * (HD / KV_Q8_GROUP) + warp)))
885                           .convert<float, sycl::rounding_mode::automatic>()[0]
886                     : 0.0f;
887    };
888    float ksn, vsn;
889    issue(row_of(cell_of(lane)), 0, ksn, vsn);
890    cp_async_commit();
891    S.sc[0][warp][0][lane] = ksn;
892    S.sc[0][warp][1][lane] = vsn;
893    long long r_next = row_of(cell_of(CH2 + lane));
894    int cell_next2 = cell_of(2 * CH2 + lane);
895
896    float acc[8][4];
897#pragma unroll
898    for (int j = 0; j < 8; ++j) acc[j][0] = acc[j][1] = acc[j][2] = acc[j][3] = 0.0f;
899
900    for (int ci = 0; ci < n_chunks; ++ci) {
901        const int st = ci & 1, c0 = ci * CH2;
902        const bool more = ci + 1 < n_chunks;
903        if (more) issue(r_next, st ^ 1, ksn, vsn);
904        cp_async_commit();
905        r_next = row_of(cell_next2);
906        cell_next2 = cell_of((ci + 3) * CH2 + lane);
907        cp_async_wait1();
908        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
909        const int8_t* K = &S.kv[st][warp][0][0][0];
910        const int8_t* V = &S.kv[st][warp][1][0][0];
911        // q.k over this warp's 64 dims, times the cell's K scale for this group
912#pragma unroll
913        for (int nt = 0; nt < CH2 / 8; ++nt) {
914            float tg[4] = {0.f, 0.f, 0.f, 0.f};
915            const int cell = nt * 8 + gid;
916#pragma unroll
917            for (int kk = 0; kk < 4; ++kk) {
918                uint32_t b[2];
919                b[0] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig)));
920                b[1] = i8x2_to_h2(*reinterpret_cast<const uint16_t*>(K + swz(cell, kk * 16 + 2 * tig + 8)));
921                mma16816(tg, qh[kk], b);
922                mma16816(tg, ql[kk], b);
923            }
924            const int c = nt * 8 + 2 * tig;
925            const float s0 = S.sc[st][warp][0][c], s1 = S.sc[st][warp][0][c + 1];
926            S.part[warp][gid][c] = tg[0] * s0;
927            S.part[warp][gid][c + 1] = tg[1] * s1;
928            S.part[warp][gid + 8][c] = tg[2] * s0;
929            S.part[warp][gid + 8][c + 1] = tg[3] * s1;
930        }
931        /*
932        DPCT1118: SYCL group functions and algorithms must be encountered in
933        converged control flow. You may need to adjust the code.
934        */
935        /*
936        DPCT1065: Consider replacing sycl::nd_item::barrier() with
937        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
938        better performance if there is no access to global memory.
939        */
940        item_ct1.barrier();
941        // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
942        {
943            const int r = t >> 3, sub = t & 7;
944            float x[4], mx = -INFINITY;
945#pragma unroll
946            for (int j = 0; j < 4; ++j) {
947                const int c = sub * 4 + j;
948                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
949                                  : -INFINITY;
950                mx = sycl::fmax(mx, x[j]);
951            }
952#pragma unroll
953            /*
954            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
955            feature masked sub_group function which may not be supported by all
956            compilers or runtimes. You may need to adjust the code.
957            */
958            for (int o = 1; o < 8; o <<= 1) mx = sycl::fmax(
959                mx,
960                dpct::experimental::permute_sub_group_by_xor(
961                    0xffffffffu,
962                    sycl::ext::oneapi::this_work_item::get_sub_group(), mx, o));
963            const float m_old = S.mrow[r];
964            const float m_new = sycl::fmax(m_old, mx);
965            float sum = 0.0f;
966#pragma unroll
967            for (int j = 0; j < 4; ++j) {
968                const float e =
969                    x[j] == -INFINITY ? 0.0f : sycl::exp2(x[j] - m_new);
970                S.p[r][sub * 4 + j] = e;
971                sum += e;
972            }
973#pragma unroll
974            /*
975            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
976            feature masked sub_group function which may not be supported by all
977            compilers or runtimes. You may need to adjust the code.
978            */
979            for (int o = 1; o < 8; o <<= 1) sum +=
980                dpct::experimental::permute_sub_group_by_xor(
981                    0xffffffffu,
982                    sycl::ext::oneapi::this_work_item::get_sub_group(), sum, o);
983            sycl::group_barrier(
984                sycl::ext::oneapi::this_work_item::get_sub_group());
985            if (sub == 0) {
986                const float a =
987                    m_old == -INFINITY ? 0.0f : sycl::exp2(m_old - m_new);
988                S.alpha[r] = a;
989                S.lsum[r] = sycl::fma(S.lsum[r], (float)a, sum);
990                S.mrow[r] = m_new;
991            }
992        }
993        /*
994        DPCT1118: SYCL group functions and algorithms must be encountered in
995        converged control flow. You may need to adjust the code.
996        */
997        /*
998        DPCT1065: Consider replacing sycl::nd_item::barrier() with
999        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
1000        better performance if there is no access to global memory.
1001        */
1002        item_ct1.barrier();
1003        // p.v over this warp's 64 dims (as v1)
1004        {
1005            float vmax = S.sc[st][warp][1][lane];
1006#pragma unroll
1007            /*
1008            DPCT1108: '__shfl_xor_sync' was migrated with the experimental
1009            feature masked sub_group function which may not be supported by all
1010            compilers or runtimes. You may need to adjust the code.
1011            */
1012            for (int o = 16; o > 0; o >>= 1) vmax = sycl::fmax(
1013                vmax, dpct::experimental::permute_sub_group_by_xor(
1014                          0xffffffffu,
1015                          sycl::ext::oneapi::this_work_item::get_sub_group(),
1016                          vmax, o));
1017            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
1018            float tmp[8][4];
1019#pragma unroll
1020            for (int j = 0; j < 8; ++j) tmp[j][0] = tmp[j][1] = tmp[j][2] = tmp[j][3] = 0.0f;
1021#pragma unroll
1022            for (int ks = 0; ks < CH2 / 16; ++ks) {
1023                const int cA = ks * 16 + 2 * tig, cB = cA + 8;
1024                const float w0 = S.sc[st][warp][1][cA] * vup, w1 = S.sc[st][warp][1][cA + 1] * vup,
1025                            w2 = S.sc[st][warp][1][cB] * vup, w3 = S.sc[st][warp][1][cB + 1] * vup;
1026                const float p00 = S.p[gid][cA] * w0, p01 = S.p[gid][cA + 1] * w1;
1027                const float p10 = S.p[gid + 8][cA] * w0, p11 = S.p[gid + 8][cA + 1] * w1;
1028                const float p02 = S.p[gid][cB] * w2, p03 = S.p[gid][cB + 1] * w3;
1029                const float p12 = S.p[gid + 8][cB] * w2, p13 = S.p[gid + 8][cB + 1] * w3;
1030                uint32_t ah[4], al[4];
1031                ah[0] = pack_h2(p00, p01);
1032                ah[1] = pack_h2(p10, p11);
1033                ah[2] = pack_h2(p02, p03);
1034                ah[3] = pack_h2(p12, p13);
1035                {
1036                    const sycl::half2 *h =
1037                        reinterpret_cast<const sycl::half2 *>(ah);
1038                    sycl::float2 f;
1039                    f = h[0].template convert<float,
1040                                              sycl::rounding_mode::automatic>();
1041                        al[0] = pack_h2(p00 - f.x(), p01 - f.y());
1042                    f = h[1].template convert<float,
1043                                              sycl::rounding_mode::automatic>();
1044                        al[1] = pack_h2(p10 - f.x(), p11 - f.y());
1045                    f = h[2].template convert<float,
1046                                              sycl::rounding_mode::automatic>();
1047                        al[2] = pack_h2(p02 - f.x(), p03 - f.y());
1048                    f = h[3].template convert<float,
1049                                              sycl::rounding_mode::automatic>();
1050                        al[3] = pack_h2(p12 - f.x(), p13 - f.y());
1051                }
1052#pragma unroll
1053                for (int j = 0; j < 8; ++j) {
1054                    const int d = j * 8 + gid;
1055                    const uint32_t x0 = (uint8_t) V[swz(cA, d)] | ((uint32_t) (uint8_t) V[swz(cA + 1, d)] << 8);
1056                    const uint32_t x1 = (uint8_t) V[swz(cB, d)] | ((uint32_t) (uint8_t) V[swz(cB + 1, d)] << 8);
1057                    uint32_t b[2];
1058                    b[0] = i8x2_to_h2(x0);
1059                    b[1] = i8x2_to_h2(x1);
1060                    mma16816(tmp[j], ah, b);
1061                    mma16816(tmp[j], al, b);
1062                }
1063            }
1064            const float a0 = S.alpha[gid], a1 = S.alpha[gid + 8];
1065#pragma unroll
1066            for (int j = 0; j < 8; ++j) {
1067                acc[j][0] = sycl::fma(acc[j][0], (float)a0, tmp[j][0] * vdown);
1068                acc[j][1] = sycl::fma(acc[j][1], (float)a0, tmp[j][1] * vdown);
1069                acc[j][2] = sycl::fma(acc[j][2], (float)a1, tmp[j][2] * vdown);
1070                acc[j][3] = sycl::fma(acc[j][3], (float)a1, tmp[j][3] * vdown);
1071            }
1072        }
1073        if (more) {
1074            S.sc[st ^ 1][warp][0][lane] = ksn;
1075            S.sc[st ^ 1][warp][1][lane] = vsn;
1076        }
1077        sycl::group_barrier(sycl::ext::oneapi::this_work_item::get_sub_group());
1078    }
1079    /*
1080    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1081    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1082    performance if there is no access to global memory.
1083    */
1084    item_ct1.barrier();
1085    const float l0 = S.lsum[gid], l1 = S.lsum[gid + 8];
1086    const float i0 = l0 > 0.0f ? 1.0f / l0 : 0.0f, i1 = l1 > 0.0f ? 1.0f / l1 : 0.0f;
1087#pragma unroll
1088    for (int j = 0; j < 8; ++j) {
1089        const int d = dim0 + j * 8 + 2 * tig;
1090        *reinterpret_cast<sycl::float2 *>(attn + (size_t)gid * HD + d) =
1091            sycl::float2(acc[j][0] * i0, acc[j][1] * i0);
1092        if (gid + 8 < G)
1093            *reinterpret_cast<sycl::float2 *>(attn + (size_t)(gid + 8) * HD +
1094                                              d) =
1095                sycl::float2(acc[j][2] * i1, acc[j][3] * i1);
1096    }
1097}
1098
1099bool launch_i8(const float *q, const QsaAttnPools &pools, const int32_t *ids,
1100               const int32_t *steps, int64_t cap, const QsaShapes &s,
1101               float *attn, int64_t n_q, dpct::queue_ptr st) try {
1102    static bool attr[64] = {};   // the shared-memory opt-in is per device (a layer split runs this on several)
1103    int dev = 0;
1104    dev = dpct::get_current_device_id();
1105    /*
1106    DPCT1083: The size of local memory in the migrated code may be different
1107    from the original code. Check that the allocated memory size in the migrated
1108    code is correct.
1109    */
1110    const int bytes = (int)sizeof(Smem2);
1111    if (dev < 0 || dev >= 64) return false;
1112    if (!attr[dev]) {
1113        /*
1114        DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
1115        because SYCL currently does not support corresponding setting.
1116        */
1117        if (0 != 0) {
1118            /*
1119            DPCT1026: The call to cudaGetLastError was removed because this
1120            functionality is redundant in SYCL.
1121            */
1122            return false;
1123        }
1124        attr[dev] = true;
1125    }
1126    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1127    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1128        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1129        {
1130            auto exp_props = sycl::ext::oneapi::experimental::properties{
1131                sycl::ext::oneapi::experimental::use_root_sync};
1132            dpct::has_capability_or_fail(st->get_device(),
1133                                         {sycl::aspect::fp16});
1134
1135            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1136                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1137                    sycl::range(bytes), cgh);
1138
1139                auto q_q0_s_n_head_HD_ct0 = q + q0 * s.n_head * HD;
1140                auto ids_q0_cap_ct2 = ids + q0 * cap;
1141                auto steps_q0_kStepCount_ct3 = steps + q0 * kStepCount;
1142                auto attn_q0_s_n_head_HD_ct7 = attn + q0 * s.n_head * HD;
1143
1144                cgh.parallel_for<
1145                    dpct_kernel_name<class prompt_attn_i8_kernel_c3d463>>(
1146                    sycl::nd_range<3>(
1147                        sycl::range(1, (unsigned)s.n_head_kv, (unsigned)nb) *
1148                            sycl::range(1, 1, THREADS),
1149                        sycl::range(1, 1, THREADS)),
1150                    exp_props,
1151                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
1152                        32)]] {
1153                        prompt_attn_i8_kernel(
1154                            q_q0_s_n_head_HD_ct0, pools, ids_q0_cap_ct2,
1155                            steps_q0_kStepCount_ct3, (int)s.n_head_kv,
1156                            (int)s.page_size, scale_log2,
1157                            attn_q0_s_n_head_HD_ct7, (int)cap,
1158                            dpct_local_acc_ct1
1159                                .get_multi_ptr<sycl::access::decorated::no>()
1160                                .get());
1161                    });
1162            });
1163        }
1164    }
1165    /*
1166    DPCT1010: SYCL uses exceptions to report errors and does not use the
1167    error codes. The cudaGetLastError function call was replaced with 0. You
1168    need to rewrite this code.
1169    */
1170    const dpct::err0 e = 0;
1171
1172    return true;
1173}
1174catch (sycl::exception const &exc) {
1175  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1176            << ", line:" << __LINE__ << std::endl;
1177  std::exit(1);
1178}
1179
1180template <int KV_MODE>
1181bool launch(const float *q, const QsaAttnPools &pools, const int32_t *ids,
1182            const int32_t *steps, int64_t cap, const QsaShapes &s, float *attn,
1183            int64_t n_q, dpct::queue_ptr st) try {
1184    static bool attr[64] = {};   // per device, as above
1185    int dev = 0;
1186    dev = dpct::get_current_device_id();
1187    /*
1188    DPCT1083: The size of local memory in the migrated code may be different
1189    from the original code. Check that the allocated memory size in the migrated
1190    code is correct.
1191    */
1192    const int bytes = (int)sizeof(Smem<KV_MODE>);
1193    if (dev < 0 || dev >= 64) return false;
1194    if (!attr[dev]) {
1195        /*
1196        DPCT1027: The call to cudaFuncSetAttribute was replaced with 0
1197        because SYCL currently does not support corresponding setting.
1198        */
1199        if (0 != 0) {
1200            /*
1201            DPCT1026: The call to cudaGetLastError was removed because this
1202            functionality is redundant in SYCL.
1203            */
1204            return false;
1205        }
1206        attr[dev] = true;
1207    }
1208    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1209    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1210        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1211        {
1212            auto exp_props = sycl::ext::oneapi::experimental::properties{
1213                sycl::ext::oneapi::experimental::use_root_sync};
1214            dpct::has_capability_or_fail(st->get_device(),
1215                                         {sycl::aspect::fp16});
1216
1217            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1218                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1219                    sycl::range(bytes), cgh);
1220
1221                auto q_q0_s_n_head_HD_ct0 = q + q0 * s.n_head * HD;
1222                auto ids_q0_cap_ct2 = ids + q0 * cap;
1223                auto steps_q0_kStepCount_ct3 = steps + q0 * kStepCount;
1224                auto attn_q0_s_n_head_HD_ct7 = attn + q0 * s.n_head * HD;
1225
1226                cgh.parallel_for<
1227                    dpct_kernel_name<class prompt_attn_kernel_e09b15,
1228                                     dpct_kernel_scalar<KV_MODE>>>(
1229                    sycl::nd_range<3>(
1230                        sycl::range(1, (unsigned)s.n_head_kv, (unsigned)nb) *
1231                            sycl::range(1, 1, THREADS),
1232                        sycl::range(1, 1, THREADS)),
1233                    exp_props,
1234                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
1235                        32)]] {
1236                        prompt_attn_kernel<KV_MODE>(
1237                            q_q0_s_n_head_HD_ct0, pools, ids_q0_cap_ct2,
1238                            steps_q0_kStepCount_ct3, (int)s.n_head_kv,
1239                            (int)s.page_size, scale_log2,
1240                            attn_q0_s_n_head_HD_ct7, (int)cap,
1241                            dpct_local_acc_ct1
1242                                .get_multi_ptr<sycl::access::decorated::no>()
1243                                .get());
1244                    });
1245            });
1246        }
1247    }
1248    /*
1249    DPCT1010: SYCL uses exceptions to report errors and does not use the
1250    error codes. The cudaGetLastError function call was replaced with 0. You
1251    need to rewrite this code.
1252    */
1253    const dpct::err0 e = 0;
1254
1255    return true;
1256}
1257catch (sycl::exception const &exc) {
1258  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1259            << ", line:" << __LINE__ << std::endl;
1260  std::exit(1);
1261}
1262
1263// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a
1264// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before).
1265#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
1266// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------
1267// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per
1268// 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
1269// 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
1270// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1),
1271// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile.
1272//   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
1273//        of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the
1274//        cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic).
1275//   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
1276//        steps of 4; p carries the V scale (as v1) and is split into hi + lo halves.
1277#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750
1278#define STRATA_PA_VOLTA 1
1279#else
1280#define STRATA_PA_VOLTA 0
1281#endif
1282
1283__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) {
1284#if STRATA_PA_VOLTA
1285    asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, "
1286                 "{%0,%1,%2,%3,%4,%5,%6,%7};\n"
1287                 : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7])
1288                 : "r"(a0), "r"(a1), "r"(b0), "r"(b1));
1289#else
1290    /* unreachable on SYCL: the launcher refuses this device */   // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70
1291#endif
1292}
1293
1294template <int KV_MODE>
1295struct Smem70 {
1296    using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
1297    using VElem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;
1298    static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;
1299    static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;
1300    __half qh[16][QS];
1301    __half ql[16][QS];
1302    KElem k[CH][KROW];
1303    VElem v[CH][VROW];
1304    float ks[CH][4];
1305    float vs[CH][4];
1306    float part[4][16][CH + 4];   // q.k per dim group (scaled by the cell's K scale)
1307    float s[16][CH + 4];         // the chunk's probabilities
1308    float qmax[THREADS / 32];
1309    float alpha[16];
1310    float lsum[16];
1311    float mrow[16];
1312    long long row[CH];
1313};
1314
1315template <int KV_MODE>
1316__global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* __restrict__ q, QsaAttnPools p,
1317                                                                  const int32_t* __restrict__ ids,
1318                                                                  const int32_t* __restrict__ steps, int n_kv_heads,
1319                                                                  int page_size, float scale_log2,
1320                                                                  float* __restrict__ attn, int cap) {
1321    extern __shared__ __align__(16) unsigned char smem_raw[];
1322    Smem70<KV_MODE>& S = *reinterpret_cast<Smem70<KV_MODE>*>(smem_raw);
1323    const int qi = blockIdx.x, kvh = blockIdx.y;
1324    const int n_head = n_kv_heads * G;
1325    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1326    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1327    ids += (size_t) qi * cap;
1328    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
1329    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1330    const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4);   // quad-pair, thread within it
1331    const int crow = (lane & 1) + 4 * (lane >> 4);                        // C row of register 0 (+2 per register pair)
1332    const int ccol = lane & 2;                                           // C column of register 0 (+4 per half, +1 per reg)
1333
1334    // q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
1335    // lo halves stay out of FP16's subnormal range), then split into hi + lo halves
1336    float qm = 0.0f;
1337    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
1338#pragma unroll
1339    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
1340    if (lane == 0) S.qmax[warp] = qm;
1341    __syncthreads();
1342    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
1343    int qe = 0;
1344    if (qm > 0.0f) frexpf(qm, &qe);                 // qm < 2^qe
1345    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
1346    for (int i = t; i < 16 * HD; i += THREADS) {
1347        const int h = i / HD, d = i % HD;
1348        const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
1349        const __half hi = __float2half_rn(x);
1350        S.qh[h][d] = hi;
1351        S.ql[h][d] = __float2half_rn(x - __half2float(hi));
1352    }
1353    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
1354
1355    float acc[2][2][8];
1356#pragma unroll
1357    for (int rb = 0; rb < 2; ++rb)
1358#pragma unroll
1359        for (int nt = 0; nt < 2; ++nt)
1360#pragma unroll
1361            for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;
1362
1363    for (int c0 = 0; c0 < n; c0 += CH) {
1364        const int nh = min(CH, n - c0);
1365        if (t < CH) {
1366            long long r = -1;
1367            if (t < nh) {
1368                const int cell = ids[c0 + t];
1369                const long long page = (long long) p.page_table[cell / page_size];
1370                r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1371            }
1372            S.row[t] = r;
1373        }
1374        __syncthreads();   // rows ready; the previous chunk's p.v is done with k, v, s
1375        // gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
1376        // and their scales
1377        {
1378            constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16;   // per K row
1379            for (int i = t; i < CH * KPIECES; i += THREADS) {
1380                const int c = i / KPIECES, pc = i % KPIECES;
1381                const long long r = S.row[c];
1382                uint4 kx = make_uint4(0, 0, 0, 0);
1383                if (r >= 0) {
1384                    if constexpr (KV_MODE == 0)
1385                        kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
1386                    else   // modes 1 and 3: the K side is INT8
1387                        kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
1388                }
1389                *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;
1390            }
1391            if constexpr (KV_MODE == 3) {   // V: dequantize the row's q4_0 blocks straight into the fp16 V row
1392                constexpr int BLKS = HD / QK4_0;
1393                constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
1394                for (int i = t; i < CH * BLKS; i += THREADS) {
1395                    const int c = i / BLKS, b = i % BLKS;
1396                    const long long r = S.row[c];
1397#pragma unroll
1398                    for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);
1399                    if (r >= 0) {
1400                        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
1401                        const float d = __half2float(__ushort_as_half(blk->d));
1402#pragma unroll
1403                        for (int j = 0; j < QK4_0 / 2; ++j) {
1404                            S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
1405                            S.v[c][b * QK4_0 + j + QK4_0 / 2] =
1406                                __float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
1407                        }
1408                    }
1409                }
1410            } else {
1411                constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16;   // per V row
1412                for (int i = t; i < CH * VPIECES; i += THREADS) {
1413                    const int c = i / VPIECES, pc = i % VPIECES;
1414                    const long long r = S.row[c];
1415                    uint4 vx = make_uint4(0, 0, 0, 0);
1416                    if (r >= 0) {
1417                        if constexpr (KV_MODE == 1)
1418                            vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
1419                        else
1420                            vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
1421                    }
1422                    *reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;
1423                }
1424            }
1425            for (int i = t; i < CH * 4; i += THREADS) {
1426                const int c = i / 4, g = i % 4;
1427                const long long r = S.row[c];
1428                float a = 0.0f, b = 0.0f;
1429                if (r >= 0) {
1430                    if constexpr (KV_MODE == 1) {
1431                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
1432                        b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
1433                    } else if constexpr (KV_MODE == 3) {   // K as int8, V dequantized to fp16 (scale 1)
1434                        a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
1435                        b = 1.0f;
1436                    } else {
1437                        a = b = 1.0f;
1438                    }
1439                }
1440                S.ks[c][g] = a;
1441                S.vs[c][g] = b;
1442            }
1443        }
1444        __syncthreads();
1445        // scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7
1446        {
1447            float tg[2][8];
1448#pragma unroll
1449            for (int rb = 0; rb < 2; ++rb)
1450#pragma unroll
1451                for (int i = 0; i < 8; ++i) tg[rb][i] = 0.0f;
1452            const int cell_b = qp * 8 + jj;
1453#pragma unroll
1454            for (int ks = 0; ks < 16; ++ks) {
1455                const int d0 = warp * 64 + ks * 4;
1456                uint32_t b0, b1;
1457                if constexpr (KV_MODE != 0) {   // modes 1 and 3: the K side is INT8 codes, exact in FP16
1458                    const uint32_t raw = *reinterpret_cast<const uint32_t*>(&S.k[cell_b][d0]);
1459                    b0 = i8x2_to_h2(raw & 0xffffu);
1460                    b1 = i8x2_to_h2(raw >> 16);
1461                } else {
1462                    const uint2 raw = *reinterpret_cast<const uint2*>(&S.k[cell_b][d0]);
1463                    b0 = raw.x;
1464                    b1 = raw.y;
1465                }
1466#pragma unroll
1467                for (int rb = 0; rb < 2; ++rb) {
1468                    const uint2 ah = *reinterpret_cast<const uint2*>(&S.qh[rb * 8 + jj][d0]);
1469                    const uint2 al = *reinterpret_cast<const uint2*>(&S.ql[rb * 8 + jj][d0]);
1470                    mma884(tg[rb], ah.x, ah.y, b0, b1);
1471                    mma884(tg[rb], al.x, al.y, b0, b1);
1472                }
1473            }
1474#pragma unroll
1475            for (int rb = 0; rb < 2; ++rb)
1476#pragma unroll
1477                for (int i = 0; i < 8; ++i) {
1478                    const int row = rb * 8 + crow + 2 * ((i >> 1) & 1);
1479                    const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1);
1480                    S.part[warp][row][cell] = tg[rb][i] * S.ks[cell][warp];
1481                }
1482        }
1483        __syncthreads();
1484        // online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
1485        {
1486            constexpr int PER = CH / 8;
1487            const int r = t >> 3, sub = t & 7;
1488            float x[PER], mx = -INFINITY;
1489#pragma unroll
1490            for (int j = 0; j < PER; ++j) {
1491                const int c = sub * PER + j;
1492                const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c];
1493                x[j] = c < nh ? sum4 * qdown : -INFINITY;
1494                mx = fmaxf(mx, x[j]);
1495            }
1496#pragma unroll
1497            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
1498            const float m_old = S.mrow[r];
1499            const float m_new = fmaxf(m_old, mx);
1500            float sum = 0.0f;
1501#pragma unroll
1502            for (int j = 0; j < PER; ++j) {
1503                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
1504                S.s[r][sub * PER + j] = e;
1505                sum += e;
1506            }
1507#pragma unroll
1508            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
1509            __syncwarp();
1510            if (sub == 0) {
1511                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
1512                S.alpha[r] = a;
1513                S.lsum[r] = fmaf(S.lsum[r], a, sum);
1514                S.mrow[r] = m_new;
1515            }
1516        }
1517        __syncthreads();
1518        __syncthreads();
1519        // 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
1520        // into p relative to the chunk's largest, times 2^14 (as v1)
1521        {
1522            float vmax = 0.0f;
1523#pragma unroll
1524            for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);
1525#pragma unroll
1526            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
1527            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
1528            float tmp[2][2][8];
1529#pragma unroll
1530            for (int rb = 0; rb < 2; ++rb)
1531#pragma unroll
1532                for (int nt = 0; nt < 2; ++nt)
1533#pragma unroll
1534                    for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = 0.0f;
1535#pragma unroll
1536            for (int ks = 0; ks < CH / 4; ++ks) {
1537                const int c0 = ks * 4;
1538                float w[4];
1539#pragma unroll
1540                for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup;
1541                uint2 ah[2], al[2];
1542#pragma unroll
1543                for (int rb = 0; rb < 2; ++rb) {
1544                    const float4 pv = *reinterpret_cast<const float4*>(&S.s[rb * 8 + jj][c0]);
1545                    const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3];
1546                    ah[rb].x = pack_h2(p0, p1);
1547                    ah[rb].y = pack_h2(p2, p3);
1548                    const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].x));
1549                    const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].y));
1550                    al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y);
1551                    al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y);
1552                }
1553#pragma unroll
1554                for (int nt = 0; nt < 2; ++nt) {
1555                    const int d = warp * 64 + qp * 16 + nt * 8 + jj;
1556                    uint32_t b0, b1;
1557                    if constexpr (KV_MODE == 1) {
1558                        const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8);
1559                        const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8);
1560                        b0 = i8x2_to_h2(x0);
1561                        b1 = i8x2_to_h2(x1);
1562                    } else {
1563                        const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]);
1564                        const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]);
1565                        b0 = *reinterpret_cast<const uint32_t*>(&h0);
1566                        b1 = *reinterpret_cast<const uint32_t*>(&h1);
1567                    }
1568#pragma unroll
1569                    for (int rb = 0; rb < 2; ++rb) {
1570                        mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1);
1571                        mma884(tmp[rb][nt], al[rb].x, al[rb].y, b0, b1);
1572                    }
1573                }
1574            }
1575#pragma unroll
1576            for (int rb = 0; rb < 2; ++rb) {
1577                float a_[2];
1578                a_[0] = S.alpha[rb * 8 + crow];
1579                a_[1] = S.alpha[rb * 8 + crow + 2];
1580#pragma unroll
1581                for (int nt = 0; nt < 2; ++nt)
1582#pragma unroll
1583                    for (int i = 0; i < 8; ++i)
1584                        acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], tmp[rb][nt][i] * vdown);
1585            }
1586        }
1587    }
1588    __syncthreads();
1589#pragma unroll
1590    for (int rb = 0; rb < 2; ++rb)
1591#pragma unroll
1592        for (int h = 0; h < 2; ++h) {
1593            const int row = rb * 8 + crow + 2 * h;
1594            if (row >= G) continue;
1595            const float l = S.lsum[row];
1596            const float inv = l > 0.0f ? 1.0f / l : 0.0f;
1597#pragma unroll
1598            for (int nt = 0; nt < 2; ++nt)
1599#pragma unroll
1600                for (int hh = 0; hh < 2; ++hh) {
1601                    const int i = hh * 4 + h * 2;               // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1}
1602                    const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh;
1603                    *reinterpret_cast<float2*>(attn + (size_t) row * HD + d) =
1604                        make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv);
1605                }
1606        }
1607}
1608
1609template <int KV_MODE>
1610bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1611              const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1612    static bool attr[64] = {};
1613    int dev = 0;
1614    cudaGetDevice(&dev);
1615    const int bytes = (int) sizeof(Smem70<KV_MODE>);
1616    if (dev < 0 || dev >= 64) return false;
1617    if (!attr[dev]) {
1618        if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
1619            cudaSuccess) {
1620            cudaGetLastError();
1621            return false;
1622        }
1623        attr[dev] = true;
1624    }
1625    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1626    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1627        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1628        prompt_attn_v70_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
1629            q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1630            (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1631    }
1632    const cudaError_t e = cudaGetLastError();
1633    if (e != cudaSuccess) {
1634        std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e));
1635        std::exit(1);
1636    }
1637    return true;
1638}
1639#else   // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)
1640template <int KV_MODE>
1641bool launch70(const float *, const QsaAttnPools &, const int32_t *,
1642              const int32_t *, int64_t, const QsaShapes &, float *, int64_t,
1643              dpct::queue_ptr) {
1644    return false;
1645}
1646#endif  // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60
1647
1648#if defined(__HIPCC__)
1649// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of
1650// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims
1651// [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
1652// exactly as FP16, the scales are applied in FP32 and the four groups' q.k partials are added in a fixed order.
1653// FP32-level accuracy, deterministic, but not bitwise equal to qsa_decode_attn_batch (another summation order).
1654// Fragment layout (16x16x16, wave32, checked on gfx1201): A lane l holds A[l % 16][(l / 16) * 8 + i], B lane l holds
1655// B[(l / 16) * 8 + i][l % 16], C/D lane l holds D[(l / 16) * 8 + i][l % 16], i = 0..7.
1656// gfx11 (RDNA3 / RDNA3.5: gfx110x, gfx115x) has the same instruction with another layout: A lane l holds all 16 k of
1657// 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
1658// 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.
1659#if defined(__gfx1200__) || defined(__gfx1201__)
1660#define STRATA_PA_WMMA 1
1661#define STRATA_PA_GFX11 0
1662#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || \
1663    defined(__gfx1151__)
1664#define STRATA_PA_WMMA 1
1665#define STRATA_PA_GFX11 1
1666#else
1667#define STRATA_PA_WMMA 0
1668#define STRATA_PA_GFX11 0
1669#endif
1670#if STRATA_PA_GFX11
1671constexpr int PA_KL = 16;
1672#define PA_KOFF(half) 0
1673#define PA_ROW(i, half) (2 * (i) + (half))
1674#else
1675constexpr int PA_KL = 8;
1676#define PA_KOFF(half) ((half) * 8)
1677#define PA_ROW(i, half) ((half) * 8 + (i))
1678#endif
1679typedef _Float16 wh8 __attribute__((ext_vector_type(PA_KL)));
1680typedef float wf8 __attribute__((ext_vector_type(8)));
1681constexpr int WCH = 32;          // cells per chunk (two 16-cell tiles)
1682constexpr int WVS = 80;          // staged V row stride in bytes (64 codes, 16-byte aligned, banks spread)
1683struct alignas(16) SmemW {
1684    float part[4][16][WCH + 1];  // q.k per dim group
1685    float p[16][WCH + 1];
1686    float vs[4][WCH];            // V scale per (group, cell)
1687    int valid[WCH];              // the cell has a resident pool row
1688    uint8_t v[4][WCH][WVS];      // per wave: the chunk's V codes of its group, one row per cell
1689    float qmax[4];
1690    float alpha[16];
1691    float lsum[16];
1692    float mrow[16];
1693};
1694
1695__device__ __forceinline__ wf8 wmma_f16(wh8 a, wh8 b, wf8 c) {
1696#if STRATA_PA_WMMA && STRATA_PA_GFX11
1697    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c);
1698#elif STRATA_PA_WMMA
1699    return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c);
1700#else
1701    __builtin_trap();
1702    return c;
1703#endif
1704}
1705
1706__device__ __forceinline__ wh8 i8_to_h(const uint32_t* x) {   // PA_KL codes, exact: |code| <= 128
1707    wh8 h;
1708#pragma unroll
1709    for (int i = 0; i < PA_KL; ++i) h[i] = (_Float16) (int) (int8_t) (x[i / 4] >> (8 * (i % 4)));
1710    return h;
1711}
1712
1713// SPLIT = true (default): q and p carried as FP16 hi + lo pairs (two WMMAs each: FP32-level). S23 (opt-in
1714// STRATA_PA_FAST=1): SPLIT = false, one FP16 image each - half the matrix work, rounding-level (FP16 attention as the
1715// usual flash-attention kernels), quality-gated
1716template <bool SPLIT>
1717__global__ void __launch_bounds__(THREADS) prompt_attn_wmma_kernel(const float* __restrict__ q, QsaAttnPools p,
1718                                                                   const int32_t* __restrict__ ids,
1719                                                                   const int32_t* __restrict__ steps, int n_kv_heads,
1720                                                                   int page_size, float scale_log2,
1721                                                                   float* __restrict__ attn, int cap) {
1722#if STRATA_PA_WMMA
1723    __shared__ SmemW S;
1724    const int qi = blockIdx.x, kvh = blockIdx.y;
1725    const int n_head = n_kv_heads * G;
1726    q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1727    attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
1728    ids += (size_t) qi * cap;
1729    const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
1730    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1731    const int col = lane & 15, half = lane >> 4;   // fragment column / k half
1732    const int dim0 = warp * 64;
1733
1734    float qm = 0.0f;
1735    for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
1736#pragma unroll
1737    for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
1738    if (lane == 0) S.qmax[warp] = qm;
1739    if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
1740    __syncthreads();
1741    qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
1742    int qe = 0;
1743    if (qm > 0.0f) frexpf(qm, &qe);
1744    const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
1745    // q A fragments of this wave's 64 dims: row = col (heads 12..15 zero), k = dim0 + kk*16 + PA_KOFF(half) + i
1746    wh8 qh[4], ql[4];
1747#pragma unroll
1748    for (int kk = 0; kk < 4; ++kk) {
1749        float x[PA_KL];
1750        if (col < G) {
1751            const float4* src = reinterpret_cast<const float4*>(q + (size_t) col * HD + dim0 + kk * 16 + PA_KOFF(half));
1752#pragma unroll
1753            for (int j = 0; j < PA_KL / 4; ++j) {
1754                const float4 a = src[j];
1755                x[4 * j] = a.x; x[4 * j + 1] = a.y; x[4 * j + 2] = a.z; x[4 * j + 3] = a.w;
1756            }
1757        } else {
1758#pragma unroll
1759            for (int i = 0; i < PA_KL; ++i) x[i] = 0.0f;
1760        }
1761#pragma unroll
1762        for (int i = 0; i < PA_KL; ++i) {
1763            const float v = x[i] * qup;
1764            const _Float16 hi = (_Float16) v;
1765            qh[kk][i] = hi;
1766            ql[kk][i] = (_Float16) (v - (float) hi);
1767        }
1768    }
1769
1770    wf8 acc[4];
1771#pragma unroll
1772    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};
1773
1774    const int n_chunks = (n + WCH - 1) / WCH;
1775    for (int ci = 0; ci < n_chunks; ++ci) {
1776        const int c0 = ci * WCH;
1777        // this lane's cell of the chunk (lane = cell index): its pool row, or -1 (past the selection, or a block the
1778        // KV streaming left non-resident: masked as in the decode kernel)
1779        long long myrow = -1;
1780        if (c0 + lane < n) {
1781            const int cell = __ldg(ids + c0 + lane);
1782            const long long page = (long long) __ldg(p.page_table + cell / page_size);
1783            if (page >= 0) myrow = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1784        }
1785        // stage this wave's V slice of the chunk (64 bytes of each row) and the V scale; the K fragments come straight
1786        // from global memory (8 consecutive codes per lane)
1787        {
1788            uint4 v0 = make_uint4(0, 0, 0, 0), v1 = v0, v2 = v0, v3 = v0;
1789            float vsc = 0.0f;
1790            if (myrow >= 0) {
1791                const uint4* src = reinterpret_cast<const uint4*>(p.v_q + myrow * HD + dim0);
1792                v0 = __ldg(src); v1 = __ldg(src + 1); v2 = __ldg(src + 2); v3 = __ldg(src + 3);
1793                vsc = __half2float(__ushort_as_half(__ldg(p.v_scale + myrow * (HD / KV_Q8_GROUP) + warp)));
1794            }
1795            uint4* dst = reinterpret_cast<uint4*>(&S.v[warp][lane][0]);
1796            dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3;
1797            S.vs[warp][lane] = vsc;
1798            if (warp == 0) S.valid[lane] = myrow >= 0;
1799        }
1800        // q.k over this wave's 64 dims for two 16-cell tiles, times the cell's K scale for this group
1801#pragma unroll
1802        for (int nt = 0; nt < 2; ++nt) {
1803            const long long rr = __shfl(myrow, nt * 16 + col);
1804            wf8 s = wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
1805            float ksc = 0.0f;
1806            if (rr >= 0) ksc = __half2float(__ushort_as_half(__ldg(p.k_scale + rr * (HD / KV_Q8_GROUP) + warp)));
1807#pragma unroll
1808            for (int kk = 0; kk < 4; ++kk) {
1809                uint32_t kx[PA_KL / 4] = {};
1810                if (rr >= 0) {
1811                    const uint32_t* src = reinterpret_cast<const uint32_t*>(p.k_q + rr * HD + dim0 + kk * 16 + PA_KOFF(half));
1812#if STRATA_PA_GFX11
1813                    const uint4 v = __ldg(reinterpret_cast<const uint4*>(src));
1814                    kx[0] = v.x; kx[1] = v.y; kx[2] = v.z; kx[3] = v.w;
1815#else
1816                    const uint2 v = __ldg(reinterpret_cast<const uint2*>(src));
1817                    kx[0] = v.x; kx[1] = v.y;
1818#endif
1819                }
1820                const wh8 b = i8_to_h(kx);
1821                s = wmma_f16(qh[kk], b, s);
1822                if constexpr (SPLIT) s = wmma_f16(ql[kk], b, s);
1823            }
1824#pragma unroll
1825            for (int i = 0; i < 8; ++i) S.part[warp][PA_ROW(i, half)][nt * 16 + col] = s[i] * ksc;
1826        }
1827        __syncthreads();
1828        // online softmax over the four groups' sum (fixed order): row t/8, 4 cells per thread
1829        {
1830            const int r = t >> 3, sub = t & 7;
1831            float x[4], mx = -INFINITY;
1832#pragma unroll
1833            for (int j = 0; j < 4; ++j) {
1834                const int c = sub * 4 + j;
1835                // past the selection, or a masked cell (non-resident page, as in the decode kernel): no weight
1836                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
1837                                  : -INFINITY;
1838                mx = fmaxf(mx, x[j]);
1839            }
1840#pragma unroll
1841            for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
1842            const float m_old = S.mrow[r];
1843            const float m_new = fmaxf(m_old, mx);
1844            float sum = 0.0f;
1845#pragma unroll
1846            for (int j = 0; j < 4; ++j) {
1847                const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
1848                S.p[r][sub * 4 + j] = e;
1849                sum += e;
1850            }
1851#pragma unroll
1852            for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
1853            if (sub == 0) {
1854                const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
1855                S.alpha[r] = a;
1856                S.lsum[r] = fmaf(S.lsum[r], a, sum);
1857                S.mrow[r] = m_new;
1858            }
1859        }
1860        __syncthreads();
1861        // p.v over this wave's 64 dims: 4 tiles of 16 dims, 2 k-steps of 16 cells
1862        {
1863            float vmax = S.vs[warp][lane];
1864#pragma unroll
1865            for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
1866            const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
1867            wf8 tmp[4];
1868#pragma unroll
1869            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};
1870#pragma unroll
1871            for (int ks = 0; ks < 2; ++ks) {
1872                const int cb = ks * 16 + PA_KOFF(half);   // this lane's PA_KL cells
1873                wh8 ah, al;
1874#pragma unroll
1875                for (int i = 0; i < PA_KL; ++i) {
1876                    const float pv = S.p[col][cb + i] * (S.vs[warp][cb + i] * vup);
1877                    const _Float16 hi = (_Float16) pv;
1878                    ah[i] = hi;
1879                    al[i] = (_Float16) (pv - (float) hi);
1880                }
1881#pragma unroll
1882                for (int j = 0; j < 4; ++j) {
1883                    const int d = j * 16 + col;
1884                    wh8 b;
1885#pragma unroll
1886                    for (int i = 0; i < PA_KL; ++i) b[i] = (_Float16) (int) (int8_t) S.v[warp][cb + i][d];
1887                    tmp[j] = wmma_f16(ah, b, tmp[j]);
1888                    if constexpr (SPLIT) tmp[j] = wmma_f16(al, b, tmp[j]);
1889                }
1890            }
1891            float a[8];
1892#pragma unroll
1893            for (int i = 0; i < 8; ++i) a[i] = S.alpha[PA_ROW(i, half)];
1894#pragma unroll
1895            for (int j = 0; j < 4; ++j)
1896#pragma unroll
1897                for (int i = 0; i < 8; ++i) acc[j][i] = fmaf(acc[j][i], a[i], tmp[j][i] * vdown);
1898        }
1899        // no barrier here: `v`/`vs` are this wave's own, and `p`/`alpha`/`valid` are rewritten only after the next
1900        // chunk's first barrier (which every wave reaches after its p.v)
1901    }
1902    float inv[8];
1903#pragma unroll
1904    for (int i = 0; i < 8; ++i) {
1905        const float l = S.lsum[PA_ROW(i, half)];
1906        inv[i] = l > 0.0f ? 1.0f / l : 0.0f;
1907    }
1908#pragma unroll
1909    for (int j = 0; j < 4; ++j)
1910#pragma unroll
1911        for (int i = 0; i < 8; ++i) {
1912            const int row = PA_ROW(i, half);
1913            if (row < G) attn[(size_t) row * HD + dim0 + j * 16 + col] = acc[j][i] * inv[i];
1914        }
1915#else
1916    __builtin_trap();
1917#endif
1918}
1919
1920// gfx12 (RDNA4) and gfx11 (RDNA3 / RDNA3.5), only on request: the output differs from the default kernel's in its
1921// last bits
1922bool hip_wmma_usable() {
1923    static const bool want = [] {
1924        const char* e = std::getenv("STRATA_HIP_WMMA");
1925        return e != nullptr && e[0] == '1';
1926    }();
1927    if (!want) return false;
1928    static int arch[64] = {};   // 0 unknown, 1 gfx11 / gfx12, 2 other
1929    int dev = 0;
1930    if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= 64) { (void) hipGetLastError(); return false; }
1931    if (arch[dev] == 0) {
1932        hipDeviceProp_t prop{};
1933        if (hipGetDeviceProperties(&prop, dev) != hipSuccess) { (void) hipGetLastError(); return false; }
1934        arch[dev] = std::strncmp(prop.gcnArchName, "gfx12", 5) == 0 || strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName)
1935                        ? 1 : 2;
1936        static bool told = false;
1937        if (!told) {
1938            told = true;
1939            std::fprintf(stderr, "strata: STRATA_HIP_WMMA: the prompt attention on matrix cores %s (%s)\n",
1940                         arch[dev] == 1 ? "on" : "unavailable", prop.gcnArchName);
1941        }
1942    }
1943    return arch[dev] == 1;
1944}
1945
1946bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
1947                 const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
1948    const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
1949    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
1950        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
1951        static const bool fast = [] { const char* e = std::getenv("STRATA_PA_FAST"); return e != nullptr && e[0] == '1'; }();
1952        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; }();
1953        if (fast && n_q >= min_t)
1954            prompt_attn_wmma_kernel<false><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(
1955                q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1956                (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1957        else
1958            prompt_attn_wmma_kernel<true><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, 0, st>>>(
1959                q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
1960                (int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
1961    }
1962    const cudaError_t e = cudaGetLastError();
1963    if (e != cudaSuccess) {
1964        std::fprintf(stderr, "qsa_prompt_attn_batch (wmma): %s\n", cudaGetErrorString(e));
1965        std::exit(1);
1966    }
1967    return true;
1968}
1969#endif
1970
1971}  // namespace
1972
1973bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
1974                           int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
1975    if (n_q <= 0) return true;
1976    bool volta = false, turing = false;   // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
1977    {   // sm_75 or newer: the MMA above compiles for both.  sm_80+ runs the cp.async kernel (launch_i8); Turing has
1978        // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order).  An older card
1979        // keeps the old kernel.
1980        // #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75)
1981#if defined(STRATA_HIP_GFX906)
1982        return false;   // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs
1983#endif
1984        static int cc[64] = {};
1985        int dev = 0;
1986        /*
1987        DPCT1026: The call to cudaGetLastError was removed because this
1988        functionality is redundant in SYCL.
1989        */
1990        if (DPCT_CHECK_ERROR(dev = dpct::get_current_device_id()) != 0 ||
1991            dev < 0 || dev >= 64) {
1992            ; return false;
1993        }
1994        if (cc[dev] == 0) {
1995            int major = 0, minor = 0;
1996            if (DPCT_CHECK_ERROR(
1997                    major = dpct::get_device(dev).get_major_version()) != 0 ||
1998                DPCT_CHECK_ERROR(
1999                    minor = dpct::get_device(dev).get_minor_version()) != 0) {
2000                /*
2001                DPCT1026: The call to cudaGetLastError was removed because
2002                this functionality is redundant in SYCL.
2003                */
2004                return false;
2005            }
2006            // STRATA_QSA_WARP=1|attn (an A/B arm): the pre-sm_80 kernels on any card, as RTX 20 runs them
2007            const char* w = std::getenv("STRATA_QSA_WARP");
2008            cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75
2009                      : 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
2010        }
2011        (void) cc[dev];
2012        // SYCL: the mma.sync kernel below is not ported (upstream's Turing/sm_80 split - `turing` - does not
2013        // apply); its XMX port takes the same arguments
2014        if (qsa_prompt_attn_esimd(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true;
2015        if (qsa_prompt_attn_xmx(q, pools, ids, steps, cap, s, attn, n_q, stream)) return true;
2016        return false;   // the caller takes the older kernel
2017    }
2018#if defined(__HIPCC__)
2019    // the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
2020    // matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
2021    (void) turing; (void) volta;
2022    if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
2023        pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
2024        cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
2025        return launch_wmma(q, pools, ids, steps, cap, s, attn, n_q, (cudaStream_t) stream);
2026    return false;
2027#endif
2028    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps || !pools.page_table)
2029        return false;
2030    dpct::queue_ptr st = strata::q_of(stream);
2031    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)
2032        static const bool q4_off = [] {
2033            const char* v = std::getenv("STRATA_PROMPT_ATTN_Q4");
2034            return v != nullptr && v[0] == '0';
2035        }();
2036        // sm_80+ only: on Turing mode 4 would run as pairs of m16n8k8 MMAs, which no parity run has checked yet
2037        if (q4_off || turing || pools.v_q4 == nullptr) return false;
2038        return launch<4>(q, pools, ids, steps, cap, s, attn, n_q, st);
2039    }
2040    if (pools.k_q != nullptr && pools.v_q4 != nullptr) {   // hybrid K8V4: int8 K + dequantized-q4 V
2041        if (!pools.k_scale) return false;
2042        if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
2043        return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
2044    }
2045    if (pools.k_q != nullptr) {
2046        if (!pools.v_q || !pools.k_scale || !pools.v_scale) return false;
2047        // STRATA_PROMPT_ATTN_V1=1 (debug): the first version, same accuracy, another summation order - the control
2048        // for how far the model amplifies an FP32-level change.  Turing always takes it: v2's cp.async does not
2049        // exist before sm_80.
2050        static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
2051        if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
2052        if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
2053        return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
2054    }
2055    if (!pools.k_pool || !pools.v_pool) return false;
2056    if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
2057    return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
2058}
2059
2060}  // namespace strata::kernels