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
22.0 KiB445 linesraw
1// SYCL port (ARC-W): the QSA prompt attention on the int8 DPAS (ESIMD, Battlemage).
2//
3// The FP32 prompt kernel (qsa_decode_attn_batch, 64-cell chunks + a merge kernel) is compute bound at ~60% of the
4// card's FP32 peak and takes 22-24% of a prompt.  This kernel runs both products on the s8 8x16x32 DPAS.
5//
6//  * One work-group of NTH = 4 hardware threads per (query, KV head).  Thread t owns the output dims [64 t, 64 t + 64),
7//    which is also V's scale group t, and computes Q.K for 32 of every 128 selected cells (a "super-step").
8//  * Q.K: A = 8 cells x 32 dims of K's int8 codes (a row of K is contiguous, so A is eight 32-byte slices), B = the
9//    32 dims x 16 heads of Q (12 real heads, 4 zero lanes), D = 8 cells x 16 heads.  Q is quantized per head to
10//    hi + lo int8 (x ~ sq (hi + lo / 254), error ~ 1.5e-5 of the head's largest value) so the product keeps ~15 bits;
11//    K's per-64-dim scale is applied per cell row to each 64-dim group's int32 sum.  The scores of the thread's 32
12//    cells go to local memory; one barrier later every thread has all 128.
13//  * Softmax: every thread reads the 128 score rows (lane = head), takes the running max, rescales its output
14//    accumulators and forms p = exp2(s - m).
15//  * P.V: A = P (8 heads x 32 cells, int8 hi + lo of p * v_scale[cell][group t], scaled to 127 by the super-step's
16//    largest v scale), B = the thread's 64 dims of 32 V rows packed four cells to a dword (a 4x4 byte transpose in
17//    registers), D = 8 heads x 16 dims into float accumulators held in registers (12 heads in two 8-row tiles x 4
18//    dim tiles).
19//  * Not bitwise the FP32 kernel: Q and P are 16-bit (hi + lo int8) numbers, the sums are exact int32, the scales and
20//    the softmax are FP32.  qsa_prompt_attn_parity bounds the difference against FP64.
21// int8 KV only (the default); anything else keeps the caller's fallback.
22#include "strata/kernels/qsa_prompt_attn_esimd.hpp"
23#include "strata/kprof.hpp"
24#include "strata/core/geometry.hpp"
25#include "strata/sycl_queue.hpp"
26#include <sycl/sycl.hpp>
27#include <sycl/ext/intel/esimd.hpp>
28#include <sycl/ext/intel/experimental/esimd/memory.hpp>
29#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
30#include <dpct/dpct.hpp>
31#include <cmath>
32#include <cstdint>
33#include <cstdio>
34#include <cstdlib>
35#include <type_traits>
36
37#ifndef STRATA_I8_NO_ESIMD
38namespace strata::kernels {
39namespace {
40using namespace sycl::ext::intel::esimd;
41namespace xmx = sycl::ext::intel::esimd::xmx;
42
43constexpr int HD = 256, G = strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, NTH = 4, SS = 128;
44static_assert(G >= 1 && G <= 16, "qsa_prompt_attn_esimd: query heads per KV head must be 1..16 (16 score columns, two 8-row tiles)");
45static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv,
46              "qsa_prompt_attn_esimd is compiled for core/geometry.hpp");
47constexpr uint32_t QT_OFF = 0;            // Q^T B tiles: [8 K steps][LV levels][128 dwords]
48
49SYCL_ESIMD_FUNCTION inline simd<int, 128> dpas8(simd<int, 128> acc, simd<int, 128> b, simd<int, 64> a) {
50    return xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>(acc, b, a);
51}
52
53// row index of 32 selected cells (selection positions c_first ...), as the page table maps them; positions past n take `fallback`
54SYCL_ESIMD_FUNCTION inline simd<int, 32> cell_rows(const int32_t* idsb, const int32_t* pt, int c_first, int n, int kvh, int nkv,
55                                                   int pshift, int pmask, int fallback) {
56    simd<uint32_t, 32> lane(0, 1);
57    simd<int, 32> pos = simd<int, 32>(c_first) + simd<int, 32>(lane);
58    simd_mask<32> ok = pos < n;
59    simd<int, 32> cell = gather<int, 32>(idsb, lane * 4u, ok, simd<int, 32>(0));
60    simd<uint32_t, 32> poff = simd<uint32_t, 32>(cell >> pshift) * 4u;
61    simd<int, 32> page = gather<int, 32>(pt, poff, ok, simd<int, 32>(0));
62    simd<int, 32> rows = ((page * nkv + kvh) << pshift) + (cell & pmask);
63    rows.merge(simd<int, 32>(fallback), !ok);
64    return rows;
65}
66
67template <int LV>
68SYCL_ESIMD_FUNCTION constexpr float level_coef(int l) { return LV == 2 ? (l == 0 ? 254.0f : 1.0f) : (l == 0 ? 64516.0f : (l == 1 ? 254.0f : 1.0f)); }
69
70// x in [-127, 127] as LV int8 levels: x ~ o[0] + o[1] / 254 + o[2] / 254^2
71template <int N, int LV>
72SYCL_ESIMD_FUNCTION inline void split_lv(simd<float, N> x, simd<int8_t, N>* o) {
73    simd<float, N> r = x;
74#pragma unroll
75    for (int l = 0; l < LV; ++l) {
76        simd<float, N> f = rnde<float>(r);   // |r| <= 127 at every level, so the rounded value fits an int8
77        o[l] = f;
78        r = (r - f) * 254.0f;
79    }
80}
81
82constexpr unsigned SURF_H = (1u << 24) - 1u;   // 2D block loads: the surface height - 1 (no clamping)
83
84// four consecutive pool rows starting at element i of a row-index vector
85template <int N>
86SYCL_ESIMD_FUNCTION inline bool contig4(const simd<int, N>& r, int i) {
87    const int r0 = r[i];
88    return r[i + 1] == r0 + 1 && r[i + 2] == r0 + 2 && r[i + 3] == r0 + 3;
89}
90
91struct Args {
92    const float* q;
93    const int8_t* kq;
94    const uint16_t* ks;
95    const int8_t* vq;
96    const uint16_t* vs;
97    const int32_t* pt;
98    const int32_t* ids;
99    const int32_t* steps;
100    float* attn;
101    int nkv, cap, pshift, pmask;
102    float scale_log2;
103    int dbg;
104};
105
106// ---- Q.K for one tile of 8 cells: S[cell][head] -> local memory (rows = cells, lanes = heads)
107//      FAST: the 8 cells are two runs of four consecutive pool rows (the indexer selects blocks of four cells): 2D block loads
108template <bool FAST, int QL>
109SYCL_ESIMD_FUNCTION inline void qk_tile(const Args& a, const simd<int, 8>& rows, int pos0, int n, const simd<float, 16>& cscale,
110                                        uint32_t s_dst) {
111    simd<float, 128> sacc = 0.0f;
112    simd<int, 512> kall;
113    simd<uint8_t, 256> dA[4], dB[4];
114    if constexpr (FAST) {
115        const int rA = rows[0], rB = rows[4];
116#pragma unroll
117        for (int pp = 0; pp < 4; ++pp) {
118            dA[pp] = sycl::ext::intel::experimental::esimd::lsc_load_2d<uint8_t, 32, 4, 2, false, false>(
119                reinterpret_cast<const uint8_t*>(a.kq), 255u, SURF_H, 255u, 64 * pp, rA);
120            dB[pp] = sycl::ext::intel::experimental::esimd::lsc_load_2d<uint8_t, 32, 4, 2, false, false>(
121                reinterpret_cast<const uint8_t*>(a.kq), 255u, SURF_H, 255u, 64 * pp, rB);
122        }
123    } else {
124#pragma unroll
125        for (int j = 0; j < 8; ++j) {
126            const size_t r = (size_t) rows[j];
127            kall.template select<64, 1>(64 * j) = block_load<int, 64>(reinterpret_cast<const int*>(a.kq) + r * 64);
128        }
129    }
130    // K scales: 8 rows x 4 halves as 16 dwords
131    simd<uint32_t, 16> so;
132#pragma unroll
133    for (int j = 0; j < 8; ++j) { so[2 * j] = (uint32_t) rows[j] * 8u; so[2 * j + 1] = (uint32_t) rows[j] * 8u + 4u; }
134    simd<uint32_t, 16> sd = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(a.ks), so);
135    simd<sycl::half, 32> ksh = sd.template bit_cast_view<sycl::half>();
136    simd<float, 32> ksf = ksh;
137#pragma unroll
138    for (int g = 0; g < 4; ++g) {
139        simd<int, 128> acc[QL];
140#pragma unroll
141        for (int l = 0; l < QL; ++l) acc[l] = 0;
142#pragma unroll
143        for (int ss = 0; ss < 2; ++ss) {
144            const int s = 2 * g + ss;
145            simd<int, 64> A;
146            if constexpr (FAST) {
147                simd<int, 64> da = dA[s >> 1].template bit_cast_view<int>(), db = dB[s >> 1].template bit_cast_view<int>();
148                A.template select<32, 1>(0) = da.template select<32, 1>((s & 1) * 32);
149                A.template select<32, 1>(32) = db.template select<32, 1>((s & 1) * 32);
150            } else {
151#pragma unroll
152                for (int j = 0; j < 8; ++j) A.template select<8, 1>(8 * j) = kall.template select<8, 1>(64 * j + 8 * s);
153            }
154#pragma unroll
155            for (int l = 0; l < QL; ++l) {
156                simd<int, 128> bq = slm_block_load<int, 128>(QT_OFF + (uint32_t) (s * QL + l) * 512u);
157                acc[l] = dpas8(acc[l], bq, A);
158            }
159        }
160        simd<float, 128> tf;
161        if constexpr (QL == 2) {
162            simd<int, 128> ti = acc[0] * 254 + acc[1];
163            tf = ti;
164        } else {
165            tf = 0.0f;
166#pragma unroll
167            for (int l = 0; l < QL; ++l) {
168                simd<float, 128> fl = acc[l];
169                tf += fl * level_coef<QL>(l);
170            }
171        }
172#pragma unroll
173        for (int j = 0; j < 8; ++j) {
174            const float ksc = ksf[4 * j + g];
175            sacc.template select<16, 1>(16 * j) += tf.template select<16, 1>(16 * j) * ksc;
176        }
177    }
178#pragma unroll
179    for (int j = 0; j < 8; ++j) {
180        simd<float, 16> row = sacc.template select<16, 1>(16 * j) * cscale;
181        const float madd = (pos0 + j >= n) ? -INFINITY : 0.0f;
182        row += madd;
183        sacc.template select<16, 1>(16 * j) = row;
184    }
185    slm_block_store<float, 128>(s_dst, sacc);
186}
187
188// ---- P.V for one step of 32 cells: O += P' V (this thread's 64 dims); lsum += sum p
189template <bool FAST, int PL>
190SYCL_ESIMD_FUNCTION inline void pv_step(const Args& a, simd<float, 1024>& O, simd<float, 16>& lsum, const simd<float, 16>& m_new,
191                                        uint32_t s_row0, const simd<float, 32>& vsf, const simd<int, 32>& rowsV, int t) {
192    constexpr float COEF0P = PL == 2 ? 254.0f : 64516.0f;
193    simd<int8_t, 256> ap[PL][2];   // [level][heads 0-7, 8-15]: 8 rows x 32 cells
194    simd<float, 16> prow[32];
195    simd<float, 16> pm = 0.0f;     // per head: the largest p * v_scale of these 32 cells
196#pragma unroll
197    for (int c = 0; c < 32; ++c) {
198        simd<float, 16> srow = slm_block_load<float, 16>(s_row0 + (uint32_t) c * 64u);
199        simd<float, 16> p = exp2(srow - m_new);
200        lsum += p;
201        const float vsc = vsf[c];
202        prow[c] = p * vsc;
203        pm = max(pm, prow[c]);
204    }
205    simd<float, 16> pinv = 127.0f / pm;
206    pinv.merge(simd<float, 16>(0.0f), pm <= 0.0f);
207    const simd<float, 16> osv = pm * (1.0f / (127.0f * COEF0P));
208#pragma unroll
209    for (int c = 0; c < 32; ++c) {
210        simd<float, 16> r = prow[c] * pinv;
211        simd<int8_t, 16> pb[PL];
212        split_lv<16, PL>(r, pb);
213#pragma unroll
214        for (int l = 0; l < PL; ++l) {
215            ap[l][0].template select<8, 32>(c) = pb[l].template select<8, 1>(0);
216            ap[l][1].template select<8, 32>(c) = pb[l].template select<8, 1>(8);
217        }
218    }
219    // V: 32 rows x this thread's 64 dims, four cells to a dword
220    simd<int, 512> vt;   // [k4][64 dims]
221#pragma unroll
222    for (int k4 = 0; k4 < 8; ++k4) {
223        simd<int, 64> w;
224        if constexpr (FAST) {
225            simd<uint8_t, 256> v2 = sycl::ext::intel::experimental::esimd::lsc_load_2d<uint8_t, 16, 4, 4, false, true>(
226                reinterpret_cast<const uint8_t*>(a.vq), 255u, SURF_H, 255u, 64 * t, (int) rowsV[4 * k4]);
227            w = v2.template bit_cast_view<int>();
228        } else {
229            auto wb = w.template bit_cast_view<uint8_t>();
230#pragma unroll
231            for (int j = 0; j < 4; ++j) {
232                const size_t r = (size_t) rowsV[4 * k4 + j];
233                wb.template select<64, 4>(j) = block_load<uint8_t, 64>(reinterpret_cast<const uint8_t*>(a.vq) + r * HD + 64 * t);
234            }
235        }
236        vt.template select<64, 1>(64 * k4) = w;
237    }
238    simd<int, 64> aq[PL][2];
239#pragma unroll
240    for (int l = 0; l < PL; ++l) {
241        aq[l][0] = ap[l][0].template bit_cast_view<int>();
242        aq[l][1] = ap[l][1].template bit_cast_view<int>();
243    }
244#pragma unroll
245    for (int nt = 0; nt < 4; ++nt) {
246        simd<int, 128> B;
247#pragma unroll
248        for (int k4 = 0; k4 < 8; ++k4) B.template select<16, 1>(16 * k4) = vt.template select<16, 1>(64 * k4 + 16 * nt);
249        simd<int, 128> z = 0;
250        simd<float, 128> f0 = 0.0f, f1 = 0.0f;
251#pragma unroll
252        for (int l = 0; l < PL; ++l) {
253            simd<int, 128> d0 = dpas8(z, B, aq[l][0]), d1 = dpas8(z, B, aq[l][1]);
254            simd<float, 128> e0 = d0, e1 = d1;
255            f0 += e0 * level_coef<PL>(l);
256            f1 += e1 * level_coef<PL>(l);
257        }
258#pragma unroll
259        for (int i = 0; i < 8; ++i) {
260            const float s0 = osv[i], s1 = osv[8 + i];
261            O.template select<16, 1>((0 * 4 + nt) * 128 + 16 * i) += f0.template select<16, 1>(16 * i) * s0;
262            O.template select<16, 1>((1 * 4 + nt) * 128 + 16 * i) += f1.template select<16, 1>(16 * i) * s1;
263        }
264    }
265}
266
267template <int QL, int PL> struct TagEsimdAttn;
268
269template <int QL, int PL>
270void launch(sycl::queue& q, const Args a, int64_t n_q) {
271    constexpr uint32_t S_OFF = 8u * QL * 512u;        // the scores of one super-step: [128 cells][16 heads] floats
272    constexpr uint32_t SLM_BYTES = S_OFF + 8192u;
273    constexpr float COEF0Q = QL == 2 ? 254.0f : 64516.0f;
274    auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>};
275    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
276        h.parallel_for<TagEsimdAttn<QL, PL>>(sycl::nd_range<3>(sycl::range<3>((size_t) n_q, (size_t) a.nkv, (size_t) NTH), sycl::range<3>(1, 1, NTH)), props,
277                                     [=](sycl::nd_item<3> ndi) SYCL_ESIMD_KERNEL {
278            slm_init<SLM_BYTES>();
279            const int qi = (int) ndi.get_group(0), kvh = (int) ndi.get_group(1), t = (int) ndi.get_local_id(2);
280            const int n_head = a.nkv * G;
281            const int n = a.steps[(size_t) qi * kStepCount + kStepWidth];
282            const int32_t* idsb = a.ids + (size_t) qi * a.cap;
283            float* outp = a.attn + ((size_t) qi * n_head + (size_t) kvh * G) * HD + 64 * t;
284            const float* qp = a.q + ((size_t) qi * n_head + (size_t) kvh * G) * HD;
285
286            // ---- Q: per-head int8 levels, the B tiles of this thread's two K steps (2t, 2t + 1)
287            const simd<uint32_t, 16> lane16(0, 1);
288            simd<float, 16> sqv = 0.0f;   // lane h: the head's scale (largest |q| / 127)
289            {
290                simd<int, 128> bq[QL][2];   // [level][step 2t, 2t + 1]
291#pragma unroll
292                for (int l = 0; l < QL; ++l) { bq[l][0] = 0; bq[l][1] = 0; }
293#pragma unroll
294                for (int hh = 0; hh < G; ++hh) {
295                    const float* row = qp + (size_t) hh * HD;
296                    simd<float, 64> r0 = block_load<float, 64>(row), r1 = block_load<float, 64>(row + 64);
297                    simd<float, 64> r2 = block_load<float, 64>(row + 128), r3 = block_load<float, 64>(row + 192);
298                    simd<float, 64> mx = max(max(abs(r0), abs(r1)), max(abs(r2), abs(r3)));
299                    const float amax = hmax<float>(mx);
300                    const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
301                    sqv.merge(simd<float, 16>(amax * (1.0f / 127.0f)), lane16 == (uint32_t) hh);
302                    simd<float, 64> mine = block_load<float, 64>(row + 64 * t);
303                    simd<int8_t, 64> qb[QL];
304                    split_lv<64, QL>(mine * inv, qb);
305#pragma unroll
306                    for (int l = 0; l < QL; ++l) {
307                        simd<int, 16> qd = qb[l].template bit_cast_view<int>();
308                        bq[l][0].template select<8, 16>(hh) = qd.template select<8, 1>(0);
309                        bq[l][1].template select<8, 16>(hh) = qd.template select<8, 1>(8);
310                    }
311                }
312                const uint32_t s0 = QT_OFF + (uint32_t) (2 * t) * (uint32_t) QL * 512u;
313#pragma unroll
314                for (int l = 0; l < QL; ++l) {
315                    slm_block_store<int, 128>(s0 + (uint32_t) l * 512u, bq[l][0]);
316                    slm_block_store<int, 128>(s0 + (uint32_t) (QL + l) * 512u, bq[l][1]);
317                }
318            }
319            barrier();
320            // S[cell][head] = sum_g ks[cell][g] * (sum of the levels) * sq[head] * scale_log2
321            const simd<float, 16> cscale = sqv * (a.scale_log2 / COEF0Q);
322
323            // the selection's first cell stands in for positions past n (finite scales, weight 0)
324            int fallback = 0;
325            if (n > 0) {
326                const int c = idsb[0];
327                fallback = ((a.pt[c >> a.pshift] * a.nkv + kvh) << a.pshift) + (c & a.pmask);
328            }
329
330            simd<float, 1024> O = 0.0f;   // [rt][nt] tiles of (8 heads x 16 dims)
331            simd<float, 16> m = -INFINITY, l = 0.0f;
332
333            for (int c0 = 0; c0 < n; c0 += SS) {
334                // ---- Q.K for this thread's 32 cells
335                simd<int, 32> rowsK = cell_rows(idsb + c0 + 32 * t, a.pt, c0 + 32 * t, n, kvh, a.nkv, a.pshift, a.pmask, fallback);
336#pragma unroll
337                for (int tl = 0; tl < 4; ++tl) {
338                    simd<int, 8> r8 = rowsK.template select<8, 1>(8 * tl);
339                    const bool fast = !(a.dbg & 16) && contig4(rowsK, 8 * tl) && contig4(rowsK, 8 * tl + 4);
340                    const uint32_t dst = S_OFF + (uint32_t) (32 * t + 8 * tl) * 64u;
341                    if (a.dbg & 2) continue;
342                    if (fast) qk_tile<true, QL>(a, r8, c0 + 32 * t + 8 * tl, n, cscale, dst);
343                    else qk_tile<false, QL>(a, r8, c0 + 32 * t + 8 * tl, n, cscale, dst);
344                }
345                barrier();
346                // ---- softmax over the 128 cells
347                simd<float, 16> mx = -INFINITY;
348#pragma unroll 1
349                for (int b = 0; b < 16; ++b) {
350                    simd<float, 128> blk = slm_block_load<float, 128>(S_OFF + (uint32_t) b * 512u);
351#pragma unroll
352                    for (int r = 0; r < 8; ++r) mx = max(mx, simd<float, 16>(blk.template select<16, 1>(16 * r)));
353                }
354                const simd<float, 16> m_new = max(m, mx);
355                const simd<float, 16> alpha = exp2(m - m_new);
356#pragma unroll
357                for (int hh = 0; hh < 16; ++hh) {
358                    const float av = alpha[hh];
359#pragma unroll
360                    for (int nt = 0; nt < 4; ++nt) {
361                        auto tile = O.template select<16, 1>(((hh >> 3) * 4 + nt) * 128 + (hh & 7) * 16);
362                        tile *= av;
363                    }
364                }
365                l *= alpha;
366                simd<float, 16> lsum = 0.0f;
367#pragma unroll
368                for (int st = 0; st < 4; ++st) {
369                    // V rows of the step's 32 cells, and their scales for this thread's group
370                    const simd<int, 32> rowsV = cell_rows(idsb + c0 + 32 * st, a.pt, c0 + 32 * st, n, kvh, a.nkv, a.pshift, a.pmask, fallback);
371                    simd<uint32_t, 32> vo = simd<uint32_t, 32>(rowsV) * 8u + (uint32_t) ((t >> 1) * 4);
372                    simd<uint32_t, 32> vd = gather<uint32_t, 32>(reinterpret_cast<const uint32_t*>(a.vs), vo);
373                    simd<uint32_t, 32> shv = (uint32_t) ((t & 1) * 16);
374                    simd<uint16_t, 32> v16 = ((vd >> shv) & 0xffffu);
375                    simd<sycl::half, 32> vh = v16.template bit_cast_view<sycl::half>();
376                    simd<float, 32> vf = vh;
377                    simd<uint32_t, 32> lane(0, 1);
378                    simd_mask<32> ok = (simd<int, 32>(c0 + 32 * st) + simd<int, 32>(lane)) < n;
379                    vf.merge(simd<float, 32>(0.0f), !ok);
380                    bool fastv = !(a.dbg & 16);
381#pragma unroll
382                    for (int g4 = 0; g4 < 8; ++g4) fastv = fastv && contig4(rowsV, 4 * g4);
383                    if (fastv) pv_step<true, PL>(a, O, lsum, m_new, S_OFF + (uint32_t) (32 * st) * 64u, vf, rowsV, t);
384                    else pv_step<false, PL>(a, O, lsum, m_new, S_OFF + (uint32_t) (32 * st) * 64u, vf, rowsV, t);
385                }
386                l += lsum;
387                m = m_new;
388                barrier();
389            }
390            // ---- out = O / l
391#pragma unroll
392            for (int hh = 0; hh < G; ++hh) {
393                const float lv = l[hh];
394                const float il = lv > 0.0f ? 1.0f / lv : 0.0f;
395#pragma unroll
396                for (int nt = 0; nt < 4; ++nt) {
397                    simd<float, 16> v = O.template select<16, 1>(((hh >> 3) * 4 + nt) * 128 + (hh & 7) * 16) * il;
398                    block_store<float, 16>(outp + (size_t) hh * HD + 16 * nt, v);
399                }
400            }
401        });
402    });
403}
404}  // namespace
405
406bool qsa_prompt_attn_esimd(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
407                           const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
408    static const int mode = [] { const char* v = std::getenv("STRATA_PROMPT_ATTN_ESIMD"); return v ? std::atoi(v) : 1; }();   // default on (Battlemage); =0 off
409    if (mode == 0 || n_q <= 0) return false;
410    if (pools.k_q == nullptr || pools.v_q == nullptr || pools.k_scale == nullptr || pools.v_scale == nullptr || pools.k_q4 != nullptr ||
411        pools.v_q4 != nullptr || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !ids || !steps ||
412        !pools.page_table)
413        return false;
414    const int64_t ps = s.page_size;
415    if (ps <= 0 || (ps & (ps - 1)) != 0) return false;
416    dpct::queue_ptr st = strata::q_of(stream);
417    if (strata::intel_gpu_gen(st->get_device()) != strata::IntelGpuGen::Battlemage) return false;
418    static bool told = false;
419    if (!told) { told = true; std::fprintf(stderr, "strata: prompt attention on the int8 DPAS (ESIMD)\n"); }
420    static const int lv = [] { const char* v = std::getenv("STRATA_ESIMD_LV"); return v ? std::atoi(v) : 2; }();
421    int sh = 0;
422    while ((1 << sh) < ps) ++sh;
423    Args a{q, pools.k_q, pools.k_scale, pools.v_q, pools.v_scale, pools.page_table, ids, steps, attn,
424           (int) s.n_head_kv, (int) cap, sh, (int) (ps - 1), 1.4426950408889634f / std::sqrt((float) HD),
425           std::getenv("STRATA_ESIMD_DBG") != nullptr ? std::atoi(std::getenv("STRATA_ESIMD_DBG")) : 0};
426    for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
427        const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
428        Args b = a;
429        b.q = q + q0 * s.n_head * HD;
430        b.ids = ids + q0 * cap;
431        b.steps = steps + q0 * kStepCount;
432        b.attn = attn + q0 * s.n_head * HD;
433        if (lv == 3) launch<3, 3>(*st, b, nb);
434        else if (lv == 32) launch<3, 2>(*st, b, nb);
435        else if (lv == 23) launch<2, 3>(*st, b, nb);
436        else launch<2, 2>(*st, b, nb);
437    }
438    return true;
439}
440}  // namespace strata::kernels
441#else
442namespace strata::kernels {
443bool qsa_prompt_attn_esimd(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*, int64_t, void*) { return false; }
444}
445#endif