okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
30.4 KiB594 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// src/models/qwen4exp.cpp; ggml/src/ggml-cuda/{set-rows.cu,norm.cu,rope.cu}.
3// MIT License
4// Copyright (c) 2023-2026 The ggml authors
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11// The above copyright notice and this permission notice shall be included in all
12// copies or substantial portions of the Software.
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#define DPCT_PROFILING_ENABLED
22#include <sycl/sycl.hpp>
23#include "strata/kprof.hpp"
24#include "strata/core/geometry.hpp"
25#include <dpct/dpct.hpp>
26#include "strata/sycl_queue.hpp"
27#include "strata/kernels/native_qsa_indexer.hpp"
28#include "strata/kernels/mrope.hpp"
29#include <atomic>
30#include <cmath>
31#include <cstddef>
32#include <cstdint>
33#include <limits>
34#include <stdexcept>
35
36namespace strata::kernels {
37namespace {
38std::atomic<bool> enabled{false};
39constexpr int D = 128, R = 4, ROT = 64, THREADS = 256;
40static_assert(D == strata::core::kCompiledGeometry.idx_key_dim && R == strata::core::kCompiledGeometry.idx_block && ROT == strata::core::kCompiledGeometry.n_rot,
41              "native_qsa_indexer is compiled for core/geometry.hpp");
42inline float warp_sum(float x) {
43#pragma unroll
44    for (int offset = 16; offset; offset >>= 1)
45        /*
46        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
47        feature masked sub_group function which may not be supported by all
48        compilers or runtimes. You may need to adjust the code.
49        */
50        x += dpct::experimental::permute_sub_group_by_xor(
51            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
52            offset);
53    return x;
54}
55// TAB (#280, STRATA_ROPE_TABLE=1): the angles from the session's float64 table.  The host launches <false> whenever
56// no table applies - the default - so the default kernel is 0.1.31's code exactly (the table read is not in it;
57// with it merely skipped at run time, the compiled default path changed its results).
58template <bool TAB>
59__dpct_inline__ void
60append(const float *__restrict__ raw, const int32_t *__restrict__ pos_dev,
61       int pos_stride, int n_steps, int pos_base,
62       const float *__restrict__ gamma, float epsilon, float *__restrict__ tail,
63       float *__restrict__ dead, float *__restrict__ pooled,
64       int32_t *__restrict__ block_pos, int max_cells, float theta_scale,
65       float freq_scale, float corr_low, float corr_high, float ext_factor,
66       float mscale, const int32_t *__restrict__ mtab, RopeTab rt) {
67    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
68auto &values = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[D]>(
69    sycl::ext::oneapi::this_work_item::get_work_group<3>());
70    auto &partials =
71        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
72            sycl::ext::oneapi::this_work_item::get_work_group<3>());
73    const int d = item_ct1.get_local_id(2);
74    for (int step_idx = 0; step_idx < n_steps; ++step_idx) {
75        const int pos = pos_dev[(std::size_t) step_idx * pos_stride];
76        if (pos >= 0 && pos < max_cells) {
77            const float* raw_step = raw + (std::size_t) step_idx * D;
78            const int slot = pos % R;
79            float incoming = 0.0f;
80            if (d < D) {
81                // SET_ROWS stores F16; GET_ROWS expands those exact values to F32.
82                incoming =
83                    sycl::vec<sycl::half, 1>(
84                        sycl::vec<float, 1>(raw_step[d])
85                            .convert<sycl::half, sycl::rounding_mode::rte>()[0])
86                        .convert<float, sycl::rounding_mode::automatic>()[0];
87                if (slot < R - 1) tail[slot * D + d] = incoming;
88            }
89            if (pos == 0 || slot == R - 1) {
90                float mean = 0.0f;
91                if (d < D) {
92                    // The spare's four gather indices all name cell zero. Completed blocks
93                    // use chronological slices; each graph ADD materializes an F32 sum.
94                    float sum = pos == 0 ? incoming : tail[d];
95#pragma unroll
96                    for (int j = 1; j < R; ++j)
97                        /*
98                        DPCT1013: The rounding mode could not be specified
99                        and the generated code may have different accuracy than
100                        the original code. Verify the correctness. SYCL math
101                        built-in function rounding mode is aligned with OpenCL
102                        C 1.2 standard.
103                        */
104                        sum = sum + (pos == 0 || j == R - 1 ? incoming
105                                                             : tail[j * D + d]);
106                    /*
107                    DPCT1013: The rounding mode could not be specified and
108                    the generated code may have different accuracy than the
109                    original code. Verify the correctness. SYCL math built-in
110                    function rounding mode is aligned with OpenCL C 1.2
111                    standard.
112                    */
113                    mean = sycl::fma(0.25f, sum,
114                                     0.0f); // SCALE includes a zero bias.
115                }
116                float square_sum = 0.0f;
117                if (d < D) square_sum += mean * mean;
118                square_sum = warp_sum(square_sum);
119                const int lane = d % 32;
120                if (lane == 0) partials[d / 32] = square_sum;
121                /*
122                DPCT1118: SYCL group functions and algorithms must be
123                encountered in converged control flow. You may need to adjust
124                the code.
125                */
126                /*
127                DPCT1065: Consider replacing sycl::nd_item::barrier() with
128                sycl::nd_item::barrier(sycl::access::fence_space::local_space)
129                for better performance if there is no access to global memory.
130                */
131                item_ct1.barrier();
132                square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;
133                square_sum = warp_sum(square_sum);
134                const float scale = sycl::rsqrt(square_sum / D + epsilon);
135                if (d < D) values[d] = scale * mean * gamma[d];
136                /*
137                DPCT1118: SYCL group functions and algorithms must be
138                encountered in converged control flow. You may need to adjust
139                the code.
140                */
141                /*
142                DPCT1065: Consider replacing sycl::nd_item::barrier() with
143                sycl::nd_item::barrier(sycl::access::fence_space::local_space)
144                for better performance if there is no access to global memory.
145                */
146                item_ct1.barrier();
147                if (d < D) {
148                    const int b = pos / R;
149                    const int rope_pos = pos == 0 ? 0 : pos_base + R * b;
150                    float y = values[d];
151                    if (d < ROT) {
152                        const int pair = d % (ROT / 2);
153                        // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in
154                        // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved.
155                        float c, s;
156                        if (!(TAB && rope_tab_cs(rt, pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
157                            const float theta_extrap =
158                                (pos == 0 ? 0
159                                          : mrope_pos(mtab, rope_pos, pair)) *
160                                dpct::pow(theta_scale, float(pair));
161                            rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
162                        }
163                        const float a = values[pair], z = values[pair + ROT / 2];
164                        y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
165                    }
166                    pooled[std::size_t(b) * D + d] = y;
167                    if (pos == 0) dead[d] = y;
168                    else pooled[std::size_t(b + 1) * D + d] = dead[d];
169                    if (d == 0 && pos != 0) *block_pos = rope_pos;
170                }
171            }
172        }
173        /*
174        DPCT1118: SYCL group functions and algorithms must be encountered in
175        converged control flow. You may need to adjust the code.
176        */
177        /*
178        DPCT1065: Consider replacing sycl::nd_item::barrier() with
179        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
180        better performance if there is no access to global memory.
181        */
182        if (n_steps > 1) item_ct1.barrier();
183    }
184}
185// ---- C-2: the batched append.  The pooled key of a completed block b (its last cell pos = 4b+3), computed with
186// the single append's arithmetic: keys rounded through F16, summed tail[0]+tail[1]+tail[2]+incoming in that order,
187// the RMS norm, gamma, the rotation at pos_base + 4b.  `k(j)` is the key of the block's cell j: a row of this batch
188// (cell >= p0) or the tail the previous batch left (cell < p0).  Only the batch's last completed block writes the
189// spare after it (every earlier one's is overwritten by the next block in order).
190template <bool TAB>
191__dpct_inline__ float
192pooled_value(const float *values, int d, int rope_pos, float theta_scale,
193             float freq_scale, float corr_low, float corr_high,
194             float ext_factor, float mscale, const int32_t *mtab, bool zero_pos,
195             const RopeTab &rt) {
196    float y = values[d];
197    if (d < ROT) {
198        const int pair = d % (ROT / 2);
199        // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is
200        // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero
201        // angle carries the mscale magnitude through cos(0) exactly as the single append's does.
202        float c, s;
203        if (!(TAB && rope_tab_cs(rt, zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair), pair, c, s))) {
204            const float theta_extrap =
205                (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) *
206                dpct::pow(theta_scale, float(pair));
207            rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s);
208        }
209        const float a = values[pair], z = values[pair + ROT / 2];
210        y = d < ROT / 2 ? a * c - z * s : a * s + z * c;
211    }
212    return y;
213}
214__dpct_inline__ float norm_scale(float mean, float *partials, int d) {
215    float square_sum = d < D ? mean * mean : 0.0f;
216    square_sum = warp_sum(square_sum);
217    const int lane = d % 32;
218    if (lane == 0) partials[d / 32] = square_sum;
219    /*
220    DPCT1065: Consider replacing sycl::nd_item::barrier() with
221    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
222    performance if there is no access to global memory.
223    */
224    sycl::ext::oneapi::this_work_item::get_nd_item<3>().barrier();
225    square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;
226    square_sum = warp_sum(square_sum);
227    return square_sum;
228}
229// cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead
230template <bool TAB>
231__dpct_inline__ void
232append_first(const float *__restrict__ raw, const float *__restrict__ gamma,
233             float epsilon, float *__restrict__ dead,
234             float *__restrict__ pooled, float theta_scale, float freq_scale,
235             float corr_low, float corr_high, float ext_factor, float mscale,
236             const int32_t *__restrict__ mtab, RopeTab rt) {
237    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
238    const int d = item_ct1.get_local_id(2);
239    auto &values =
240        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[D]>(
241            sycl::ext::oneapi::this_work_item::get_work_group<3>());
242    auto &partials =
243        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
244            sycl::ext::oneapi::this_work_item::get_work_group<3>());
245    float mean = 0.0f;
246    if (d < D) {
247        const float incoming =
248            sycl::vec<sycl::half, 1>(
249                sycl::vec<float, 1>(raw[d])
250                    .convert<sycl::half, sycl::rounding_mode::rte>()[0])
251                .convert<float, sycl::rounding_mode::automatic>()[0];
252        float sum = incoming;
253#pragma unroll
254        /*
255        DPCT1013: The rounding mode could not be specified and the generated
256        code may have different accuracy than the original code. Verify the
257        correctness. SYCL math built-in function rounding mode is aligned with
258        OpenCL C 1.2 standard.
259        */
260        for (int j = 1; j < R; ++j) sum = sum + incoming;
261        /*
262        DPCT1013: The rounding mode could not be specified and the generated
263        code may have different accuracy than the original code. Verify the
264        correctness. SYCL math built-in function rounding mode is aligned with
265        OpenCL C 1.2 standard.
266        */
267        mean = sycl::fma(0.25f, sum, 0.0f);
268    }
269    const float square_sum = norm_scale(mean, partials, d);
270    const float scale = sycl::rsqrt(square_sum / D + epsilon);
271    if (d < D) values[d] = scale * mean * gamma[d];
272    /*
273    DPCT1065: Consider replacing sycl::nd_item::barrier() with
274    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
275    performance if there is no access to global memory.
276    */
277    item_ct1.barrier();
278    if (d >= D) return;
279    const float y = pooled_value<TAB>(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale,
280                                 mtab, true, rt);
281    pooled[d] = y;
282    dead[d] = y;
283}
284template <bool TAB>
285__dpct_inline__ void
286append_blocks(const float *__restrict__ raw, int64_t n, int64_t p0,
287              int pos_base, const float *__restrict__ gamma, float epsilon,
288              const float *__restrict__ tail, const float *__restrict__ dead,
289              float *__restrict__ pooled, int32_t *__restrict__ block_pos,
290              int64_t first_block, int64_t last_block, float theta_scale,
291              float freq_scale, float corr_low, float corr_high,
292              float ext_factor, float mscale, const int32_t *__restrict__ mtab,
293              RopeTab rt) {
294    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
295    const int64_t b = first_block + item_ct1.get_group(2);
296    const int d = item_ct1.get_local_id(2);
297    auto &values =
298        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[D]>(
299            sycl::ext::oneapi::this_work_item::get_work_group<3>());
300    auto &partials =
301        *sycl::ext::oneapi::group_local_memory_for_overwrite<float[32]>(
302            sycl::ext::oneapi::this_work_item::get_work_group<3>());
303    float mean = 0.0f;
304    if (d < D) {
305        auto key = [&](int j) -> float {
306            const int64_t cell = b * R + j;
307            return cell >= p0
308                       ? sycl::vec<sycl::half, 1>(
309                             sycl::vec<float, 1>(raw[(cell - p0) * D + d])
310                                 .convert<sycl::half,
311                                          sycl::rounding_mode::rte>()[0])
312                             .convert<float,
313                                      sycl::rounding_mode::automatic>()[0]
314                       : tail[j * D + d];
315        };
316        float sum = key(0);
317#pragma unroll
318        /*
319        DPCT1013: The rounding mode could not be specified and the generated
320        code may have different accuracy than the original code. Verify the
321        correctness. SYCL math built-in function rounding mode is aligned with
322        OpenCL C 1.2 standard.
323        */
324        for (int j = 1; j < R; ++j) sum = sum + key(j);
325        /*
326        DPCT1013: The rounding mode could not be specified and the generated
327        code may have different accuracy than the original code. Verify the
328        correctness. SYCL math built-in function rounding mode is aligned with
329        OpenCL C 1.2 standard.
330        */
331        mean = sycl::fma(0.25f, sum, 0.0f);
332    }
333    const float square_sum = norm_scale(mean, partials, d);
334    const float scale = sycl::rsqrt(square_sum / D + epsilon);
335    if (d < D) values[d] = scale * mean * gamma[d];
336    /*
337    DPCT1065: Consider replacing sycl::nd_item::barrier() with
338    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
339    performance if there is no access to global memory.
340    */
341    item_ct1.barrier();
342    if (d >= D) return;
343    const int rope_pos = pos_base + R * (int) b;
344    pooled[std::size_t(b) * D + d] = pooled_value<TAB>(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high,
345                                                  ext_factor, mscale, mtab, false, rt);
346    if (b == last_block) {
347        pooled[std::size_t(b + 1) * D + d] = dead[d];
348        if (d == 0) *block_pos = rope_pos;
349    }
350}
351// the tail after the batch: slot s holds the key of the batch's last cell with cell % 4 == s (s < 3), if any
352__dpct_inline__ void append_tail(const float *__restrict__ raw, int64_t n,
353                                 int64_t p0, float *__restrict__ tail) {
354    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
355    const int s = item_ct1.get_group(2), d = item_ct1.get_local_id(2);
356    if (d >= D) return;
357    const int64_t last = p0 + n - 1;
358    int64_t cell = last - ((last % R) - s + R) % R;       // the last cell <= last with cell % 4 == s
359    if (cell < p0) return;
360    tail[s * D + d] =
361        sycl::vec<sycl::half, 1>(
362            sycl::vec<float, 1>(raw[(cell - p0) * D + d])
363                .convert<sycl::half, sycl::rounding_mode::rte>()[0])
364            .convert<float, sycl::rounding_mode::automatic>()[0];
365}
366struct Span { const void* p; std::size_t n; };
367void validate(Span s) {
368    const auto p = reinterpret_cast<std::uintptr_t>(s.p);
369    if (!p || p % 4 || s.n > UINTPTR_MAX - p)
370        throw std::invalid_argument("native QSA indexer requires aligned bounded spans");
371}
372bool overlaps(Span a, Span b) {
373    const auto x = reinterpret_cast<std::uintptr_t>(a.p), y = reinterpret_cast<std::uintptr_t>(b.p);
374    return x < y + b.n && y < x + a.n;
375}
376} // namespace
377
378void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); }
379bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); }
380void native_qsa_indexer_append_steps(const float* raw, const int32_t* relative_pos_device,
381                                     int pos_stride, int n_steps, int32_t pos_base,
382                                     const float* gamma, float epsilon, const QsaIndexerBuffers& b,
383                                     const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
384    if (n_steps <= 0) return;
385    if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT ||
386        max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R ||
387        int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f ||
388        rope_scaling_invalid(scaling) != nullptr)
389        throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream");
390    const std::size_t pos_span = (n_steps == 1 || pos_stride <= 0) ? 4 : (std::size_t(n_steps - 1) * pos_stride + 1) * 4;
391    const Span spans[] = {{raw,std::size_t(n_steps)*D*4},{relative_pos_device,pos_span},{gamma,D*4},{b.tail,(R-1)*D*4},
392        {b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}};
393    for (const auto& span : spans) validate(span);
394    for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j)
395        if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap");
396    const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
397    const RopeKernelArgs k = scaling.kernel_args(ROT);   // none: the identity constants
398    const RopeTab rt = rope_table_for(scaling);
399    if (rt.cos != nullptr)
400    {
401        auto exp_props = sycl::ext::oneapi::experimental::properties{
402            sycl::ext::oneapi::experimental::use_root_sync};
403
404        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
405            ->submit([&](sycl::handler &cgh) {
406                auto mrope_table_ct18 = mrope_table();
407
408                cgh.parallel_for<dpct_kernel_name<class append_182f95,
409                                                  dpct_kernel_scalar<true>>>(
410                    sycl::nd_range<3>(sycl::range(1, 1, THREADS),
411                                      sycl::range(1, 1, THREADS)),
412                    exp_props,
413                    [=](sycl::nd_item<3> item_ct1)
414                        [[sycl::reqd_sub_group_size(32)]] {
415                            append<true>(raw, relative_pos_device, pos_stride,
416                                         n_steps, pos_base, gamma, epsilon,
417                                         b.tail, b.dead, b.pooled, b.block_pos,
418                                         int(max_cells), theta_scale,
419                                         k.freq_scale, k.corr_low, k.corr_high,
420                                         k.ext_factor, k.attn_factor,
421                                         mrope_table_ct18, rt);
422                        });
423            });
424    } else {
425        auto exp_props = sycl::ext::oneapi::experimental::properties{
426            sycl::ext::oneapi::experimental::use_root_sync};
427
428        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
429            ->submit([&](sycl::handler &cgh) {
430                auto mrope_table_ct18 = mrope_table();
431
432                cgh.parallel_for<dpct_kernel_name<class append_182f95,
433                                                  dpct_kernel_scalar<false>>>(
434                    sycl::nd_range<3>(sycl::range(1, 1, THREADS),
435                                      sycl::range(1, 1, THREADS)),
436                    exp_props,
437                    [=](sycl::nd_item<3> item_ct1)
438                        [[sycl::reqd_sub_group_size(32)]] {
439                            append<false>(raw, relative_pos_device, pos_stride,
440                                          n_steps, pos_base, gamma, epsilon,
441                                          b.tail, b.dead, b.pooled, b.block_pos,
442                                          int(max_cells), theta_scale,
443                                          k.freq_scale, k.corr_low, k.corr_high,
444                                          k.ext_factor, k.attn_factor,
445                                          mrope_table_ct18, rt);
446                        });
447            });
448    }
449    /*
450    DPCT1010: SYCL uses exceptions to report errors and does not use the
451    error codes. The cudaGetLastError function call was replaced with 0. You
452    need to rewrite this code.
453    */
454    const auto error = 0;
455    /*
456    DPCT1009: SYCL reports errors using exceptions and does not use error
457    codes. Please replace the "get_error_string_dummy(...)" with a real
458    error-handling function.
459    */
460    /*
461    DPCT1001: The statement could not be removed.
462    */
463    /*
464    DPCT1000: Error handling if-stmt was detected but could not be
465    rewritten.
466    */
467    if (error !=
468        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
469}
470
471void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base,
472                               const float* gamma, float epsilon, const QsaIndexerBuffers& b,
473                               const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) {
474    native_qsa_indexer_append_steps(raw, relative_pos_device, 0, 1, pos_base, gamma, epsilon, b, s, max_cells, scaling, stream);
475}
476void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma,
477                                     float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells,
478                                     const RopeScaling& scaling, void* stream) {
479    if (n <= 0) return;
480    if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells ||
481        max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX ||
482        !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr)
483        throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling");
484    const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT);
485    const RopeKernelArgs k = scaling.kernel_args(ROT);   // none: the identity constants
486    const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor;
487    const dpct::queue_ptr st = strata::q_of(stream);
488    const int32_t* mtab = mrope_table();
489    const RopeTab rt = rope_table_for(scaling);
490    if (p0 == 0) {
491        if (rt.cos != nullptr)
492        {
493            auto exp_props = sycl::ext::oneapi::experimental::properties{
494                sycl::ext::oneapi::experimental::use_root_sync};
495
496            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class append_first_ea2d1f,
497                                              dpct_kernel_scalar<true>>>(
498                sycl::nd_range<3>(sycl::range(1, 1, THREADS),
499                                  sycl::range(1, 1, THREADS)),
500                exp_props,
501                [=](sycl::nd_item<3> item_ct1)
502                    [[sycl::reqd_sub_group_size(32)]] {
503                        append_first<true>(raw, gamma, epsilon, b.dead,
504                                           b.pooled, theta_scale, fsf, cl, ch,
505                                           ef, ms, mtab, rt);
506                    });
507        } else {
508            auto exp_props = sycl::ext::oneapi::experimental::properties{
509                sycl::ext::oneapi::experimental::use_root_sync};
510
511            strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class append_first_ea2d1f,
512                                              dpct_kernel_scalar<false>>>(
513                sycl::nd_range<3>(sycl::range(1, 1, THREADS),
514                                  sycl::range(1, 1, THREADS)),
515                exp_props,
516                [=](sycl::nd_item<3> item_ct1)
517                    [[sycl::reqd_sub_group_size(32)]] {
518                        append_first<false>(raw, gamma, epsilon, b.dead,
519                                            b.pooled, theta_scale, fsf, cl, ch,
520                                            ef, ms, mtab, rt);
521                    });
522        }
523    }
524    // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n)
525    const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R;       // the smallest b with 4b+3 >= p0
526    const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1;   // the largest b with 4b+3 <= p0+n-1
527    if (hi >= first && rt.cos != nullptr)
528    {
529        auto exp_props = sycl::ext::oneapi::experimental::properties{
530            sycl::ext::oneapi::experimental::use_root_sync};
531
532        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class append_blocks_a6c94e,
533                                          dpct_kernel_scalar<true>>>(
534            sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(hi - first + 1)) *
535                                  sycl::range(1, 1, THREADS),
536                              sycl::range(1, 1, THREADS)),
537            exp_props,
538            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
539                append_blocks<true>(raw, n, p0, pos_base, gamma, epsilon,
540                                    b.tail, b.dead, b.pooled, b.block_pos,
541                                    first, hi, theta_scale, fsf, cl, ch, ef, ms,
542                                    mtab, rt);
543            });
544    } else if (hi >= first)
545    {
546        auto exp_props = sycl::ext::oneapi::experimental::properties{
547            sycl::ext::oneapi::experimental::use_root_sync};
548
549        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class append_blocks_a6c94e,
550                                          dpct_kernel_scalar<false>>>(
551            sycl::nd_range<3>(sycl::range(1, 1, (unsigned)(hi - first + 1)) *
552                                  sycl::range(1, 1, THREADS),
553                              sycl::range(1, 1, THREADS)),
554            exp_props,
555            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
556                append_blocks<false>(raw, n, p0, pos_base, gamma, epsilon,
557                                     b.tail, b.dead, b.pooled, b.block_pos,
558                                     first, hi, theta_scale, fsf, cl, ch, ef,
559                                     ms, mtab, rt);
560            });
561    }
562    {
563        auto exp_props = sycl::ext::oneapi::experimental::properties{
564            sycl::ext::oneapi::experimental::use_root_sync};
565
566        strata::kprof::kp(st, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class append_tail_e0658e>>(
567            sycl::nd_range<3>(sycl::range(1, 1, R - 1) * sycl::range(1, 1, D),
568                              sycl::range(1, 1, D)),
569            exp_props, [=](sycl::nd_item<3> item_ct1) {
570                append_tail(raw, n, p0, b.tail);
571            });
572    }
573    /*
574    DPCT1010: SYCL uses exceptions to report errors and does not use the
575    error codes. The cudaGetLastError function call was replaced with 0. You
576    need to rewrite this code.
577    */
578    const auto error = 0;
579    /*
580    DPCT1009: SYCL reports errors using exceptions and does not use error
581    codes. Please replace the "get_error_string_dummy(...)" with a real
582    error-handling function.
583    */
584    /*
585    DPCT1001: The statement could not be removed.
586    */
587    /*
588    DPCT1000: Error handling if-stmt was detected but could not be
589    rewritten.
590    */
591    if (error !=
592        0) throw std::runtime_error(dpct::get_error_string_dummy(error));
593}
594} // namespace strata::kernels