okami.mom/strata

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

Niko1221Merge f-sycl-prs e106b4c86 into the batch 16 candidate (SYCL pull requests 4185 and 3153)a8a51b280

main
133.5 KiB2636 linesraw
1#include "b60_layout_state.hpp"
2#include <cstdlib>
3// src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp.
4#define DPCT_PROFILING_ENABLED
5#include <sycl/sycl.hpp>
6#include "strata/kprof.hpp"
7#include "strata/core/geometry.hpp"
8#include <dpct/dpct.hpp>
9#include "strata/sycl_queue.hpp"
10#include "strata/workload_trace.hpp"
11#include "strata/kernels/qsa_decode_attn.hpp"
12#include "strata/kernels/kv_q8.hpp"
13#include "strata/kernels/kv_q4.hpp"
14
15#include <cfloat>
16#include <cstdio>
17#include <cstdlib>
18// BEGIN PRIVATE QSA TWO STAGE INCLUDES
19#include <climits>
20#include <stdexcept>
21// END PRIVATE QSA TWO STAGE INCLUDES
22#include <cmath>
23
24namespace strata::kernels {
25namespace {
26
27constexpr int HD = 256;          // head_dim
28constexpr int G = strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv;   // query heads per KV head (12 for Flash-Next; 1..16, a multiple of 4)
29static_assert(G % 4 == 0 && G <= 16, "qsa_decode_attn: query heads per KV head must be 4, 8, 12 or 16 (float4 probability rows, the 16-lane score reduce)");
30static_assert(HD == strata::core::kCompiledGeometry.head_dim && G == strata::core::kCompiledGeometry.n_head / strata::core::kCompiledGeometry.n_head_kv, "qsa_decode_attn is compiled for core/geometry.hpp");
31constexpr int CHUNK = 64;        // cells per block
32constexpr int THREADS = 256;
33constexpr int WARPS = THREADS / 32;
34
35__dpct_inline__ float warp_sum(float v) {
36#pragma unroll
37    /*
38    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
39    masked sub_group function which may not be supported by all compilers or
40    runtimes. You may need to adjust the code.
41    */
42    for (int o = 16; o > 0; o >>= 1) v +=
43        dpct::experimental::permute_sub_group_by_xor(
44            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
45            o);
46    return v;
47}
48__dpct_inline__ float warp_max(float v) {
49#pragma unroll
50    /*
51    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
52    masked sub_group function which may not be supported by all compilers or
53    runtimes. You may need to adjust the code.
54    */
55    for (int o = 16; o > 0; o >>= 1) v = sycl::fmax(
56        v, dpct::experimental::permute_sub_group_by_xor(
57               0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
58               v, o));
59    return v;
60}
61
62// 8 consecutive values of one cell's key or value row for KV head `kvh`, dimensions [d0, d0+8).
63// Per-format bodies; `load8` below is the KV_MODE dispatcher. value=false is the K side, true the V side.
64__dpct_inline__ void load8_f16(const QsaAttnPools &p, bool value, long long row,
65                               int d0, float *out) {
66    const uint16_t* base = (value ? p.v_pool : p.k_pool) + row * HD + d0;
67    const sycl::uint4 raw = *reinterpret_cast<const sycl::uint4 *>(base);
68    const sycl::half2 *h2 = reinterpret_cast<const sycl::half2 *>(&raw);
69#pragma unroll
70    for (int j = 0; j < 4; ++j) {
71        const sycl::float2 f =
72            h2[j].template convert<float, sycl::rounding_mode::automatic>();
73        out[2 * j] = f.x();
74        out[2 * j + 1] = f.y();
75    }
76}
77__dpct_inline__ void load8_q8(const QsaAttnPools &p, bool value, long long row,
78                              int d0, float *out) {
79    const int8_t* codes = (value ? p.v_q : p.k_q) + row * HD + d0;
80    const uint16_t sbits = (value ? p.v_scale : p.k_scale)[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP];
81    const float sc = sycl::vec<sycl::half, 1>(
82                         sycl::bit_cast<sycl::half, unsigned short>(sbits))
83                         .convert<float, sycl::rounding_mode::automatic>()[0];
84    const sycl::uint2 raw = *reinterpret_cast<const sycl::uint2 *>(codes);
85    const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
86#pragma unroll
87    for (int j = 0; j < 8; ++j) out[j] = (float) c[j] * sc;
88}
89__dpct_inline__ void load8_q4(const QsaAttnPools &p, bool value, long long row,
90                              int d0, float *out) {
91    constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
92    const int b = d0 / QK4_0;
93    const int rem = d0 % QK4_0;
94    const block_q4_0* blk = reinterpret_cast<const block_q4_0*>((value ? p.v_q4 : p.k_q4) + row * bytes_per_head) + b;
95    const float d = sycl::vec<sycl::half, 1>(
96                        sycl::bit_cast<sycl::half, unsigned short>(blk->d))
97                        .convert<float, sycl::rounding_mode::automatic>()[0];
98    const int j = (rem == 0 || rem == 16) ? 0 : 8;
99    const uint8_t* bytes = blk->qs + j;
100    if (rem < 16) {
101#pragma unroll
102        for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] & 0x0F) - 8) * d;
103    } else {
104#pragma unroll
105        for (int k = 0; k < 8; ++k) out[k] = (float) ((int)(bytes[k] >> 4) - 8) * d;
106    }
107}
108template <int KV_MODE>
109__dpct_inline__ void load8(const QsaAttnPools &p, bool value, long long row,
110                           int d0, float *out) {
111    if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out);
112    else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out);
113    else if constexpr (KV_MODE == 3) {
114        // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call
115        // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review)
116        if (value) load8_q4(p, value, row, d0, out);
117        else load8_q8(p, value, row, d0, out);
118    } else load8_q4(p, value, row, d0, out);
119}
120
121template <int KV_MODE, bool LANE_CELL = false, int RS = 0>
122/*
123DPCT1110: The total declared local variable size in device function
124attn_chunk_kernel exceeds 128 bytes and may cause high register pressure.
125Consult with your hardware vendor to find the total register size available and
126adjust the code, or use smaller sub-group size to avoid high register pressure.
127*/
128__dpct_inline__ void
129attn_chunk_kernel(const float *__restrict__ q, QsaAttnPools p,
130                  const int32_t *__restrict__ ids,
131                  const int32_t *__restrict__ step, int n_kv_heads,
132                  int page_size, float scale, float *__restrict__ part_acc,
133                  float *__restrict__ part_m, float *__restrict__ part_l,
134                  int n_chunks, int cap = 0, long long scratch_stride = 0,
135                  QsaAttnPoolsRows prow = {}) {
136    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
137    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
138    if (prow.n > 0) p = prow.p[item_ct1.get_group(0)];   // a batch window's query attends over its own slot's pools
139    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
140    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
141    step += (size_t)item_ct1.get_group(0) * kStepCount;
142    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
143    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
144    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
145    auto &sq =
146        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
147            sycl::ext::oneapi::this_work_item::get_work_group<
148                3>()); // 12 KB: this KV head's query heads
149    auto &sp =
150        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G * CHUNK]>(
151            sycl::ext::oneapi::this_work_item::get_work_group<
152                3>()); // scores, then probabilities
153    auto &srow =
154        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
155            sycl::ext::oneapi::this_work_item::get_work_group<
156                3>()); // pool row of each cell (page, kv head, slot)
157    /*
158    DPCT1098: The '*' expression is used instead of the __ldg call. These
159    two expressions do not provide the exact same functionality. Check the
160    generated code for potential precision and/or performance issues.
161    */
162    // the scores and probabilities: [head][cell], or - RS - [cell][head] so the value phase reads a cell's 12 probabilities as 3 vectors
163    const auto spi = [](int h, int c) { return RS != 0 ? c * G + h : h * CHUNK + c; };
164    const int n_ids = *(step + kStepWidth);
165    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
166    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
167    const int c0 = chunk * CHUNK;
168    const int n_here = sycl::min(CHUNK, n_ids - c0);
169    const int slot = kvh * n_chunks + chunk;
170    if (n_here <= 0) {
171        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
172        return;
173    }
174#pragma unroll
175    for (int i = t; i < G * HD; i += THREADS)
176        sq[i / HD][i % HD] = q[(size_t)(kvh * G) * HD + i];
177    if (t < CHUNK) {
178        long long r = -1;
179        if (t < n_here) {
180            const int cell = ids[c0 + t];
181            const long long page = (long long) p.page_table[cell / page_size];
182            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
183            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
184            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
185        }
186        srow[t] = r;
187    }
188    /*
189    DPCT1065: Consider replacing sycl::nd_item::barrier() with
190    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
191    performance if there is no access to global memory.
192    */
193    item_ct1.barrier();
194    if constexpr (LANE_CELL) {
195        // S25 (STRATA_ATTN_LANECELL=1): thread t scores cell t % 64 for heads 3 (t / 64) .. +2 by itself - the same
196        // 8-dimension partial per former lane (the identical expression), then the former warp_sum's butterfly as
197        // lane 0 ran it (a[l] += a[l + o] for o = 16 .. 1), so every score is bit-identical without 12 shuffle
198        // reductions per cell
199        constexpr int HPT = G * CHUNK / THREADS;   // heads per thread (3)
200        const int c = t % CHUNK, h0 = (t / CHUNK) * HPT;
201        if (c >= n_here || srow[c] < 0) {
202#pragma unroll
203            for (int j = 0; j < HPT; ++j) sp[spi(h0 + j, c)] = -FLT_MAX;
204        } else {
205            float a[HPT][32];
206#pragma unroll
207            for (int l = 0; l < 32; ++l) {
208                float k8[8];
209                load8<KV_MODE>(p, false, srow[c], l * 8, k8);
210#pragma unroll
211                for (int j = 0; j < HPT; ++j) {
212                    const sycl::float4 qa =
213                        *reinterpret_cast<const sycl::float4 *>(
214                            &sq[h0 + j][l * 8]);
215                    const sycl::float4 qb =
216                        *reinterpret_cast<const sycl::float4 *>(
217                            &sq[h0 + j][l * 8 + 4]);
218                    float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
219                              k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
220                              k8[6] * qb.z() + k8[7] * qb.w();
221                    a[j][l] = s;
222                }
223            }
224#pragma unroll
225            for (int j = 0; j < HPT; ++j) {
226#pragma unroll
227                for (int o = 16; o > 0; o >>= 1)
228#pragma unroll
229                    for (int l = 0; l < o; ++l) a[j][l] = a[j][l] + a[j][l + o];
230                sp[spi(h0 + j, c)] = a[j][0] * scale;
231            }
232        }
233    } else
234    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
235    for (int c = warp; c < CHUNK; c += WARPS) {
236        if (c >= n_here || srow[c] < 0) {
237            if (lane < G) sp[spi(lane, c)] = -FLT_MAX;
238            continue;
239        }
240        float k8[8];
241        load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
242        if constexpr (RS == 1) {
243            // 151-b70: the 12 heads' 32-lane butterfly sums as ONE reduce-scatter - 16 shuffles instead of 60.  Each stage pairs the
244            // same lanes in the same order as warp_sum (xor 16, 8, 4, 2, 1) and adds own + partner, so every head's sum is the
245            // same tree and the same bits; the heads are padded to 16, halved at each stage (the lane keeps the half its bit
246            // selects, sends the other), and after the xor-2 stage lane 2h + {0, 1} holds head h's partial pair; xor 1 finishes it.
247            float part[16];
248#pragma unroll
249            for (int h = 0; h < G; ++h) {
250                const sycl::float4 qa =
251                    *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8]);
252                const sycl::float4 qb =
253                    *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8 + 4]);
254                part[h] = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
255                          k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
256                          k8[6] * qb.z() + k8[7] * qb.w();
257            }
258#pragma unroll
259            for (int h = G; h < 16; ++h) part[h] = 0.0f;
260            const auto xr = [](float v, int o) {
261                return dpct::experimental::permute_sub_group_by_xor(
262                    0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), v, o);
263            };
264            float c8[8];
265            const bool b16 = (lane & 16) != 0, b8 = (lane & 8) != 0, b4 = (lane & 4) != 0, b2 = (lane & 2) != 0;
266#pragma unroll
267            for (int i = 0; i < 8; ++i) {
268                const float send = b16 ? part[i] : part[8 + i];
269                const float keep = b16 ? part[8 + i] : part[i];
270                c8[i] = keep + xr(send, 16);
271            }
272            float c4[4];
273#pragma unroll
274            for (int i = 0; i < 4; ++i) {
275                const float send = b8 ? c8[i] : c8[4 + i];
276                const float keep = b8 ? c8[4 + i] : c8[i];
277                c4[i] = keep + xr(send, 8);
278            }
279            float c2[2];
280#pragma unroll
281            for (int i = 0; i < 2; ++i) {
282                const float send = b4 ? c4[i] : c4[2 + i];
283                const float keep = b4 ? c4[2 + i] : c4[i];
284                c2[i] = keep + xr(send, 4);
285            }
286            const float send1 = b2 ? c2[0] : c2[1];
287            const float keep1 = b2 ? c2[1] : c2[0];
288            float s = keep1 + xr(send1, 2);
289            s = s + xr(s, 1);
290            const int head = (lane >> 1) & 15;
291            if ((lane & 1) == 0 && head < G) sp[spi(head, c)] = s * scale;
292        } else {
293#pragma unroll
294        for (int h = 0; h < G; ++h) {
295            const sycl::float4 qa =
296                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8]);
297            const sycl::float4 qb =
298                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8 + 4]);
299            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
300                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
301                      k8[6] * qb.z() + k8[7] * qb.w();
302            s = warp_sum(s);
303            if (lane == 0) sp[spi(h, c)] = s * scale;
304        }
305        }
306    }
307    /*
308    DPCT1065: Consider replacing sycl::nd_item::barrier() with
309    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
310    performance if there is no access to global memory.
311    */
312    item_ct1.barrier();
313    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
314    for (int h = warp; h < G; h += WARPS) {
315        const float a = sp[spi(h, lane)], b = sp[spi(h, lane + 32)];
316        const float m = warp_max(sycl::fmax(a, b));
317        const float ea = (lane < n_here && srow[lane] >= 0)
318                             ? sycl::native::exp(a - m)
319                             : 0.0f;
320        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
321                             ? sycl::native::exp(b - m)
322                             : 0.0f;
323        sp[spi(h, lane)] = ea;
324        sp[spi(h, lane + 32)] = eb;
325        const float l = warp_sum(ea + eb);
326        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
327    }
328    /*
329    DPCT1065: Consider replacing sycl::nd_item::barrier() with
330    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
331    performance if there is no access to global memory.
332    */
333    item_ct1.barrier();
334    // values: thread t owns dimension t for all 12 heads.
335    float acc[G];
336#pragma unroll
337    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
338    for (int c = 0; c < n_here; ++c) {
339        if (srow[c] < 0) continue;   // masked above, weight 0
340        float v;
341        if constexpr (KV_MODE == 0) {
342            v = sycl::vec<sycl::half, 1>(
343                    sycl::bit_cast<sycl::half, unsigned short>(
344                        p.v_pool[srow[c] * HD + t]))
345                    .convert<float, sycl::rounding_mode::automatic>()[0];
346        } else if constexpr (KV_MODE == 1) {
347            const float sc =
348                sycl::vec<sycl::half, 1>(
349                    sycl::bit_cast<sycl::half, unsigned short>(
350                        p.v_scale[srow[c] * (HD / KV_Q8_GROUP) +
351                                  t / KV_Q8_GROUP]))
352                    .convert<float, sycl::rounding_mode::automatic>()[0];
353            v = (float) p.v_q[srow[c] * HD + t] * sc;
354        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
355            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
356            const int b = t / QK4_0;
357            const int rem = t % QK4_0;
358            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
359            const float d =
360                sycl::vec<sycl::half, 1>(
361                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
362                    .convert<float, sycl::rounding_mode::automatic>()[0];
363            const int j = rem < 16 ? rem : (rem - 16);
364            const uint8_t byte = blk->qs[j];
365            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
366            v = (float) nibble * d;
367        }
368        if constexpr (RS != 0) {
369            // the cell's 12 probabilities as three vector loads (the layout is [cell][head]); the same fma per head in the same order
370#pragma unroll
371            for (int q4 = 0; q4 < G / 4; ++q4) {
372                const sycl::float4 pv = *reinterpret_cast<const sycl::float4 *>(&sp[c * G + 4 * q4]);
373                acc[4 * q4 + 0] = sycl::fma(pv.x(), v, acc[4 * q4 + 0]);
374                acc[4 * q4 + 1] = sycl::fma(pv.y(), v, acc[4 * q4 + 1]);
375                acc[4 * q4 + 2] = sycl::fma(pv.z(), v, acc[4 * q4 + 2]);
376                acc[4 * q4 + 3] = sycl::fma(pv.w(), v, acc[4 * q4 + 3]);
377            }
378        } else {
379#pragma unroll
380        for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[spi(h, c)], v, acc[h]);
381        }
382    }
383#pragma unroll
384    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
385}
386
387// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
388// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk.  It
389// uses more registers (80 vs 38 on sm_70), so it runs on cards below sm_75 only, and exists only in the experimental
390// build (-DSTRATA_EXPERIMENTAL_SM60=ON): the ready-made engine keeps exactly the kernel above.
391#if defined(STRATA_EXPERIMENTAL_SM60)
392// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1):
393// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes),
394// for 16 shuffles instead of 12 x 5.  Lane l ends holding head head_of_lane(l); lanes l and l^1 agree.
395__device__ __forceinline__ float reduce12(const float (&part)[16], int lane) {
396    float r8[8];
397#pragma unroll
398    for (int i = 0; i < 8; ++i) {
399        const bool hi = (lane & 16) != 0;
400        r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16);
401    }
402    float r4[4];
403#pragma unroll
404    for (int i = 0; i < 4; ++i) {
405        const bool hi = (lane & 8) != 0;
406        r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8);
407    }
408    float r2[2];
409#pragma unroll
410    for (int i = 0; i < 2; ++i) {
411        const bool hi = (lane & 4) != 0;
412        r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4);
413    }
414    const bool hi2 = (lane & 2) != 0;
415    const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2);
416    return r1 + __shfl_xor_sync(0xffffffffu, r1, 1);
417}
418__device__ __forceinline__ int head_of_lane(int lane) {
419    return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
420}
421
422// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format.
423template <int KV_MODE>
424__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) {
425    if constexpr (KV_MODE == 0) {
426        return __half2float(__ushort_as_half(p.v_pool[row * HD + d]));
427    } else if constexpr (KV_MODE == 1) {
428        const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP]));
429        return (float) p.v_q[row * HD + d] * sc;
430    } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
431        constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
432        const int b = d / QK4_0;
433        const int rem = d % QK4_0;
434        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
435        const float dd = __half2float(__ushort_as_half(blk->d));
436        const int j = rem < 16 ? rem : (rem - 16);
437        const uint8_t byte = blk->qs[j];
438        const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
439        return (float) nibble * dd;
440    }
441}
442
443template <int KV_MODE>
444__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* __restrict__ q, QsaAttnPools p,
445                                                             const int32_t* __restrict__ ids,
446                                                             const int32_t* __restrict__ step, int n_kv_heads,
447                                                             int page_size, float scale, float* __restrict__ part_acc,
448                                                             float* __restrict__ part_m, float* __restrict__ part_l,
449                                                             int n_chunks, int cap = 0, long long scratch_stride = 0) {
450    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
451    q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
452    ids += (size_t) blockIdx.z * (size_t) cap;
453    step += (size_t) blockIdx.z * kStepCount;
454    part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
455    part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
456    part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
457    __shared__ __align__(16) float sq[G][HD];     // 12 KB: this KV head's query heads (dead once the scores are done)
458    __shared__ float sp[G][CHUNK];                // scores
459    __shared__ long long srow[CHUNK];             // pool row of each cell (page, kv head, slot)
460    // probabilities, cell-major: the value loop reads one cell's 12 as three float4.  They are first written after the
461    // __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12
462    // floats) and the block's shared memory stays what it was before the cell-major layout.
463    float (*const spt)[G] = reinterpret_cast<float (*)[G]>(&sq[0][0]);
464    static_assert(CHUNK * G <= G * HD, "spt must fit in sq");
465    const int n_ids = __ldg(step + kStepWidth);
466    const int chunk = blockIdx.x, kvh = blockIdx.y;
467    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
468    const int c0 = chunk * CHUNK;
469    const int n_here = min(CHUNK, n_ids - c0);
470    const int slot = kvh * n_chunks + chunk;
471    if (n_here <= 0) {
472        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
473        return;
474    }
475    for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
476    if (t < CHUNK) {
477        long long r = -1;
478        if (t < n_here) {
479            const int cell = ids[c0 + t];
480            const long long page = (long long) p.page_table[cell / page_size];
481            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
482            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
483            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
484        }
485        srow[t] = r;
486    }
487    __syncthreads();
488    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.  NC cells per step
489    // (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts the traffic
490    // that bounds this phase (24 x 16 B per lane per cell, against the FMAs) by NC; every dot product is the same
491    // expression as for a single cell, so the scores are unchanged.
492    constexpr int NC = 2;   // 4 measured slower on a V100 (the registers cost occupancy)
493    const int hd = head_of_lane(lane);
494    for (int i = 0; i < CHUNK / WARPS; i += NC) {
495        int cc[NC];
496        bool all_ok = true;
497#pragma unroll
498        for (int j = 0; j < NC; ++j) {
499            cc[j] = warp + WARPS * (i + j);
500            all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;
501        }
502        if (all_ok) {
503            float kk[NC][8];
504#pragma unroll
505            for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);
506            float pp[NC][16];
507#pragma unroll
508            for (int h = 0; h < G; ++h) {
509                const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
510                const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
511#pragma unroll
512                for (int j = 0; j < NC; ++j)
513                    pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w +
514                               kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;
515            }
516#pragma unroll
517            for (int j = 0; j < NC; ++j) {
518#pragma unroll
519                for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;
520                const float sj = reduce12(pp[j], lane);
521                if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;
522            }
523        } else {
524            for (int k = 0; k < NC; ++k) {   // a masked or out-of-range cell in the group: one cell at a time
525                const int c = cc[k];
526                if (c >= n_here || srow[c] < 0) {
527                    if (lane < G) sp[lane][c] = -FLT_MAX;
528                    continue;
529                }
530                float k8[8];
531                load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
532                float part[16];
533#pragma unroll
534                for (int h = 0; h < G; ++h) {
535                    const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
536                    const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
537                    part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
538                              k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
539                }
540#pragma unroll
541                for (int h = G; h < 16; ++h) part[h] = 0.0f;
542                const float s = reduce12(part, lane);
543                if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;
544            }
545        }
546    }
547    __syncthreads();
548    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
549    for (int h = warp; h < G; h += WARPS) {
550        const float a = sp[h][lane], b = sp[h][lane + 32];
551        const float m = warp_max(fmaxf(a, b));
552        const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
553        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
554        spt[lane][h] = ea;
555        spt[lane + 32][h] = eb;
556        const float l = warp_sum(ea + eb);
557        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
558    }
559    __syncthreads();
560    // values: thread t owns dimension t for all 12 heads.
561    float acc[G];
562#pragma unroll
563    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
564    // One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
565    // ascending order, so the sums are the plain loop's, bit for bit.
566    const auto fold = [&](int c, float v) {
567        const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
568        const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];
569        acc[0] = fmaf(w0.x, v, acc[0]);  acc[1] = fmaf(w0.y, v, acc[1]);
570        acc[2] = fmaf(w0.z, v, acc[2]);  acc[3] = fmaf(w0.w, v, acc[3]);
571        acc[4] = fmaf(w1.x, v, acc[4]);  acc[5] = fmaf(w1.y, v, acc[5]);
572        acc[6] = fmaf(w1.z, v, acc[6]);  acc[7] = fmaf(w1.w, v, acc[7]);
573        acc[8] = fmaf(w2.x, v, acc[8]);  acc[9] = fmaf(w2.y, v, acc[9]);
574        acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);
575    };
576    int c = 0;
577    // four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
578    // a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.
579    for (; c + 4 <= n_here; c += 4) {
580        const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];
581        if ((r0 | r1 | r2 | r3) < 0) break;
582        const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);
583        const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);
584        fold(c, v0);
585        fold(c + 1, v1);
586        fold(c + 2, v2);
587        fold(c + 3, v3);
588    }
589    for (; c < n_here; ++c) {
590        if (srow[c] < 0) continue;   // masked above, weight 0
591        fold(c, load_v1<KV_MODE>(p, srow[c], t));
592    }
593#pragma unroll
594    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
595}
596#endif  // STRATA_EXPERIMENTAL_SM60
597
598__dpct_inline__ void attn_merge_kernel(const float *__restrict__ part_acc,
599                                       const float *__restrict__ part_m,
600                                       const float *__restrict__ part_l,
601                                       int n_chunks, float *__restrict__ attn,
602                                       long long scratch_stride = 0) {
603    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
604    part_acc += (size_t)item_ct1.get_group(1) * (size_t)scratch_stride;
605    part_m += (size_t)item_ct1.get_group(1) * (size_t)scratch_stride;
606    part_l += (size_t)item_ct1.get_group(1) * (size_t)scratch_stride;
607    attn += (size_t)item_ct1.get_group(1) *
608            (size_t)item_ct1.get_group_range(2) * HD;
609    const int h = item_ct1.get_group(2); // global query head
610    const int kvh = h / G, hl = h % G;
611    const int d = item_ct1.get_local_id(2);
612    float M = -FLT_MAX;
613#pragma unroll
614    for (int c = 0; c < n_chunks; ++c)
615        M = sycl::fmax(M, part_m[(kvh * n_chunks + c) * G + hl]);
616    float L = 0.0f, acc = 0.0f;
617    for (int c = 0; c < n_chunks; ++c) {
618        const int slot = kvh * n_chunks + c;
619        const float m = part_m[slot * G + hl];
620        if (m == -FLT_MAX) continue;
621        const float w = sycl::native::exp(m - M);
622        L = sycl::fma((float)(part_l[slot * G + hl]), (float)w, L);
623        acc = sycl::fma((float)(part_acc[((size_t)slot * G + hl) * HD + d]),
624                        (float)w, acc);
625    }
626    attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
627}
628
629// Chunks beyond the device-side width contain only -FLT_MAX maxima. Keep the
630// original fold order while issuing eight independent partial reads together.
631__dpct_inline__ void attn_merge_active_kernel(
632    const float *__restrict__ part_acc, const float *__restrict__ part_m,
633    const float *__restrict__ part_l, int n_chunks, float *__restrict__ attn,
634    long long scratch_stride, const int32_t *__restrict__ steps) {
635    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
636    const int z = item_ct1.get_group(1);
637    part_acc += (size_t) z * (size_t) scratch_stride;
638    part_m += (size_t) z * (size_t) scratch_stride;
639    part_l += (size_t) z * (size_t) scratch_stride;
640    attn += (size_t) z * (size_t) item_ct1.get_group_range(2) * HD;
641    const int width = steps[(size_t) z * kStepCount + kStepWidth];
642    const int reach = width <= 0 ? 0 : 1 + (width - 1) / CHUNK;
643    const int nc = sycl::min(reach, n_chunks);
644    const int h = item_ct1.get_group(2), kvh = h / G, hl = h % G;
645    const int d = item_ct1.get_local_id(2);
646    const float* pm_h = part_m + (size_t) kvh * n_chunks * G + hl;
647    const float* pl_h = part_l + (size_t) kvh * n_chunks * G + hl;
648    const float* pa_h = part_acc + ((size_t) kvh * n_chunks * G + hl) * HD + d;
649    constexpr int MU = 8;
650    float M = -FLT_MAX;
651    int c = 0;
652    for (; c + MU <= nc; c += MU) {
653        float pm[MU];
654#pragma unroll
655        for (int j = 0; j < MU; ++j) pm[j] = pm_h[(size_t) (c + j) * G];
656#pragma unroll
657        for (int j = 0; j < MU; ++j) M = sycl::fmax(M, pm[j]);
658    }
659    for (; c < nc; ++c) M = sycl::fmax(M, pm_h[(size_t) c * G]);
660    float L = 0.0f, acc = 0.0f;
661    c = 0;
662    for (; c + MU <= nc; c += MU) {
663        float pm[MU], pl[MU], pa[MU];
664#pragma unroll
665        for (int j = 0; j < MU; ++j) {
666            pm[j] = pm_h[(size_t) (c + j) * G];
667            pl[j] = pl_h[(size_t) (c + j) * G];
668            pa[j] = pa_h[(size_t) (c + j) * G * HD];
669        }
670#pragma unroll
671        for (int j = 0; j < MU; ++j) {
672            if (pm[j] == -FLT_MAX) continue;
673            const float w = sycl::native::exp(pm[j] - M);
674            L = sycl::fma(pl[j], w, L);
675            acc = sycl::fma(pa[j], w, acc);
676        }
677    }
678    for (; c < nc; ++c) {
679        const float m = pm_h[(size_t) c * G];
680        if (m == -FLT_MAX) continue;
681        const float w = sycl::native::exp(m - M);
682        L = sycl::fma(pl_h[(size_t) c * G], w, L);
683        acc = sycl::fma(pa_h[(size_t) c * G * HD], w, acc);
684    }
685    attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
686}
687
688bool merge_active_on(const sycl::device& d) {
689    static const bool on = strata::bm_default_on("STRATA_ATTN_MERGE_ACTIVE", d);
690    return on;
691}
692
693// BEGIN PRIVATE QSA TWO STAGE HELPER
694
695struct QsaMergeGroupPartial { float m, l, acc; };
696__dpct_inline__ QsaMergeGroupPartial qsa_merge_group_partial(
697    const float* __restrict__ part_acc, const float* __restrict__ part_m,
698    const float* __restrict__ part_l, int n_chunks, int kvh, int hl, int d,
699    int first, int last) {
700    float M = -FLT_MAX;
701#pragma unroll
702    for (int c = first; c < last; ++c)
703        M = sycl::fmax(M, part_m[(kvh * n_chunks + c) * G + hl]);
704    float L = 0.0f, acc = 0.0f;
705    for (int c = first; c < last; ++c) {
706        const int slot = kvh * n_chunks + c;
707        const float m = part_m[slot * G + hl];
708        if (m == -FLT_MAX) continue;
709        const float w = sycl::native::exp(m - M);
710        L = sycl::fma((float)(part_l[slot * G + hl]), (float)w, L);
711        acc = sycl::fma((float)(part_acc[((size_t)slot * G + hl) * HD + d]),
712                        (float)w, acc);
713    }
714    return {M, L, acc};
715}
716
717constexpr int QsaMergeGroupChunks = 32;
718class QsaMergeTwoStageOriginal;
719class QsaMergeTwoStagePartial;
720class QsaMergeTwoStageFinal;
721
722void launch_qsa_merge_two_stage_original(const float* part_acc,
723    const float* part_m, const float* part_l, int n_chunks, float* out,
724    sycl::queue* queue) {
725    auto props = sycl::ext::oneapi::experimental::properties{};
726    queue->parallel_for<QsaMergeTwoStageOriginal>(
727        sycl::nd_range<3>(sycl::range<3>(1, 1, size_t(24) * THREADS),
728                          sycl::range<3>(1, 1, THREADS)), props,
729        [=](sycl::nd_item<3>) {
730            attn_merge_kernel(part_acc, part_m, part_l, n_chunks, out, 0);
731        });
732}
733
734void launch_qsa_merge_two_stage_partial(const float* part_acc,
735    const float* part_m, const float* part_l, int n_chunks,
736    float* group_acc, float* group_m, float* group_l, int n_groups,
737    float* out, sycl::queue* queue) {
738    static_assert(HD == 256 && G == 12 && THREADS == 256);
739    auto props = sycl::ext::oneapi::experimental::properties{};
740    queue->parallel_for<QsaMergeTwoStagePartial>(
741        sycl::nd_range<3>(sycl::range<3>(1, 1, size_t(24) * n_groups * THREADS),
742                          sycl::range<3>(1, 1, THREADS)), props,
743        [=](sycl::nd_item<3> item) {
744            const size_t index = item.get_group(2);
745            const int h = int(index / n_groups), group = int(index % n_groups);
746            const int kvh = h / G, hl = h % G;
747            const int d = int(item.get_local_id(2));
748            const int first = group * QsaMergeGroupChunks;
749            const int last = sycl::min(first + QsaMergeGroupChunks, n_chunks);
750            const auto partial = qsa_merge_group_partial(
751                part_acc, part_m, part_l, n_chunks, kvh, hl, d, first, last);
752            const int slot = (kvh * n_groups + group) * G + hl;
753            // Keep an unnormalised acc: the original final helper applies L once.
754            group_acc[size_t(slot) * HD + d] = partial.acc;
755            if (d == 0) { group_m[slot] = partial.m; group_l[slot] = partial.l; }
756        });
757    // The caller's in-order queue/capture supplies the inter-kernel dependency.
758    // No new wait/event/node API, SLM or global barrier is introduced here.
759    queue->parallel_for<QsaMergeTwoStageFinal>(
760        sycl::nd_range<3>(sycl::range<3>(1, 1, size_t(24) * THREADS),
761                          sycl::range<3>(1, 1, THREADS)), props,
762        [=](sycl::nd_item<3>) {
763            attn_merge_kernel(group_acc, group_m, group_l, n_groups, out, 0);
764        });
765}
766// END PRIVATE QSA TWO STAGE HELPER
767#if defined(STRATA_EXPERIMENTAL_SM60)
768// the current device is below sm_75 (per device: a layer split can mix cards); STRATA_ATTN_PRE75=0 turns PR #540's
769// kernel off (A/B)
770bool pre75_attn() {
771    static const bool off = [] {
772        const char* e = std::getenv("STRATA_ATTN_PRE75");
773        return e != nullptr && e[0] == '0';
774    }();
775    static int cc[64] = {};
776    int dev = 0;
777    if (off) return false;
778    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
779    if (cc[dev] == 0) {
780        int major = 0, minor = 0;
781        if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
782            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
783            cudaGetLastError();
784            return false;
785        }
786        cc[dev] = 10 * major + minor;
787    }
788    return cc[dev] < 75;
789}
790#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
791#else
792#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
793#endif
794
795// ---- SYCL port: the prompt path's chunk kernel with the scores computed one work-item per cell (attn_bench).
796// The warp kernel above splits a cell's 256 dimensions over a sub-group and adds them up with a 5-step shuffle
797// tree per query head - 60 shuffles a cell. Here work-item c holds cell c's key row (16-byte loads) and all 12
798// heads' dot products, reading the query heads from local memory, where every work-item reads the same element
799// at once. 128-cell chunks. The values pass is the warp kernel's. FP32, but another summation order than the warp
800// kernel: not bitwise (relative error ~2e-7 in attn_bench); attn_bench: 1.55-1.69x the warp kernel's time.
801constexpr int PC_CHUNK = 128;
802
803// 16 consecutive key values of row `row`, dimensions [d0, d0+16)
804template <int KV_MODE>
805__dpct_inline__ void load16_k(const QsaAttnPools &p, long long row, int d0, float *out) {
806    if constexpr (KV_MODE == 0) {
807        load8_f16(p, false, row, d0, out);
808        load8_f16(p, false, row, d0 + 8, out + 8);
809    } else if constexpr (KV_MODE == 1 || KV_MODE == 3) {
810        const int8_t* codes = p.k_q + row * HD + d0;
811        const float sc = sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
812                             p.k_scale[row * (HD / KV_Q8_GROUP) + d0 / KV_Q8_GROUP]))
813                             .convert<float, sycl::rounding_mode::automatic>()[0];
814        const sycl::int4 raw = *reinterpret_cast<const sycl::int4 *>(codes);
815        const int8_t* c = reinterpret_cast<const int8_t*>(&raw);
816#pragma unroll
817        for (int j = 0; j < 16; ++j) out[j] = (float) c[j] * sc;
818    } else {   // q4_0 (rotated): element j of a 32-block in qs[j]'s low nibble, j + 16 in its high one
819        load8_q4(p, false, row, d0, out);
820        load8_q4(p, false, row, d0 + 8, out + 8);
821    }
822}
823
824template <int KV_MODE>
825__dpct_inline__ float load1_v(const QsaAttnPools &p, long long row, int t) {
826    if constexpr (KV_MODE == 0) {
827        return sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(p.v_pool[row * HD + t]))
828            .convert<float, sycl::rounding_mode::automatic>()[0];
829    } else if constexpr (KV_MODE == 1) {
830        const float sc = sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
831                             p.v_scale[row * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP]))
832                             .convert<float, sycl::rounding_mode::automatic>()[0];
833        return (float) p.v_q[row * HD + t] * sc;
834    } else {
835        constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
836        const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + t / QK4_0;
837        const float d = sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(blk->d))
838                            .convert<float, sycl::rounding_mode::automatic>()[0];
839        const int rem = t % QK4_0;
840        const uint8_t byte = blk->qs[rem < 16 ? rem : rem - 16];
841        return (float) ((rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8)) * d;
842    }
843}
844
845template <int KV_MODE>
846__dpct_inline__ void attn_chunk_percell_kernel(const float *__restrict__ q, QsaAttnPools p,
847                                               const int32_t *__restrict__ ids, const int32_t *__restrict__ step,
848                                               int n_kv_heads, int page_size, float scale, float *__restrict__ part_acc,
849                                               float *__restrict__ part_m, float *__restrict__ part_l, int n_chunks,
850                                               int cap, long long scratch_stride) {
851    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
852    auto sg = item_ct1.get_sub_group();
853    q += (size_t) item_ct1.get_group(0) * (size_t) (n_kv_heads * G) * HD;
854    ids += (size_t) item_ct1.get_group(0) * (size_t) cap;
855    step += (size_t) item_ct1.get_group(0) * kStepCount;
856    part_acc += (size_t) item_ct1.get_group(0) * (size_t) scratch_stride;
857    part_m += (size_t) item_ct1.get_group(0) * (size_t) scratch_stride;
858    part_l += (size_t) item_ct1.get_group(0) * (size_t) scratch_stride;
859    auto &sq = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
860        sycl::ext::oneapi::this_work_item::get_work_group<3>());
861    auto &sp = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][PC_CHUNK]>(
862        sycl::ext::oneapi::this_work_item::get_work_group<3>());
863    auto &srow = *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[PC_CHUNK]>(
864        sycl::ext::oneapi::this_work_item::get_work_group<3>());
865    const int n_ids = *(step + kStepWidth);
866    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
867    const int t = item_ct1.get_local_id(2);
868    const int lane = (int) sg.get_local_id()[0], warp = (int) sg.get_group_id()[0];
869    const int SGS = (int) sg.get_local_range()[0], NW = THREADS / SGS;
870    const int c0 = chunk * PC_CHUNK;
871    const int n_here = sycl::min(PC_CHUNK, n_ids - c0);
872    const int slot = kvh * n_chunks + chunk;
873    if (n_here <= 0) {
874        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
875        return;
876    }
877    for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
878    for (int c = t; c < PC_CHUNK; c += THREADS) {
879        long long r = -1;
880        if (c < n_here) {
881            const int cell = ids[c0 + c];
882            const long long page = (long long) p.page_table[cell / page_size];
883            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);   // -1: masked (KV streaming)
884        }
885        srow[c] = r;
886    }
887    item_ct1.barrier(sycl::access::fence_space::local_space);
888    for (int c = t; c < PC_CHUNK; c += THREADS) {
889        if (c >= n_here || srow[c] < 0) {
890#pragma unroll
891            for (int h = 0; h < G; ++h) sp[h][c] = -FLT_MAX;
892            continue;
893        }
894        float acc_s[G];
895#pragma unroll
896        for (int h = 0; h < G; ++h) acc_s[h] = 0.0f;
897        for (int d = 0; d < HD; d += 16) {
898            float kf[16];
899            load16_k<KV_MODE>(p, srow[c], d, kf);
900#pragma unroll
901            for (int h = 0; h < G; ++h) {   // a 16-dimension block in four short chains, then into the cell's sum:
902                float b0 = 0.0f, b1 = 0.0f, b2 = 0.0f, b3 = 0.0f;   // FP32 error near the warp kernel's tree
903#pragma unroll
904                for (int j = 0; j < 16; j += 4) {
905                    b0 = sycl::fma(kf[j], sq[h][d + j], b0);
906                    b1 = sycl::fma(kf[j + 1], sq[h][d + j + 1], b1);
907                    b2 = sycl::fma(kf[j + 2], sq[h][d + j + 2], b2);
908                    b3 = sycl::fma(kf[j + 3], sq[h][d + j + 3], b3);
909                }
910                acc_s[h] += (b0 + b1) + (b2 + b3);
911            }
912        }
913#pragma unroll
914        for (int h = 0; h < G; ++h) sp[h][c] = acc_s[h] * scale;
915    }
916    item_ct1.barrier(sycl::access::fence_space::local_space);
917    for (int h = warp; h < G; h += NW) {
918        float m = -FLT_MAX;
919        for (int c = lane; c < PC_CHUNK; c += SGS) m = sycl::fmax(m, sp[h][c]);
920        m = sycl::reduce_over_group(sg, m, sycl::maximum<float>());
921        float l = 0.0f;
922        for (int c = lane; c < PC_CHUNK; c += SGS) {
923            const float e = (c < n_here && srow[c] >= 0) ? sycl::native::exp(sp[h][c] - m) : 0.0f;
924            sp[h][c] = e;
925            l += e;
926        }
927        l = sycl::reduce_over_group(sg, l, sycl::plus<float>());
928        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
929    }
930    item_ct1.barrier(sycl::access::fence_space::local_space);
931    float acc[G];
932#pragma unroll
933    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
934    for (int c = 0; c < n_here; ++c) {
935        if (srow[c] < 0) continue;   // masked above, weight 0
936        const float v = load1_v<KV_MODE == 3 ? 2 : KV_MODE>(p, srow[c], t);
937#pragma unroll
938        for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c], v, acc[h]);
939    }
940#pragma unroll
941    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
942}
943
944template <int KV_MODE>
945void launch_percell(dpct::queue_ptr st, const float* q, const QsaAttnPools& pools, const int32_t* ids,
946                    const int32_t* steps, int64_t cap, const QsaShapes& s, float* part_acc, float* part_m, float* part_l,
947                    int n_chunks, long long stride, int64_t n_q, float scale) {
948    const sycl::range<3> grid((size_t) n_q, (size_t) s.n_head_kv, (size_t) n_chunks);
949    st->parallel_for(sycl::nd_range<3>(grid * sycl::range<3>(1, 1, THREADS), sycl::range<3>(1, 1, THREADS)),
950                     [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
951                         attn_chunk_percell_kernel<KV_MODE>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
952                                                            scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
953                     });
954}
955
956}  // namespace
957
958
959static void launch_qsa_chunk_down(int,const float*,const QsaAttnPools&,const int32_t*,const int32_t*,int64_t,
960                           const QsaShapes&,float*,float*,int64_t,void*);
961bool qsa_chunk_down_supported(int64_t cap, int64_t n_q, const QsaShapes& s, void* stream) {
962    static const bool enabled = [] {
963        const char* v = std::getenv("STRATA_SYCL_QSA_CHUNK_DOWN");
964        return !v || v[0] == '1';
965    }();
966    const bool batch = n_q >= 1 && n_q <= 6;
967    const bool shape = (cap == 2051 && (batch || n_q == 32)) || (cap == 32768 && batch);
968    return enabled && shape && s.n_head == 24 && s.n_head_kv == 2 && s.page_size == 4 &&
969        strata::intel_gpu_gen(strata::q_of(stream)->get_device()) == strata::IntelGpuGen::Battlemage;
970}
971// BEGIN PRIVATE QSA TWO STAGE ENTRY
972uint64_t qsa_merge_two_stage_scratch_floats(int n_chunks) {
973    if (n_chunks <= 0 || n_chunks > INT_MAX / 24)
974        throw std::invalid_argument("QSA two-stage scratch arguments");
975    const uint64_t n_groups = (uint64_t(n_chunks) + 31) / 32;
976    return n_groups * 24 * (HD + 2) + 64;
977}
978
979void qsa_merge_two_stage_probe(int mode, const float* scratch, int n_chunks,
980                               float* group_scratch, float* out, void* stream) {
981    if (mode < 0 || mode > 1 || !scratch || !out || !stream || n_chunks <= 0 ||
982        n_chunks > INT_MAX / 24 || (mode == 1 && !group_scratch))
983        throw std::invalid_argument("QSA two-stage diagnostic arguments");
984    auto* queue = strata::q_of(stream);
985    if (!queue->is_in_order())
986        throw std::invalid_argument("QSA two-stage probe requires an in-order queue");
987    const float* part_m = scratch + size_t(n_chunks) * 24 * HD;
988    const float* part_l = part_m + size_t(n_chunks) * 24;
989    if (mode == 0) {
990        launch_qsa_merge_two_stage_original(scratch, part_m, part_l, n_chunks, out, queue);
991        return;
992    }
993    const int n_groups = (n_chunks + 31) / 32;
994    float* group_m = group_scratch + size_t(n_groups) * 24 * HD;
995    float* group_l = group_m + size_t(n_groups) * 24;
996    launch_qsa_merge_two_stage_partial(scratch, part_m, part_l, n_chunks,
997                                      group_scratch, group_m, group_l, n_groups, out, queue);
998}
999
1000// END PRIVATE QSA TWO STAGE ENTRY
1001void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
1002                           int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1003    if (n_q <= 0) return;
1004    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps ||
1005        !pools.page_table || n_q > 65535) {
1006        std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n");
1007        std::exit(1);
1008    }
1009    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1010                        : (pools.k_q != nullptr ? 1 : 0));
1011    strata::workload_trace::Scope trace("decode.qsa_attention", stream, n_q, s.n_head, s.head_dim,
1012                                        cap, s.n_head_kv, kv_mode);
1013    if (qsa_chunk_down_supported(cap, n_q, s, stream) && kv_mode == 1 && pools.v_q) {
1014        launch_qsa_chunk_down(1, q, pools, ids, steps, cap, s, scratch, attn, n_q, stream);
1015        return;
1016    }
1017    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1018    // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride
1019    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1020    float* part_acc = scratch;
1021    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1022    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1023    const float scale = 1.0f / sqrtf((float) HD);
1024    const dpct::dim3 grid((unsigned)n_chunks, (unsigned)s.n_head_kv,
1025                          (unsigned)n_q);
1026    dpct::queue_ptr st = strata::q_of(stream);
1027    // S25: the score phase one cell per thread (bit-identical scores, no shuffle reductions).  Prompt batches take
1028    // it by default: on 2x Arc Pro B65 it reads a 4,106-token prompt 5.2% faster, 8,191 tokens 5.2% and 16,380
1029    // tokens 4.8%, with the same tokens; the decode window's few queries per call are 1.4% slower with it (56.6-57.0
1030    // against 55.9-56.3 tok/s), so the choice follows the query count.  It is a Battlemage (Xe2) default only: on an Arc
1031    // A750 (Alchemist) the same switch reads a 4,106-token prompt 0.7% slower (three interleaved runs, 4 of 5 pairs
1032    // faster with it off), so the generation comes from the device's architecture id (strata::intel_gpu_gen: the
1033    // runtime's architecture enum first, the name only as a fallback), never from the name alone.
1034    // STRATA_ATTN_LANECELL=1/0 forces either way on any device.
1035    static const int lane_cell_env = [] {
1036        const char* v = std::getenv("STRATA_ATTN_LANECELL");
1037        return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
1038    }();
1039    const bool lane_cell = lane_cell_env >= 0
1040        ? lane_cell_env != 0
1041        : (n_q >= 16 && strata::intel_gpu_gen(st->get_device()) == strata::IntelGpuGen::Battlemage);
1042#define STRATA_ATTN_LC(M)                                                      \
1043    {                                                                          \
1044        auto exp_props = sycl::ext::oneapi::experimental::properties{          \
1045            sycl::ext::oneapi::experimental::use_root_sync};                   \
1046        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});  \
1047                                                                               \
1048        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {                                   \
1049            auto q_ct0 = q;                                                    \
1050            QsaAttnPools pools_ct1 = pools;                                    \
1051            auto ids_ct2 = ids;                                                \
1052            auto steps_ct3 = steps;                                            \
1053            auto s_n_head_kv_ct4 = (int)s.n_head_kv;                           \
1054            auto s_page_size_ct5 = (int)s.page_size;                           \
1055            auto scale_ct6 = scale;                                            \
1056            auto part_acc_ct7 = part_acc;                                      \
1057            auto part_m_ct8 = part_m;                                          \
1058            auto part_l_ct9 = part_l;                                          \
1059            auto n_chunks_ct10 = n_chunks;                                     \
1060            auto cap_ct11 = (int)cap;                                          \
1061            auto stride_ct12 = stride;                                         \
1062                                                                               \
1063            cgh.parallel_for<dpct_kernel_name<class attn_chunk_kernel_6e87d5,  \
1064                                              dpct_kernel_scalar<M>,           \
1065                                              dpct_kernel_scalar<true>>>(      \
1066                sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),           \
1067                                  sycl::range(1, 1, THREADS)),                 \
1068                exp_props,                                                     \
1069                [=](sycl::nd_item<3> item_ct1)                                 \
1070                    [[sycl::reqd_sub_group_size(32)]] {                        \
1071                        attn_chunk_kernel<M, true>(                            \
1072                            q_ct0, pools_ct1, ids_ct2, steps_ct3,              \
1073                            s_n_head_kv_ct4, s_page_size_ct5, scale_ct6,       \
1074                            part_acc_ct7, part_m_ct8, part_l_ct9,              \
1075                            n_chunks_ct10, cap_ct11, stride_ct12);             \
1076                    });                                                        \
1077        });                                                                    \
1078    }
1079#define STRATA_ATTN_RSK(M, V)                                                      \
1080    {                                                                          \
1081        auto exp_props = sycl::ext::oneapi::experimental::properties{          \
1082            sycl::ext::oneapi::experimental::use_root_sync};                   \
1083        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});  \
1084                                                                               \
1085        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {                                   \
1086            auto q_ct0 = q;                                                    \
1087            QsaAttnPools pools_ct1 = pools;                                    \
1088            auto ids_ct2 = ids;                                                \
1089            auto steps_ct3 = steps;                                            \
1090            auto s_n_head_kv_ct4 = (int)s.n_head_kv;                           \
1091            auto s_page_size_ct5 = (int)s.page_size;                           \
1092            auto scale_ct6 = scale;                                            \
1093            auto part_acc_ct7 = part_acc;                                      \
1094            auto part_m_ct8 = part_m;                                          \
1095            auto part_l_ct9 = part_l;                                          \
1096            auto n_chunks_ct10 = n_chunks;                                     \
1097            auto cap_ct11 = (int)cap;                                          \
1098            auto stride_ct12 = stride;                                         \
1099                                                                               \
1100            cgh.parallel_for<dpct_kernel_name<class attn_chunk_kernel_rs_7c2a91,  \
1101                                              dpct_kernel_scalar<M>,           \
1102                                              dpct_kernel_scalar<V>>>(      \
1103                sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),           \
1104                                  sycl::range(1, 1, THREADS)),                 \
1105                exp_props,                                                     \
1106                [=](sycl::nd_item<3> item_ct1)                                 \
1107                    [[sycl::reqd_sub_group_size(32)]] {                        \
1108                        attn_chunk_kernel<M, false, V>(                            \
1109                            q_ct0, pools_ct1, ids_ct2, steps_ct3,              \
1110                            s_n_head_kv_ct4, s_page_size_ct5, scale_ct6,       \
1111                            part_acc_ct7, part_m_ct8, part_l_ct9,              \
1112                            n_chunks_ct10, cap_ct11, stride_ct12);             \
1113                    });                                                        \
1114        });                                                                    \
1115    }
1116#undef STRATA_ATTN_RSK_DEFINED
1117    // 151-b70: STRATA_ATTN_RS=2 (default): the probabilities in [cell][head] order and the value phase reading a cell's 12 as three vectors - the same
1118    // bits (first-token logits md5 equal at 4K and 16K), +0.8..0.9% prompt tok/s on the B70; =1 adds a 16-shuffle reduce-scatter for the scores
1119    // (bit-exact too, but -1.5% here: the score phase is not shuffle bound); =0 the layout before
1120    static const int rs_on = [] { const char* v = std::getenv("STRATA_ATTN_RS"); return v ? std::atoi(v) : 2; }();
1121    if (lane_cell) {
1122        if (kv_mode == 3) { STRATA_ATTN_LC(3); }
1123        else if (kv_mode == 2) { STRATA_ATTN_LC(2); }
1124        else if (kv_mode == 1) { STRATA_ATTN_LC(1); }
1125        else { STRATA_ATTN_LC(0); }
1126    } else if (rs_on == 1) {
1127        if (kv_mode == 3) { STRATA_ATTN_RSK(3, 1); }
1128        else if (kv_mode == 2) { STRATA_ATTN_RSK(2, 1); }
1129        else if (kv_mode == 1) { STRATA_ATTN_RSK(1, 1); }
1130        else { STRATA_ATTN_RSK(0, 1); }
1131    } else if (rs_on == 2) {
1132        if (kv_mode == 3) { STRATA_ATTN_RSK(3, 2); }
1133        else if (kv_mode == 2) { STRATA_ATTN_RSK(2, 2); }
1134        else if (kv_mode == 1) { STRATA_ATTN_RSK(1, 2); }
1135        else { STRATA_ATTN_RSK(0, 2); }
1136    } else
1137#undef STRATA_ATTN_LC
1138#undef STRATA_ATTN_RSK
1139    if (kv_mode == 3)
1140    {
1141        auto exp_props = sycl::ext::oneapi::experimental::properties{
1142            sycl::ext::oneapi::experimental::use_root_sync};
1143        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1144
1145        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_dfacfc,
1146                                          dpct_kernel_scalar<3>>>(
1147            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1148                              sycl::range(1, 1, THREADS)),
1149            exp_props,
1150            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1151                attn_chunk_kernel<3>(q, pools, ids, steps, (int)s.n_head_kv,
1152                                     (int)s.page_size, scale, part_acc, part_m,
1153                                     part_l, n_chunks, (int)cap, stride);
1154            });
1155    } else if (kv_mode == 2)
1156    {
1157        auto exp_props = sycl::ext::oneapi::experimental::properties{
1158            sycl::ext::oneapi::experimental::use_root_sync};
1159        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1160
1161        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_b0d448,
1162                                          dpct_kernel_scalar<2>>>(
1163            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1164                              sycl::range(1, 1, THREADS)),
1165            exp_props,
1166            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1167                attn_chunk_kernel<2>(q, pools, ids, steps, (int)s.n_head_kv,
1168                                     (int)s.page_size, scale, part_acc, part_m,
1169                                     part_l, n_chunks, (int)cap, stride);
1170            });
1171    } else if (kv_mode == 1)
1172    {
1173        auto exp_props = sycl::ext::oneapi::experimental::properties{
1174            sycl::ext::oneapi::experimental::use_root_sync};
1175        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1176
1177        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_2ad0a4,
1178                                          dpct_kernel_scalar<1>>>(
1179            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1180                              sycl::range(1, 1, THREADS)),
1181            exp_props,
1182            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1183                attn_chunk_kernel<1>(q, pools, ids, steps, (int)s.n_head_kv,
1184                                     (int)s.page_size, scale, part_acc, part_m,
1185                                     part_l, n_chunks, (int)cap, stride);
1186            });
1187    } else {
1188        auto exp_props = sycl::ext::oneapi::experimental::properties{
1189            sycl::ext::oneapi::experimental::use_root_sync};
1190        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1191
1192        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_5c04f7,
1193                                          dpct_kernel_scalar<0>>>(
1194            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1195                              sycl::range(1, 1, THREADS)),
1196            exp_props,
1197            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1198                attn_chunk_kernel<0>(q, pools, ids, steps, (int)s.n_head_kv,
1199                                     (int)s.page_size, scale, part_acc, part_m,
1200                                     part_l, n_chunks, (int)cap, stride);
1201            });
1202    }
1203    {
1204        auto exp_props = sycl::ext::oneapi::experimental::properties{
1205            sycl::ext::oneapi::experimental::use_root_sync};
1206
1207        if (merge_active_on(st->get_device()) && n_q <= 8) {
1208            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_merge_active>>(
1209                sycl::nd_range<3>(
1210                    sycl::range(1, (unsigned)n_q, (unsigned)s.n_head) *
1211                        sycl::range(1, 1, HD),
1212                    sycl::range(1, 1, HD)),
1213                exp_props, [=](sycl::nd_item<3> item_ct1) {
1214                    attn_merge_active_kernel(part_acc, part_m, part_l, n_chunks,
1215                                             attn, stride, steps);
1216                });
1217        } else {
1218            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_merge_kernel_338175>>(
1219                sycl::nd_range<3>(
1220                    sycl::range(1, (unsigned)n_q, (unsigned)s.n_head) *
1221                        sycl::range(1, 1, HD),
1222                    sycl::range(1, 1, HD)),
1223                exp_props, [=](sycl::nd_item<3> item_ct1) {
1224                    attn_merge_kernel(part_acc, part_m, part_l, n_chunks, attn,
1225                                      stride);
1226                });
1227        }
1228    }
1229    /*
1230    DPCT1010: SYCL uses exceptions to report errors and does not use the
1231    error codes. The cudaGetLastError function call was replaced with 0. You
1232    need to rewrite this code.
1233    */
1234    const dpct::err0 e = 0;
1235}
1236
1237namespace {
1238template <int M>
1239void attn_rows_chunks(dpct::queue_ptr st, const dpct::dim3& grid, const float* q, const QsaAttnPools& pools,
1240                      const int32_t* ids, const int32_t* steps, int n_kv_heads, int page_size, float scale,
1241                      float* part_acc, float* part_m, float* part_l, int n_chunks, int cap, long long stride,
1242                      const QsaAttnPoolsRows& rows) {
1243    auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
1244    dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1245    const QsaAttnPools p0 = pools;
1246    const QsaAttnPoolsRows rr = rows;
1247    strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_rows_chunk_kernel_9f2, dpct_kernel_scalar<M>>>(
1248        sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS), sycl::range(1, 1, THREADS)), exp_props,
1249        [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1250            attn_chunk_kernel<M, false, 2>(q, p0, ids, steps, n_kv_heads, page_size, scale, part_acc, part_m, part_l,
1251                                           n_chunks, cap, stride, rr);
1252        });
1253}
1254}  // namespace
1255
1256void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, const int32_t* ids, const int32_t* steps,
1257                                int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1258    if (n_q <= 0) return;
1259    const QsaAttnPools& pools = rows.p[0];
1260    if (rows.n != n_q || n_q > kAttnRowsMax || s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 ||
1261        !scratch || !ids || !steps) {
1262        std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n");
1263        std::exit(1);
1264    }
1265    static const int rs_on = [] { const char* v = std::getenv("STRATA_ATTN_RS"); return v ? std::atoi(v) : 2; }();
1266    static const int lane_cell_env = [] {
1267        const char* v = std::getenv("STRATA_ATTN_LANECELL");
1268        return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
1269    }();
1270    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1271    if (rs_on != 2 || lane_cell_env == 1) {   // a non-default per-row kernel is selected: the per-row calls
1272        for (int64_t z = 0; z < n_q; ++z)
1273            qsa_decode_attn_batch(q + (size_t) z * s.n_head * HD, rows.p[z], ids + (size_t) z * cap,
1274                                  steps + (size_t) z * kStepCount, cap, s, scratch + (size_t) z * stride,
1275                                  attn + (size_t) z * s.n_head * HD, 1, stream);
1276        return;
1277    }
1278    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1279                        : (pools.k_q != nullptr ? 1 : 0));
1280    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1281    float* part_acc = scratch;
1282    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1283    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1284    const float scale = 1.0f / sqrtf((float) HD);
1285    const dpct::dim3 grid((unsigned)n_chunks, (unsigned)s.n_head_kv, (unsigned)n_q);
1286    dpct::queue_ptr st = strata::q_of(stream);
1287    if (kv_mode == 3) attn_rows_chunks<3>(st, grid, q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride, rows);
1288    else if (kv_mode == 2) attn_rows_chunks<2>(st, grid, q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride, rows);
1289    else if (kv_mode == 1) attn_rows_chunks<1>(st, grid, q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride, rows);
1290    else attn_rows_chunks<0>(st, grid, q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride, rows);
1291    {
1292        auto exp_props = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::use_root_sync};
1293        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_merge_rows_kernel_9f2>>(
1294            sycl::nd_range<3>(sycl::range(1, (unsigned)n_q, (unsigned)s.n_head) * sycl::range(1, 1, HD),
1295                              sycl::range(1, 1, HD)),
1296            exp_props, [=](sycl::nd_item<3> item_ct1) {
1297                attn_merge_kernel(part_acc, part_m, part_l, n_chunks, attn, stride);
1298            });
1299    }
1300}
1301
1302uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) {
1303    const int64_t chunks = (cap + CHUNK - 1) / CHUNK;
1304    return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64;
1305}
1306
1307void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step,
1308                          int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) {
1309    if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step ||
1310        !pools.page_table) {
1311        std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n");
1312        std::exit(1);
1313    }
1314    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1315                        : (pools.k_q != nullptr ? 1 : 0));
1316    if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4)
1317                     : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale)
1318                                                                     : (!pools.k_pool || !pools.v_pool)))) {
1319        std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n");
1320        std::exit(1);
1321    }
1322    if(qsa_chunk_down_supported(cap, 1, s, stream)&&kv_mode==1){
1323        launch_qsa_chunk_down(1,q,pools,ids,step,cap,s,scratch,attn,1,stream);return;
1324    }
1325    const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK);
1326    float* part_acc = scratch;
1327    float* part_m = scratch + (size_t) n_chunks * s.n_head * HD;
1328    float* part_l = part_m + (size_t) n_chunks * s.n_head;
1329    const float scale = 1.0f / sqrtf((float) HD);
1330    const dpct::dim3 grid((unsigned)n_chunks, (unsigned)s.n_head_kv);
1331    dpct::queue_ptr st = strata::q_of(stream);
1332    if (kv_mode == 3)
1333    {
1334        auto exp_props = sycl::ext::oneapi::experimental::properties{
1335            sycl::ext::oneapi::experimental::use_root_sync};
1336        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1337
1338        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_f262e6,
1339                                          dpct_kernel_scalar<3>>>(
1340            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1341                              sycl::range(1, 1, THREADS)),
1342            exp_props,
1343            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1344                attn_chunk_kernel<3>(q, pools, ids, step, (int)s.n_head_kv,
1345                                     (int)s.page_size, scale, part_acc, part_m,
1346                                     part_l, n_chunks, 0, 0);
1347            });
1348    } else if (kv_mode == 2)
1349    {
1350        auto exp_props = sycl::ext::oneapi::experimental::properties{
1351            sycl::ext::oneapi::experimental::use_root_sync};
1352        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1353
1354        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_4fd923,
1355                                          dpct_kernel_scalar<2>>>(
1356            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1357                              sycl::range(1, 1, THREADS)),
1358            exp_props,
1359            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1360                attn_chunk_kernel<2>(q, pools, ids, step, (int)s.n_head_kv,
1361                                     (int)s.page_size, scale, part_acc, part_m,
1362                                     part_l, n_chunks, 0, 0);
1363            });
1364    } else if (kv_mode == 1)
1365    {
1366        auto exp_props = sycl::ext::oneapi::experimental::properties{
1367            sycl::ext::oneapi::experimental::use_root_sync};
1368        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1369
1370        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_f6855e,
1371                                          dpct_kernel_scalar<1>>>(
1372            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1373                              sycl::range(1, 1, THREADS)),
1374            exp_props,
1375            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1376                attn_chunk_kernel<1>(q, pools, ids, step, (int)s.n_head_kv,
1377                                     (int)s.page_size, scale, part_acc, part_m,
1378                                     part_l, n_chunks, 0, 0);
1379            });
1380    } else {
1381        auto exp_props = sycl::ext::oneapi::experimental::properties{
1382            sycl::ext::oneapi::experimental::use_root_sync};
1383        dpct::has_capability_or_fail(st->get_device(), {sycl::aspect::fp16});
1384
1385        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_chunk_kernel_7c8e09,
1386                                          dpct_kernel_scalar<0>>>(
1387            sycl::nd_range<3>(grid * sycl::range(1, 1, THREADS),
1388                              sycl::range(1, 1, THREADS)),
1389            exp_props,
1390            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1391                attn_chunk_kernel<0>(q, pools, ids, step, (int)s.n_head_kv,
1392                                     (int)s.page_size, scale, part_acc, part_m,
1393                                     part_l, n_chunks, 0, 0);
1394            });
1395    }
1396    {
1397        auto exp_props = sycl::ext::oneapi::experimental::properties{
1398            sycl::ext::oneapi::experimental::use_root_sync};
1399
1400        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class attn_merge_kernel_c055e7>>(
1401            sycl::nd_range<3>(sycl::range(1, 1, (unsigned)s.n_head) *
1402                                  sycl::range(1, 1, HD),
1403                              sycl::range(1, 1, HD)),
1404            exp_props, [=](sycl::nd_item<3> item_ct1) {
1405                attn_merge_kernel(part_acc, part_m, part_l, n_chunks, attn, 0);
1406            });
1407    }
1408    /*
1409    DPCT1010: SYCL uses exceptions to report errors and does not use the
1410    error codes. The cudaGetLastError function call was replaced with 0. You
1411    need to rewrite this code.
1412    */
1413    const dpct::err0 e = 0;
1414}
1415
1416// SYCL port, prompt path only (prefill.cpp; decode and the draft layer keep qsa_decode_attn_batch): the chunk
1417// attention with the per-cell score kernel above, 128-cell chunks in the same scratch as the warp kernel (its stride
1418// is the 64-cell layout's, so it fits). FP32, another summation order than the warp kernel: not bitwise.
1419void qsa_prompt_attn_percell(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
1420                             int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) {
1421    if (n_q <= 0) return;
1422    const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3
1423                        : (pools.k_q != nullptr ? 1 : 0));
1424    const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s);
1425    const float scale = 1.0f / sqrtf((float) HD);
1426    dpct::queue_ptr st = strata::q_of(stream);
1427    const int nc = (int) ((cap + PC_CHUNK - 1) / PC_CHUNK);
1428    float* pa = scratch;
1429    float* pm = scratch + (size_t) nc * s.n_head * HD;
1430    float* pl = pm + (size_t) nc * s.n_head;
1431    if (kv_mode == 3) launch_percell<3>(st, q, pools, ids, steps, cap, s, pa, pm, pl, nc, stride, n_q, scale);
1432    else if (kv_mode == 2) launch_percell<2>(st, q, pools, ids, steps, cap, s, pa, pm, pl, nc, stride, n_q, scale);
1433    else if (kv_mode == 1) launch_percell<1>(st, q, pools, ids, steps, cap, s, pa, pm, pl, nc, stride, n_q, scale);
1434    else launch_percell<0>(st, q, pools, ids, steps, cap, s, pa, pm, pl, nc, stride, n_q, scale);
1435    st->parallel_for(sycl::nd_range<3>(sycl::range<3>(1, (size_t) n_q, (size_t) s.n_head) * sycl::range<3>(1, 1, HD),
1436                                       sycl::range<3>(1, 1, HD)),
1437                     [=](sycl::nd_item<3>) { attn_merge_kernel(pa, pm, pl, nc, attn, stride); });
1438}
1439
1440}  // namespace strata::kernels
1441
1442#include <stdexcept>
1443
1444namespace strata::kernels {
1445namespace {
1446__dpct_inline__ float lane0_sum(float value){
1447    auto group=sycl::ext::oneapi::this_work_item::get_sub_group();
1448#pragma unroll
1449    for(int offset=16;offset>0;offset>>=1)value+=sycl::shift_group_left(group,value,offset);
1450    return value;
1451}
1452template <int KV_MODE>
1453/*
1454DPCT1110: The total declared local variable size in device function
1455chunk_down_kernel exceeds 128 bytes and may cause high register pressure.
1456Consult with your hardware vendor to find the total register size available and
1457adjust the code, or use smaller sub-group size to avoid high register pressure.
1458*/
1459__dpct_inline__ void
1460chunk_down_kernel(const float *__restrict__ q, QsaAttnPools p,
1461                  const int32_t *__restrict__ ids,
1462                  const int32_t *__restrict__ step, int n_kv_heads,
1463                  int page_size, float scale, float *__restrict__ part_acc,
1464                  float *__restrict__ part_m, float *__restrict__ part_l,
1465                  int n_chunks, int cap = 0, long long scratch_stride = 0) {
1466    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
1467    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1468    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
1469    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
1470    step += (size_t)item_ct1.get_group(0) * kStepCount;
1471    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1472    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1473    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1474    auto &sq =
1475        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
1476            sycl::ext::oneapi::this_work_item::get_work_group<
1477                3>()); // 12 KB: this KV head's query heads
1478    auto &sp =
1479        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][CHUNK]>(
1480            sycl::ext::oneapi::this_work_item::get_work_group<
1481                3>()); // scores, then probabilities
1482    auto &srow =
1483        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
1484            sycl::ext::oneapi::this_work_item::get_work_group<
1485                3>()); // pool row of each cell (page, kv head, slot)
1486    /*
1487    DPCT1098: The '*' expression is used instead of the __ldg call. These
1488    two expressions do not provide the exact same functionality. Check the
1489    generated code for potential precision and/or performance issues.
1490    */
1491    const int n_ids = *(step + kStepWidth);
1492    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
1493    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1494    const int c0 = chunk * CHUNK;
1495    const int n_here = sycl::min(CHUNK, n_ids - c0);
1496    const int slot = kvh * n_chunks + chunk;
1497    if (n_here <= 0) {
1498        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
1499        return;
1500    }
1501#pragma unroll
1502    for (int i = t; i < G * HD; i += THREADS)
1503        sq[i / HD][i % HD] = q[(size_t)(kvh * G) * HD + i];
1504    if (t < CHUNK) {
1505        long long r = -1;
1506        if (t < n_here) {
1507            const int cell = ids[c0 + t];
1508            const long long page = (long long) p.page_table[cell / page_size];
1509            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
1510            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
1511            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1512        }
1513        srow[t] = r;
1514    }
1515    /*
1516    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1517    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1518    performance if there is no access to global memory.
1519    */
1520    item_ct1.barrier();
1521    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
1522    for (int c = warp; c < CHUNK; c += WARPS) {
1523        if (c >= n_here || srow[c] < 0) {
1524            if (lane < G) sp[lane][c] = -FLT_MAX;
1525            continue;
1526        }
1527        float k8[8];
1528        load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
1529#pragma unroll
1530        for (int h = 0; h < G; ++h) {
1531            const sycl::float4 qa =
1532                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8]);
1533            const sycl::float4 qb =
1534                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8 + 4]);
1535            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
1536                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
1537                      k8[6] * qb.z() + k8[7] * qb.w();
1538            s = lane0_sum(s);
1539            if (lane == 0) sp[h][c] = s * scale;
1540        }
1541    }
1542    /*
1543    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1544    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1545    performance if there is no access to global memory.
1546    */
1547    item_ct1.barrier();
1548    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
1549    for (int h = warp; h < G; h += WARPS) {
1550        const float a = sp[h][lane], b = sp[h][lane + 32];
1551        const float m = warp_max(sycl::fmax(a, b));
1552        const float ea = (lane < n_here && srow[lane] >= 0)
1553                             ? sycl::native::exp(a - m)
1554                             : 0.0f;
1555        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
1556                             ? sycl::native::exp(b - m)
1557                             : 0.0f;
1558        sp[h][lane] = ea;
1559        sp[h][lane + 32] = eb;
1560        const float l = lane0_sum(ea + eb);
1561        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
1562    }
1563    /*
1564    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1565    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1566    performance if there is no access to global memory.
1567    */
1568    item_ct1.barrier();
1569    // values: thread t owns dimension t for all 12 heads.
1570    float acc[G];
1571#pragma unroll
1572    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
1573    for (int c = 0; c < n_here; ++c) {
1574        if (srow[c] < 0) continue;   // masked above, weight 0
1575        float v;
1576        if constexpr (KV_MODE == 0) {
1577            v = sycl::vec<sycl::half, 1>(
1578                    sycl::bit_cast<sycl::half, unsigned short>(
1579                        p.v_pool[srow[c] * HD + t]))
1580                    .convert<float, sycl::rounding_mode::automatic>()[0];
1581        } else if constexpr (KV_MODE == 1) {
1582            const float sc =
1583                sycl::vec<sycl::half, 1>(
1584                    sycl::bit_cast<sycl::half, unsigned short>(
1585                        p.v_scale[srow[c] * (HD / KV_Q8_GROUP) +
1586                                  t / KV_Q8_GROUP]))
1587                    .convert<float, sycl::rounding_mode::automatic>()[0];
1588            v = (float) p.v_q[srow[c] * HD + t] * sc;
1589        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
1590            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
1591            const int b = t / QK4_0;
1592            const int rem = t % QK4_0;
1593            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + srow[c] * bytes_per_head) + b;
1594            const float d =
1595                sycl::vec<sycl::half, 1>(
1596                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
1597                    .convert<float, sycl::rounding_mode::automatic>()[0];
1598            const int j = rem < 16 ? rem : (rem - 16);
1599            const uint8_t byte = blk->qs[j];
1600            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
1601            v = (float) nibble * d;
1602        }
1603#pragma unroll
1604        for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c], v, acc[h]);
1605    }
1606#pragma unroll
1607    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
1608}
1609
1610
1611class QsaChunkDown;
1612}
1613namespace {
1614__dpct_inline__ void private_load8_vector_codes(const QsaAttnPools& p,bool value,long long row,int d0,float* out){
1615    const int8_t* codes=(value?p.v_q:p.k_q)+row*HD+d0;
1616    const uint16_t sbits=(value?p.v_scale:p.k_scale)[row*(HD/KV_Q8_GROUP)+d0/KV_Q8_GROUP];
1617    const float sc=sycl::vec<sycl::half,1>(sycl::bit_cast<sycl::half,unsigned short>(sbits)).convert<float,sycl::rounding_mode::automatic>()[0];
1618    const auto raw=*reinterpret_cast<const sycl::vec<int8_t,8>*>(codes);
1619    const auto converted=raw.convert<float,sycl::rounding_mode::automatic>();
1620#pragma unroll
1621    for(int j=0;j<8;++j)out[j]=converted[j]*sc;
1622}
1623template <int KV_MODE>
1624/*
1625DPCT1110: The total declared local variable size in device function
1626chunk_down_kernel exceeds 128 bytes and may cause high register pressure.
1627Consult with your hardware vendor to find the total register size available and
1628adjust the code, or use smaller sub-group size to avoid high register pressure.
1629*/
1630__dpct_inline__ void
1631chunk_vector_codes_kernel(const float *__restrict__ q, QsaAttnPools p,
1632                  const int32_t *__restrict__ ids,
1633                  const int32_t *__restrict__ step, int n_kv_heads,
1634                  int page_size, float scale, float *__restrict__ part_acc,
1635                  float *__restrict__ part_m, float *__restrict__ part_l,
1636                  int n_chunks, int cap = 0, long long scratch_stride = 0) {
1637    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
1638    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1639    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
1640    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
1641    step += (size_t)item_ct1.get_group(0) * kStepCount;
1642    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1643    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1644    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1645    auto &sq =
1646        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
1647            sycl::ext::oneapi::this_work_item::get_work_group<
1648                3>()); // 12 KB: this KV head's query heads
1649    auto &sp =
1650        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][CHUNK]>(
1651            sycl::ext::oneapi::this_work_item::get_work_group<
1652                3>()); // scores, then probabilities
1653    auto &srow =
1654        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
1655            sycl::ext::oneapi::this_work_item::get_work_group<
1656                3>()); // pool row of each cell (page, kv head, slot)
1657    /*
1658    DPCT1098: The '*' expression is used instead of the __ldg call. These
1659    two expressions do not provide the exact same functionality. Check the
1660    generated code for potential precision and/or performance issues.
1661    */
1662    const int n_ids = *(step + kStepWidth);
1663    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
1664    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1665    const int c0 = chunk * CHUNK;
1666    const int n_here = sycl::min(CHUNK, n_ids - c0);
1667    const int slot = kvh * n_chunks + chunk;
1668    if (n_here <= 0) {
1669        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
1670        return;
1671    }
1672#pragma unroll
1673    for (int i = t; i < G * HD; i += THREADS)
1674        sq[i / HD][i % HD] = q[(size_t)(kvh * G) * HD + i];
1675    if (t < CHUNK) {
1676        long long r = -1;
1677        if (t < n_here) {
1678            const int cell = ids[c0 + t];
1679            const long long page = (long long) p.page_table[cell / page_size];
1680            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
1681            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
1682            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1683        }
1684        srow[t] = r;
1685    }
1686    /*
1687    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1688    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1689    performance if there is no access to global memory.
1690    */
1691    item_ct1.barrier();
1692    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
1693    for (int c = warp; c < CHUNK; c += WARPS) {
1694        if (c >= n_here || srow[c] < 0) {
1695            if (lane < G) sp[lane][c] = -FLT_MAX;
1696            continue;
1697        }
1698        float k8[8];
1699        private_load8_vector_codes(p, false, srow[c], lane * 8, k8);
1700#pragma unroll
1701        for (int h = 0; h < G; ++h) {
1702            const sycl::float4 qa =
1703                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8]);
1704            const sycl::float4 qb =
1705                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 8 + 4]);
1706            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
1707                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
1708                      k8[6] * qb.z() + k8[7] * qb.w();
1709            s = lane0_sum(s);
1710            if (lane == 0) sp[h][c] = s * scale;
1711        }
1712    }
1713    /*
1714    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1715    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1716    performance if there is no access to global memory.
1717    */
1718    item_ct1.barrier();
1719    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
1720    for (int h = warp; h < G; h += WARPS) {
1721        const float a = sp[h][lane], b = sp[h][lane + 32];
1722        const float m = warp_max(sycl::fmax(a, b));
1723        const float ea = (lane < n_here && srow[lane] >= 0)
1724                             ? sycl::native::exp(a - m)
1725                             : 0.0f;
1726        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
1727                             ? sycl::native::exp(b - m)
1728                             : 0.0f;
1729        sp[h][lane] = ea;
1730        sp[h][lane + 32] = eb;
1731        const float l = lane0_sum(ea + eb);
1732        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
1733    }
1734    /*
1735    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1736    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1737    performance if there is no access to global memory.
1738    */
1739    item_ct1.barrier();
1740    // values: thread t owns dimension t for all 12 heads.
1741    float acc[G];
1742#pragma unroll
1743    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
1744    for (int c0 = 0; c0 < n_here; c0 += 8) {
1745        long long rows[8]; bool full = c0 + 8 <= n_here;
1746#pragma unroll
1747        for (int j = 0; j < 8; ++j) {
1748            rows[j] = c0 + j < n_here ? srow[c0 + j] : -1;
1749            full = full && rows[j] >= 0;
1750        }
1751        if (full) {
1752            float values[8];
1753#pragma unroll
1754            for (int j = 0; j < 8; ++j) {
1755                const long long row = rows[j];
1756        float v;
1757        if constexpr (KV_MODE == 0) {
1758            v = sycl::vec<sycl::half, 1>(
1759                    sycl::bit_cast<sycl::half, unsigned short>(
1760                        p.v_pool[row * HD + t]))
1761                    .convert<float, sycl::rounding_mode::automatic>()[0];
1762        } else if constexpr (KV_MODE == 1) {
1763            const float sc =
1764                sycl::vec<sycl::half, 1>(
1765                    sycl::bit_cast<sycl::half, unsigned short>(
1766                        p.v_scale[row * (HD / KV_Q8_GROUP) +
1767                                  t / KV_Q8_GROUP]))
1768                    .convert<float, sycl::rounding_mode::automatic>()[0];
1769            v = (float) p.v_q[row * HD + t] * sc;
1770        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
1771            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
1772            const int b = t / QK4_0;
1773            const int rem = t % QK4_0;
1774            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
1775            const float d =
1776                sycl::vec<sycl::half, 1>(
1777                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
1778                    .convert<float, sycl::rounding_mode::automatic>()[0];
1779            const int j = rem < 16 ? rem : (rem - 16);
1780            const uint8_t byte = blk->qs[j];
1781            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
1782            v = (float) nibble * d;
1783        }
1784                values[j] = v;
1785            }
1786#pragma unroll
1787        for (int h = 0; h < G; ++h) {
1788            const sycl::float4 p0 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0]);
1789            const sycl::float4 p1 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0 + 4]);
1790            acc[h] = sycl::fma(p0[0], values[0], acc[h]);
1791            acc[h] = sycl::fma(p0[1], values[1], acc[h]);
1792            acc[h] = sycl::fma(p0[2], values[2], acc[h]);
1793            acc[h] = sycl::fma(p0[3], values[3], acc[h]);
1794            acc[h] = sycl::fma(p1[0], values[4], acc[h]);
1795            acc[h] = sycl::fma(p1[1], values[5], acc[h]);
1796            acc[h] = sycl::fma(p1[2], values[6], acc[h]);
1797            acc[h] = sycl::fma(p1[3], values[7], acc[h]);
1798        }
1799
1800        } else {
1801#pragma unroll
1802            for (int j = 0; j < 8; ++j) {
1803                const long long row = rows[j];
1804                if (row < 0) continue;
1805        float v;
1806        if constexpr (KV_MODE == 0) {
1807            v = sycl::vec<sycl::half, 1>(
1808                    sycl::bit_cast<sycl::half, unsigned short>(
1809                        p.v_pool[row * HD + t]))
1810                    .convert<float, sycl::rounding_mode::automatic>()[0];
1811        } else if constexpr (KV_MODE == 1) {
1812            const float sc =
1813                sycl::vec<sycl::half, 1>(
1814                    sycl::bit_cast<sycl::half, unsigned short>(
1815                        p.v_scale[row * (HD / KV_Q8_GROUP) +
1816                                  t / KV_Q8_GROUP]))
1817                    .convert<float, sycl::rounding_mode::automatic>()[0];
1818            v = (float) p.v_q[row * HD + t] * sc;
1819        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
1820            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
1821            const int b = t / QK4_0;
1822            const int rem = t % QK4_0;
1823            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
1824            const float d =
1825                sycl::vec<sycl::half, 1>(
1826                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
1827                    .convert<float, sycl::rounding_mode::automatic>()[0];
1828            const int j = rem < 16 ? rem : (rem - 16);
1829            const uint8_t byte = blk->qs[j];
1830            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
1831            v = (float) nibble * d;
1832        }
1833#pragma unroll
1834                for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c0 + j], v, acc[h]);
1835            }
1836        }
1837    }
1838
1839#pragma unroll
1840    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
1841}
1842
1843template <int KV_MODE>
1844/*
1845DPCT1110: The total declared local variable size in device function
1846chunk_down_kernel exceeds 128 bytes and may cause high register pressure.
1847Consult with your hardware vendor to find the total register size available and
1848adjust the code, or use smaller sub-group size to avoid high register pressure.
1849*/
1850__dpct_inline__ void
1851b60_qsa_float4_kernel(const float *__restrict__ q, QsaAttnPools p,
1852                  const int32_t *__restrict__ ids,
1853                  const int32_t *__restrict__ step, int n_kv_heads,
1854                  int page_size, float scale, float *__restrict__ part_acc,
1855                  float *__restrict__ part_m, float *__restrict__ part_l,
1856                  int n_chunks, int cap = 0, long long scratch_stride = 0) {
1857    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
1858    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1859    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
1860    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
1861    step += (size_t)item_ct1.get_group(0) * kStepCount;
1862    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1863    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1864    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
1865    auto &sq =
1866        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
1867            sycl::ext::oneapi::this_work_item::get_work_group<
1868                3>()); // 12 KB: this KV head's query heads
1869    auto &sp =
1870        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][CHUNK]>(
1871            sycl::ext::oneapi::this_work_item::get_work_group<
1872                3>()); // scores, then probabilities
1873    auto &srow =
1874        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
1875            sycl::ext::oneapi::this_work_item::get_work_group<
1876                3>()); // pool row of each cell (page, kv head, slot)
1877    /*
1878    DPCT1098: The '*' expression is used instead of the __ldg call. These
1879    two expressions do not provide the exact same functionality. Check the
1880    generated code for potential precision and/or performance issues.
1881    */
1882    const int n_ids = *(step + kStepWidth);
1883    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
1884    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1885    const int c0 = chunk * CHUNK;
1886    const int n_here = sycl::min(CHUNK, n_ids - c0);
1887    const int slot = kvh * n_chunks + chunk;
1888    if (n_here <= 0) {
1889        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
1890        return;
1891    }
1892#pragma unroll
1893    for (int i = t; i < G * HD; i += THREADS)
1894        sq[i / HD][i % HD] = q[(size_t)(kvh * G + i / HD) * HD +
1895            ((i % HD) % 128 / 4) * 8 + ((i % HD) / 128) * 4 + (i % 4)];
1896    if (t < CHUNK) {
1897        long long r = -1;
1898        if (t < n_here) {
1899            const int cell = ids[c0 + t];
1900            const long long page = (long long) p.page_table[cell / page_size];
1901            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
1902            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
1903            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
1904        }
1905        srow[t] = r;
1906    }
1907    /*
1908    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1909    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1910    performance if there is no access to global memory.
1911    */
1912    item_ct1.barrier();
1913    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
1914    for (int c = warp; c < CHUNK; c += WARPS) {
1915        if (c >= n_here || srow[c] < 0) {
1916            if (lane < G) sp[lane][c] = -FLT_MAX;
1917            continue;
1918        }
1919        float k8[8];
1920        private_load8_vector_codes(p, false, srow[c], lane * 8, k8);
1921#pragma unroll
1922        for (int h = 0; h < G; ++h) {
1923            const sycl::float4 qa =
1924                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 4]);
1925            const sycl::float4 qb =
1926                *reinterpret_cast<const sycl::float4 *>(&sq[h][128 + lane * 4]);
1927            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
1928                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
1929                      k8[6] * qb.z() + k8[7] * qb.w();
1930            s = lane0_sum(s);
1931            if (lane == 0) sp[h][c] = s * scale;
1932        }
1933    }
1934    /*
1935    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1936    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1937    performance if there is no access to global memory.
1938    */
1939    item_ct1.barrier();
1940    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
1941    for (int h = warp; h < G; h += WARPS) {
1942        const float a = sp[h][lane], b = sp[h][lane + 32];
1943        const float m = warp_max(sycl::fmax(a, b));
1944        const float ea = (lane < n_here && srow[lane] >= 0)
1945                             ? sycl::native::exp(a - m)
1946                             : 0.0f;
1947        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
1948                             ? sycl::native::exp(b - m)
1949                             : 0.0f;
1950        sp[h][lane] = ea;
1951        sp[h][lane + 32] = eb;
1952        const float l = lane0_sum(ea + eb);
1953        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
1954    }
1955    /*
1956    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1957    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1958    performance if there is no access to global memory.
1959    */
1960    item_ct1.barrier();
1961    // values: thread t owns dimension t for all 12 heads.
1962    float acc[G];
1963#pragma unroll
1964    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
1965    for (int c0 = 0; c0 < n_here; c0 += 8) {
1966        long long rows[8]; bool full = c0 + 8 <= n_here;
1967#pragma unroll
1968        for (int j = 0; j < 8; ++j) {
1969            rows[j] = c0 + j < n_here ? srow[c0 + j] : -1;
1970            full = full && rows[j] >= 0;
1971        }
1972        if (full) {
1973            float values[8];
1974#pragma unroll
1975            for (int j = 0; j < 8; ++j) {
1976                const long long row = rows[j];
1977        float v;
1978        if constexpr (KV_MODE == 0) {
1979            v = sycl::vec<sycl::half, 1>(
1980                    sycl::bit_cast<sycl::half, unsigned short>(
1981                        p.v_pool[row * HD + t]))
1982                    .convert<float, sycl::rounding_mode::automatic>()[0];
1983        } else if constexpr (KV_MODE == 1) {
1984            const float sc =
1985                sycl::vec<sycl::half, 1>(
1986                    sycl::bit_cast<sycl::half, unsigned short>(
1987                        p.v_scale[row * (HD / KV_Q8_GROUP) +
1988                                  t / KV_Q8_GROUP]))
1989                    .convert<float, sycl::rounding_mode::automatic>()[0];
1990            v = (float) p.v_q[row * HD + t] * sc;
1991        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
1992            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
1993            const int b = t / QK4_0;
1994            const int rem = t % QK4_0;
1995            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
1996            const float d =
1997                sycl::vec<sycl::half, 1>(
1998                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
1999                    .convert<float, sycl::rounding_mode::automatic>()[0];
2000            const int j = rem < 16 ? rem : (rem - 16);
2001            const uint8_t byte = blk->qs[j];
2002            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2003            v = (float) nibble * d;
2004        }
2005                values[j] = v;
2006            }
2007#pragma unroll
2008        for (int h = 0; h < G; ++h) {
2009            const sycl::float4 p0 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0]);
2010            const sycl::float4 p1 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0 + 4]);
2011            acc[h] = sycl::fma(p0[0], values[0], acc[h]);
2012            acc[h] = sycl::fma(p0[1], values[1], acc[h]);
2013            acc[h] = sycl::fma(p0[2], values[2], acc[h]);
2014            acc[h] = sycl::fma(p0[3], values[3], acc[h]);
2015            acc[h] = sycl::fma(p1[0], values[4], acc[h]);
2016            acc[h] = sycl::fma(p1[1], values[5], acc[h]);
2017            acc[h] = sycl::fma(p1[2], values[6], acc[h]);
2018            acc[h] = sycl::fma(p1[3], values[7], acc[h]);
2019        }
2020
2021        } else {
2022#pragma unroll
2023            for (int j = 0; j < 8; ++j) {
2024                const long long row = rows[j];
2025                if (row < 0) continue;
2026        float v;
2027        if constexpr (KV_MODE == 0) {
2028            v = sycl::vec<sycl::half, 1>(
2029                    sycl::bit_cast<sycl::half, unsigned short>(
2030                        p.v_pool[row * HD + t]))
2031                    .convert<float, sycl::rounding_mode::automatic>()[0];
2032        } else if constexpr (KV_MODE == 1) {
2033            const float sc =
2034                sycl::vec<sycl::half, 1>(
2035                    sycl::bit_cast<sycl::half, unsigned short>(
2036                        p.v_scale[row * (HD / KV_Q8_GROUP) +
2037                                  t / KV_Q8_GROUP]))
2038                    .convert<float, sycl::rounding_mode::automatic>()[0];
2039            v = (float) p.v_q[row * HD + t] * sc;
2040        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
2041            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
2042            const int b = t / QK4_0;
2043            const int rem = t % QK4_0;
2044            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
2045            const float d =
2046                sycl::vec<sycl::half, 1>(
2047                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
2048                    .convert<float, sycl::rounding_mode::automatic>()[0];
2049            const int j = rem < 16 ? rem : (rem - 16);
2050            const uint8_t byte = blk->qs[j];
2051            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2052            v = (float) nibble * d;
2053        }
2054#pragma unroll
2055                for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c0 + j], v, acc[h]);
2056            }
2057        }
2058    }
2059
2060#pragma unroll
2061    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
2062}
2063
2064template <int KV_MODE>
2065/*
2066DPCT1110: The total declared local variable size in device function
2067chunk_down_kernel exceeds 128 bytes and may cause high register pressure.
2068Consult with your hardware vendor to find the total register size available and
2069adjust the code, or use smaller sub-group size to avoid high register pressure.
2070*/
2071__dpct_inline__ void
2072b60_qsa_head6_kernel(const float *__restrict__ q, QsaAttnPools p,
2073                  const int32_t *__restrict__ ids,
2074                  const int32_t *__restrict__ step, int n_kv_heads,
2075                  int page_size, float scale, float *__restrict__ part_acc,
2076                  float *__restrict__ part_m, float *__restrict__ part_l,
2077                  int n_chunks, int cap = 0, long long scratch_stride = 0) {
2078    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
2079    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2080    constexpr int H=6;const int headbase=int(item_ct1.get_group(2)%2)*H;
2081    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
2082    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
2083    step += (size_t)item_ct1.get_group(0) * kStepCount;
2084    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2085    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2086    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2087    auto &sq =
2088        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[H][HD]>(
2089            sycl::ext::oneapi::this_work_item::get_work_group<
2090                3>()); // 12 KB: this KV head's query heads
2091    auto &sp =
2092        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[H][CHUNK]>(
2093            sycl::ext::oneapi::this_work_item::get_work_group<
2094                3>()); // scores, then probabilities
2095    auto &srow =
2096        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
2097            sycl::ext::oneapi::this_work_item::get_work_group<
2098                3>()); // pool row of each cell (page, kv head, slot)
2099    /*
2100    DPCT1098: The '*' expression is used instead of the __ldg call. These
2101    two expressions do not provide the exact same functionality. Check the
2102    generated code for potential precision and/or performance issues.
2103    */
2104    const int n_ids = *(step + kStepWidth);
2105    const int chunk = item_ct1.get_group(2)/2, kvh = item_ct1.get_group(1);
2106    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
2107    const int c0 = chunk * CHUNK;
2108    const int n_here = sycl::min(CHUNK, n_ids - c0);
2109    const int slot = kvh * n_chunks + chunk;
2110    if (n_here <= 0) {
2111        if (t < H) { part_m[slot * G + headbase + t] = -FLT_MAX; part_l[slot * G + headbase + t] = 0.0f; }
2112        return;
2113    }
2114#pragma unroll
2115    for (int i = t; i < H * HD; i += THREADS)
2116        sq[i / HD][i % HD] = q[(size_t)(kvh * G + headbase + i / HD) * HD +
2117            ((i % HD) % 128 / 4) * 8 + ((i % HD) / 128) * 4 + (i % 4)];
2118    if (t < CHUNK) {
2119        long long r = -1;
2120        if (t < n_here) {
2121            const int cell = ids[c0 + t];
2122            const long long page = (long long) p.page_table[cell / page_size];
2123            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
2124            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
2125            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
2126        }
2127        srow[t] = r;
2128    }
2129    /*
2130    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2131    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2132    performance if there is no access to global memory.
2133    */
2134    item_ct1.barrier();
2135    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
2136    for (int c = warp; c < CHUNK; c += WARPS) {
2137        if (c >= n_here || srow[c] < 0) {
2138            if (lane < H) sp[lane][c] = -FLT_MAX;
2139            continue;
2140        }
2141        float k8[8];
2142        private_load8_vector_codes(p, false, srow[c], lane * 8, k8);
2143#pragma unroll
2144        for (int h = 0; h < H; ++h) {
2145            const sycl::float4 qa =
2146                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 4]);
2147            const sycl::float4 qb =
2148                *reinterpret_cast<const sycl::float4 *>(&sq[h][128 + lane * 4]);
2149            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
2150                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
2151                      k8[6] * qb.z() + k8[7] * qb.w();
2152            s = lane0_sum(s);
2153            if (lane == 0) sp[h][c] = s * scale;
2154        }
2155    }
2156    /*
2157    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2158    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2159    performance if there is no access to global memory.
2160    */
2161    item_ct1.barrier();
2162    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
2163    for (int h = warp; h < H; h += WARPS) {
2164        const float a = sp[h][lane], b = sp[h][lane + 32];
2165        const float m = warp_max(sycl::fmax(a, b));
2166        const float ea = (lane < n_here && srow[lane] >= 0)
2167                             ? sycl::native::exp(a - m)
2168                             : 0.0f;
2169        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
2170                             ? sycl::native::exp(b - m)
2171                             : 0.0f;
2172        sp[h][lane] = ea;
2173        sp[h][lane + 32] = eb;
2174        const float l = lane0_sum(ea + eb);
2175        if (lane == 0) { part_m[slot * G + headbase + h] = m; part_l[slot * G + headbase + h] = l; }
2176    }
2177    /*
2178    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2179    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2180    performance if there is no access to global memory.
2181    */
2182    item_ct1.barrier();
2183    // values: thread t owns dimension t for all 12 heads.
2184    float acc[H];
2185#pragma unroll
2186    for (int h = 0; h < H; ++h) acc[h] = 0.0f;
2187    for (int c0 = 0; c0 < n_here; c0 += 8) {
2188        long long rows[8]; bool full = c0 + 8 <= n_here;
2189#pragma unroll
2190        for (int j = 0; j < 8; ++j) {
2191            rows[j] = c0 + j < n_here ? srow[c0 + j] : -1;
2192            full = full && rows[j] >= 0;
2193        }
2194        if (full) {
2195            float values[8];
2196#pragma unroll
2197            for (int j = 0; j < 8; ++j) {
2198                const long long row = rows[j];
2199        float v;
2200        if constexpr (KV_MODE == 0) {
2201            v = sycl::vec<sycl::half, 1>(
2202                    sycl::bit_cast<sycl::half, unsigned short>(
2203                        p.v_pool[row * HD + t]))
2204                    .convert<float, sycl::rounding_mode::automatic>()[0];
2205        } else if constexpr (KV_MODE == 1) {
2206            const float sc =
2207                sycl::vec<sycl::half, 1>(
2208                    sycl::bit_cast<sycl::half, unsigned short>(
2209                        p.v_scale[row * (HD / KV_Q8_GROUP) +
2210                                  t / KV_Q8_GROUP]))
2211                    .convert<float, sycl::rounding_mode::automatic>()[0];
2212            v = (float) p.v_q[row * HD + t] * sc;
2213        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
2214            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
2215            const int b = t / QK4_0;
2216            const int rem = t % QK4_0;
2217            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
2218            const float d =
2219                sycl::vec<sycl::half, 1>(
2220                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
2221                    .convert<float, sycl::rounding_mode::automatic>()[0];
2222            const int j = rem < 16 ? rem : (rem - 16);
2223            const uint8_t byte = blk->qs[j];
2224            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2225            v = (float) nibble * d;
2226        }
2227                values[j] = v;
2228            }
2229#pragma unroll
2230        for (int h = 0; h < H; ++h) {
2231            const sycl::float4 p0 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0]);
2232            const sycl::float4 p1 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0 + 4]);
2233            acc[h] = sycl::fma(p0[0], values[0], acc[h]);
2234            acc[h] = sycl::fma(p0[1], values[1], acc[h]);
2235            acc[h] = sycl::fma(p0[2], values[2], acc[h]);
2236            acc[h] = sycl::fma(p0[3], values[3], acc[h]);
2237            acc[h] = sycl::fma(p1[0], values[4], acc[h]);
2238            acc[h] = sycl::fma(p1[1], values[5], acc[h]);
2239            acc[h] = sycl::fma(p1[2], values[6], acc[h]);
2240            acc[h] = sycl::fma(p1[3], values[7], acc[h]);
2241        }
2242
2243        } else {
2244#pragma unroll
2245            for (int j = 0; j < 8; ++j) {
2246                const long long row = rows[j];
2247                if (row < 0) continue;
2248        float v;
2249        if constexpr (KV_MODE == 0) {
2250            v = sycl::vec<sycl::half, 1>(
2251                    sycl::bit_cast<sycl::half, unsigned short>(
2252                        p.v_pool[row * HD + t]))
2253                    .convert<float, sycl::rounding_mode::automatic>()[0];
2254        } else if constexpr (KV_MODE == 1) {
2255            const float sc =
2256                sycl::vec<sycl::half, 1>(
2257                    sycl::bit_cast<sycl::half, unsigned short>(
2258                        p.v_scale[row * (HD / KV_Q8_GROUP) +
2259                                  t / KV_Q8_GROUP]))
2260                    .convert<float, sycl::rounding_mode::automatic>()[0];
2261            v = (float) p.v_q[row * HD + t] * sc;
2262        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
2263            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
2264            const int b = t / QK4_0;
2265            const int rem = t % QK4_0;
2266            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
2267            const float d =
2268                sycl::vec<sycl::half, 1>(
2269                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
2270                    .convert<float, sycl::rounding_mode::automatic>()[0];
2271            const int j = rem < 16 ? rem : (rem - 16);
2272            const uint8_t byte = blk->qs[j];
2273            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2274            v = (float) nibble * d;
2275        }
2276#pragma unroll
2277                for (int h = 0; h < H; ++h) acc[h] = sycl::fma(sp[h][c0 + j], v, acc[h]);
2278            }
2279        }
2280    }
2281
2282#pragma unroll
2283    for (int h = 0; h < H; ++h) part_acc[((size_t) slot * G + headbase + h) * HD + t] = acc[h];
2284}
2285
2286class B60QsaHead6;
2287template <int KV_MODE>
2288/*
2289DPCT1110: The total declared local variable size in device function
2290chunk_down_kernel exceeds 128 bytes and may cause high register pressure.
2291Consult with your hardware vendor to find the total register size available and
2292adjust the code, or use smaller sub-group size to avoid high register pressure.
2293*/
2294__dpct_inline__ void
2295b60_qsa_local_fence_kernel(const float *__restrict__ q, QsaAttnPools p,
2296                  const int32_t *__restrict__ ids,
2297                  const int32_t *__restrict__ step, int n_kv_heads,
2298                  int page_size, float scale, float *__restrict__ part_acc,
2299                  float *__restrict__ part_m, float *__restrict__ part_l,
2300                  int n_chunks, int cap = 0, long long scratch_stride = 0) {
2301    // batched form: query blockIdx.z, with its own q row, selection, step and scratch
2302    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2303    q += (size_t)item_ct1.get_group(0) * (size_t)(n_kv_heads * G) * HD;
2304    ids += (size_t)item_ct1.get_group(0) * (size_t)cap;
2305    step += (size_t)item_ct1.get_group(0) * kStepCount;
2306    part_acc += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2307    part_m += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2308    part_l += (size_t)item_ct1.get_group(0) * (size_t)scratch_stride;
2309    auto &sq =
2310        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][HD]>(
2311            sycl::ext::oneapi::this_work_item::get_work_group<
2312                3>()); // 12 KB: this KV head's query heads
2313    auto &sp =
2314        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[G][CHUNK]>(
2315            sycl::ext::oneapi::this_work_item::get_work_group<
2316                3>()); // scores, then probabilities
2317    auto &srow =
2318        *sycl::ext::oneapi::group_local_memory_for_overwrite<long long[CHUNK]>(
2319            sycl::ext::oneapi::this_work_item::get_work_group<
2320                3>()); // pool row of each cell (page, kv head, slot)
2321    /*
2322    DPCT1098: The '*' expression is used instead of the __ldg call. These
2323    two expressions do not provide the exact same functionality. Check the
2324    generated code for potential precision and/or performance issues.
2325    */
2326    const int n_ids = *(step + kStepWidth);
2327    const int chunk = item_ct1.get_group(2), kvh = item_ct1.get_group(1);
2328    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
2329    const int c0 = chunk * CHUNK;
2330    const int n_here = sycl::min(CHUNK, n_ids - c0);
2331    const int slot = kvh * n_chunks + chunk;
2332    if (n_here <= 0) {
2333        if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
2334        return;
2335    }
2336#pragma unroll
2337    for (int i = t; i < G * HD; i += THREADS)
2338        sq[i / HD][i % HD] = q[(size_t)(kvh * G + i / HD) * HD +
2339            ((i % HD) % 128 / 4) * 8 + ((i % HD) / 128) * 4 + (i % 4)];
2340    if (t < CHUNK) {
2341        long long r = -1;
2342        if (t < n_here) {
2343            const int cell = ids[c0 + t];
2344            const long long page = (long long) p.page_table[cell / page_size];
2345            // a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
2346            // (score -FLT_MAX, weight 0) instead of being read from before the pool.
2347            if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
2348        }
2349        srow[t] = r;
2350    }
2351    /*
2352    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2353    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2354    performance if there is no access to global memory.
2355    */
2356    item_ct1.barrier(sycl::access::fence_space::local_space);
2357    // scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions.
2358    for (int c = warp; c < CHUNK; c += WARPS) {
2359        if (c >= n_here || srow[c] < 0) {
2360            if (lane < G) sp[lane][c] = -FLT_MAX;
2361            continue;
2362        }
2363        float k8[8];
2364        private_load8_vector_codes(p, false, srow[c], lane * 8, k8);
2365#pragma unroll
2366        for (int h = 0; h < G; ++h) {
2367            const sycl::float4 qa =
2368                *reinterpret_cast<const sycl::float4 *>(&sq[h][lane * 4]);
2369            const sycl::float4 qb =
2370                *reinterpret_cast<const sycl::float4 *>(&sq[h][128 + lane * 4]);
2371            float s = k8[0] * qa.x() + k8[1] * qa.y() + k8[2] * qa.z() +
2372                      k8[3] * qa.w() + k8[4] * qb.x() + k8[5] * qb.y() +
2373                      k8[6] * qb.z() + k8[7] * qb.w();
2374            s = lane0_sum(s);
2375            if (lane == 0) sp[h][c] = s * scale;
2376        }
2377    }
2378    /*
2379    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2380    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2381    performance if there is no access to global memory.
2382    */
2383    item_ct1.barrier(sycl::access::fence_space::local_space);
2384    // per-head chunk max and exp-sum: warp w handles heads w and w+8.
2385    for (int h = warp; h < G; h += WARPS) {
2386        const float a = sp[h][lane], b = sp[h][lane + 32];
2387        const float m = warp_max(sycl::fmax(a, b));
2388        const float ea = (lane < n_here && srow[lane] >= 0)
2389                             ? sycl::native::exp(a - m)
2390                             : 0.0f;
2391        const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0)
2392                             ? sycl::native::exp(b - m)
2393                             : 0.0f;
2394        sp[h][lane] = ea;
2395        sp[h][lane + 32] = eb;
2396        const float l = lane0_sum(ea + eb);
2397        if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
2398    }
2399    /*
2400    DPCT1065: Consider replacing sycl::nd_item::barrier() with
2401    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
2402    performance if there is no access to global memory.
2403    */
2404    item_ct1.barrier(sycl::access::fence_space::local_space);
2405    // values: thread t owns dimension t for all 12 heads.
2406    float acc[G];
2407#pragma unroll
2408    for (int h = 0; h < G; ++h) acc[h] = 0.0f;
2409    for (int c0 = 0; c0 < n_here; c0 += 8) {
2410        long long rows[8]; bool full = c0 + 8 <= n_here;
2411#pragma unroll
2412        for (int j = 0; j < 8; ++j) {
2413            rows[j] = c0 + j < n_here ? srow[c0 + j] : -1;
2414            full = full && rows[j] >= 0;
2415        }
2416        if (full) {
2417            float values[8];
2418#pragma unroll
2419            for (int j = 0; j < 8; ++j) {
2420                const long long row = rows[j];
2421        float v;
2422        if constexpr (KV_MODE == 0) {
2423            v = sycl::vec<sycl::half, 1>(
2424                    sycl::bit_cast<sycl::half, unsigned short>(
2425                        p.v_pool[row * HD + t]))
2426                    .convert<float, sycl::rounding_mode::automatic>()[0];
2427        } else if constexpr (KV_MODE == 1) {
2428            const float sc =
2429                sycl::vec<sycl::half, 1>(
2430                    sycl::bit_cast<sycl::half, unsigned short>(
2431                        p.v_scale[row * (HD / KV_Q8_GROUP) +
2432                                  t / KV_Q8_GROUP]))
2433                    .convert<float, sycl::rounding_mode::automatic>()[0];
2434            v = (float) p.v_q[row * HD + t] * sc;
2435        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
2436            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
2437            const int b = t / QK4_0;
2438            const int rem = t % QK4_0;
2439            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
2440            const float d =
2441                sycl::vec<sycl::half, 1>(
2442                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
2443                    .convert<float, sycl::rounding_mode::automatic>()[0];
2444            const int j = rem < 16 ? rem : (rem - 16);
2445            const uint8_t byte = blk->qs[j];
2446            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2447            v = (float) nibble * d;
2448        }
2449                values[j] = v;
2450            }
2451#pragma unroll
2452        for (int h = 0; h < G; ++h) {
2453            const sycl::float4 p0 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0]);
2454            const sycl::float4 p1 = *reinterpret_cast<const sycl::float4*>(&sp[h][c0 + 4]);
2455            acc[h] = sycl::fma(p0[0], values[0], acc[h]);
2456            acc[h] = sycl::fma(p0[1], values[1], acc[h]);
2457            acc[h] = sycl::fma(p0[2], values[2], acc[h]);
2458            acc[h] = sycl::fma(p0[3], values[3], acc[h]);
2459            acc[h] = sycl::fma(p1[0], values[4], acc[h]);
2460            acc[h] = sycl::fma(p1[1], values[5], acc[h]);
2461            acc[h] = sycl::fma(p1[2], values[6], acc[h]);
2462            acc[h] = sycl::fma(p1[3], values[7], acc[h]);
2463        }
2464
2465        } else {
2466#pragma unroll
2467            for (int j = 0; j < 8; ++j) {
2468                const long long row = rows[j];
2469                if (row < 0) continue;
2470        float v;
2471        if constexpr (KV_MODE == 0) {
2472            v = sycl::vec<sycl::half, 1>(
2473                    sycl::bit_cast<sycl::half, unsigned short>(
2474                        p.v_pool[row * HD + t]))
2475                    .convert<float, sycl::rounding_mode::automatic>()[0];
2476        } else if constexpr (KV_MODE == 1) {
2477            const float sc =
2478                sycl::vec<sycl::half, 1>(
2479                    sycl::bit_cast<sycl::half, unsigned short>(
2480                        p.v_scale[row * (HD / KV_Q8_GROUP) +
2481                                  t / KV_Q8_GROUP]))
2482                    .convert<float, sycl::rounding_mode::automatic>()[0];
2483            v = (float) p.v_q[row * HD + t] * sc;
2484        } else {   // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
2485            constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
2486            const int b = t / QK4_0;
2487            const int rem = t % QK4_0;
2488            const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
2489            const float d =
2490                sycl::vec<sycl::half, 1>(
2491                    sycl::bit_cast<sycl::half, unsigned short>(blk->d))
2492                    .convert<float, sycl::rounding_mode::automatic>()[0];
2493            const int j = rem < 16 ? rem : (rem - 16);
2494            const uint8_t byte = blk->qs[j];
2495            const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
2496            v = (float) nibble * d;
2497        }
2498#pragma unroll
2499                for (int h = 0; h < G; ++h) acc[h] = sycl::fma(sp[h][c0 + j], v, acc[h]);
2500            }
2501        }
2502    }
2503
2504#pragma unroll
2505    for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
2506}
2507
2508class B60QsaLocalFence;
2509inline bool b60_next_qsa_pool(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_B60_NEXT_POOL");return p&&p[0]=='1';}();return on;}
2510class B60QsaFloat4;
2511thread_local bool b60_qsa_float4_probe_mode=false;
2512
2513class QsaVectorCodes;
2514}
2515static void launch_normal_qsa_vector(int mode,const float* q,const QsaAttnPools& pools,
2516    const int32_t* ids,const int32_t* steps,int64_t cap,const QsaShapes& sh,
2517    float* scratch,float* attn,int64_t nq,void* stream,float* secondary = nullptr){
2518    if(nq<=0)return;
2519    const int chunks=int((cap+CHUNK-1)/CHUNK);
2520    const long long stride=qsa_decode_attn_scratch_floats(cap,sh);
2521    auto* pm=scratch+size_t(chunks)*sh.n_head*HD;
2522    auto* pl=pm+size_t(chunks)*sh.n_head;
2523    auto* queue=strata::q_of(stream);const float scale=1.f/sqrtf(float(HD));
2524    auto props=sycl::ext::oneapi::experimental::properties{};
2525    if(b60_layout_requested()&&b60_next_qsa_pool()&&((cap==2051&&nq==1&&(!b60_single_actor_requested()&&queue->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || (cap==2051&&nq==1&&(b60_single_actor_requested()||queue->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))) {
2526    queue->parallel_for<B60QsaHead6>(
2527        sycl::nd_range<3>(sycl::range<3>(nq,sh.n_head_kv,size_t(chunks)*2*THREADS),sycl::range<3>(1,1,THREADS)),props,
2528        [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{
2529            b60_qsa_head6_kernel<1>(q,pools,ids,steps,sh.n_head_kv,sh.page_size,scale,scratch,pm,pl,chunks,cap,stride);
2530        });
2531    } else
2532    if(b60_layout_requested()&&b60_next_qsa_pool()&&((cap==2051&&nq==4&&(!b60_single_actor_requested()&&queue->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || (cap==32768&&nq==1&&(b60_single_actor_requested()||queue->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))) {
2533    queue->parallel_for<B60QsaLocalFence>(
2534        sycl::nd_range<3>(sycl::range<3>(nq,sh.n_head_kv,size_t(chunks)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2535        [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{
2536            b60_qsa_local_fence_kernel<1>(q,pools,ids,steps,sh.n_head_kv,sh.page_size,scale,scratch,pm,pl,chunks,cap,stride);
2537        });
2538    } else
2539    if(b60_qsa_float4_probe_mode || (b60_layout_requested() && ((cap==2051&&nq>=1&&nq<=4)||(cap==32768&&nq==1)))) {
2540    queue->parallel_for<B60QsaFloat4>(
2541        sycl::nd_range<3>(sycl::range<3>(nq,sh.n_head_kv,size_t(chunks)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2542        [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{
2543            b60_qsa_float4_kernel<1>(q,pools,ids,steps,sh.n_head_kv,sh.page_size,scale,scratch,pm,pl,chunks,cap,stride);
2544        });
2545    } else {
2546    queue->parallel_for<QsaVectorCodes>(
2547        sycl::nd_range<3>(sycl::range<3>(nq,sh.n_head_kv,size_t(chunks)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2548        [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{
2549            chunk_vector_codes_kernel<1>(q,pools,ids,steps,sh.n_head_kv,sh.page_size,scale,scratch,pm,pl,chunks,cap,stride);
2550        });
2551    }
2552    if (secondary) {
2553        qsa_merge_two_stage_probe(1, scratch, chunks, secondary, attn, stream);
2554        return;
2555    }
2556    queue->parallel_for<dpct_kernel_name<class qsa_vector_codes_merge>>(
2557        sycl::nd_range<3>(sycl::range<3>(1,nq,size_t(sh.n_head)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2558        [=](sycl::nd_item<3>){attn_merge_kernel(scratch,pm,pl,chunks,attn,stride);});
2559}
2560static void launch_qsa_chunk_down(int mode,const float* q,const QsaAttnPools& pools,
2561    const int32_t* ids,const int32_t* steps,int64_t cap,const QsaShapes& s,
2562    float* scratch,float* attn,int64_t nq,void* stream){
2563    if(mode<0||mode>1)throw std::invalid_argument("QSA chunk down mode");
2564    if(mode==0||!pools.k_q||!pools.v_q||pools.k_q4||pools.v_q4){
2565        qsa_decode_attn_batch(q,pools,ids,steps,cap,s,scratch,attn,nq,stream);return;
2566    }
2567    if(nq<=0)return;
2568    static const bool vector_enabled = [] {
2569        const char* v = std::getenv("STRATA_SYCL_QSA_VALUE8_K8_VEC");
2570        return !v || v[0] == '1';
2571    }();
2572    const bool vector_shape=(cap==2051&&(nq==1||nq==2||nq==3||nq==4||nq==32))||(cap==32768&&nq==1);
2573    if(vector_enabled&&vector_shape){launch_normal_qsa_vector(1,q,pools,ids,steps,cap,s,scratch,attn,nq,stream);return;}
2574    const int chunks=int((cap+CHUNK-1)/CHUNK);
2575    const long long stride=qsa_decode_attn_scratch_floats(cap,s);
2576    auto* part_m=scratch+size_t(chunks)*s.n_head*HD;
2577    auto* part_l=part_m+size_t(chunks)*s.n_head;
2578    auto* queue=strata::q_of(stream);
2579    const float scale=1.f/sqrtf(float(HD));
2580    auto props=sycl::ext::oneapi::experimental::properties{};
2581    queue->parallel_for<QsaChunkDown>(
2582        sycl::nd_range<3>(sycl::range<3>(nq,s.n_head_kv,size_t(chunks)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2583        [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{
2584            chunk_down_kernel<1>(q,pools,ids,steps,s.n_head_kv,s.page_size,scale,
2585                scratch,part_m,part_l,chunks,cap,stride);
2586        });
2587    queue->parallel_for<dpct_kernel_name<class qsa_chunk_down_merge>>(
2588        sycl::nd_range<3>(sycl::range<3>(1,nq,size_t(s.n_head)*THREADS),sycl::range<3>(1,1,THREADS)),props,
2589        [=](sycl::nd_item<3>){attn_merge_kernel(scratch,part_m,part_l,chunks,attn,stride);});
2590}
2591
2592bool qsa_decode_attn_batch_try_two_stage(const float* q, const QsaAttnPools& pools,
2593    const int32_t* ids, const int32_t* steps, int64_t cap, const QsaShapes& s,
2594    float* scratch, float* attn, int64_t n_q, float* secondary,
2595    uint64_t secondary_floats, void* stream) {
2596    // The sole caller owns parts_ and a one-query scratch. Keep every other
2597    // caller, geometry, storage mode and existing dispatch fallback unchanged.
2598    if (cap != 32768 || n_q != 1 || s.n_head != 24 || s.n_head_kv != 2 ||
2599        s.head_dim != 256 || s.page_size != 4 || !q || !ids || !steps ||
2600        !scratch || !attn || !secondary || !pools.page_table ||
2601        !pools.k_q || !pools.v_q || !pools.k_scale || !pools.v_scale ||
2602        pools.k_q4 || pools.v_q4 || !qsa_chunk_down_supported(cap, n_q, s, stream))
2603        return false;
2604    static const bool vector_enabled = [] {
2605        const char* v = std::getenv("STRATA_SYCL_QSA_VALUE8_K8_VEC");
2606        return !v || v[0] == '1';
2607    }();
2608    auto* queue = strata::q_of(stream);
2609    const int chunks = int((cap + CHUNK - 1) / CHUNK);
2610    const uint64_t used = qsa_merge_two_stage_scratch_floats(chunks);
2611    if (!vector_enabled || !queue->is_in_order() || secondary_floats < used)
2612        return false;
2613    const auto disjoint = [](const void* a, uint64_t an, const void* b, uint64_t bn) {
2614        const uintptr_t av = reinterpret_cast<uintptr_t>(a), bv = reinterpret_cast<uintptr_t>(b);
2615        if (av > UINTPTR_MAX - an || bv > UINTPTR_MAX - bn) return false;
2616        return av + an <= bv || bv + bn <= av;
2617    };
2618    const uint64_t bytes = used * sizeof(float);
2619    if (!disjoint(secondary, bytes, scratch, qsa_decode_attn_scratch_floats(cap, s) * sizeof(float)) ||
2620        !disjoint(secondary, bytes, attn, uint64_t(24 * HD) * sizeof(float)) ||
2621        !disjoint(secondary, bytes, q, uint64_t(24 * HD) * sizeof(float)))
2622        return false;
2623    launch_normal_qsa_vector(1, q, pools, ids, steps, cap, s, scratch, attn,
2624                             n_q, stream, secondary);
2625    return true;
2626}
2627}
2628
2629namespace strata::kernels {
2630void qsa_query_float4_probe(int mode,const float*q,const QsaAttnPools&p,const int32_t*ids,const int32_t*steps,int64_t cap,const QsaShapes&sh,float*scratch,float*attn,int64_t T,void*stream,float*secondary){
2631 if(mode<0||mode>1)throw std::invalid_argument("B60 query float4 mode");
2632 struct Restore {bool previous;~Restore(){b60_qsa_float4_probe_mode=previous;}} restore{b60_qsa_float4_probe_mode};
2633 b60_qsa_float4_probe_mode=mode==1;
2634 launch_normal_qsa_vector(1,q,p,ids,steps,cap,sh,scratch,attn,T,stream,secondary);
2635}
2636}