okami.mom/strata

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

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

main
46.6 KiB983 linesraw
1// src/kernels/cuda/elementwise.cu - P2.S5's glue kernels.  See the header for why each exists.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include "strata/kprof.hpp"
5#include <dpct/dpct.hpp>
6#include "strata/sycl_queue.hpp"
7#include "strata/sycl_doorbell.hpp"
8#include "strata/kernels/elementwise.hpp"
9#include "strata/kernels/dp4a.hpp"
10
11#include "strata/kernels/bf16_bits.hpp"
12#include "strata/kernels/f16_bits.hpp"
13
14#include <cmath>
15#include <cstdio>
16#include <cstdlib>
17#include <atomic>
18#include <chrono>
19
20namespace strata::kernels {
21namespace {
22
23constexpr int THREADS = 256;
24
25__dpct_inline__ void embedding_gather_kernel(const uint8_t *__restrict__ codes,
26                                             const float *__restrict__ scales,
27                                             const float *__restrict__ offsets,
28                                             int64_t n, int code_bits,
29                                             int code_bias, int group_elems,
30                                             float *__restrict__ out) {
31    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
32    const int64_t i =
33        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
34        item_ct1.get_local_id(2);
35    if (i >= n) return;
36    const int per_byte = 8 / code_bits;
37    const unsigned mask = (1u << code_bits) - 1u;
38    const int code = (codes[i / per_byte] >> ((i % per_byte) * code_bits)) & mask;
39    const int64_t group = i / group_elems;
40    /*
41    DPCT1013: The rounding mode could not be specified and the generated
42    code may have different accuracy than the original code. Verify the
43    correctness. SYCL math built-in function rounding mode is aligned with
44    OpenCL C 1.2 standard.
45    */
46    const float product = (float)(code + code_bias) * scales[group];
47    /*
48    DPCT1013: The rounding mode could not be specified and the generated
49    code may have different accuracy than the original code. Verify the
50    correctness. SYCL math built-in function rounding mode is aligned with
51    OpenCL C 1.2 standard.
52    */
53    out[i] = product + (offsets ? offsets[group] : 0.0f);
54}
55
56/// `ggml_compute_softplus_f32`: `log1p(exp(x))`, with the large-x branch that avoids overflow.
57///
58/// The branch is not cosmetic. `exp(89)` overflows f32 and `exp(20)` is already 4.85e8 where `log1p` loses
59/// relative precision; above 20 the function is `x` to within f32 anyway.
60__dpct_inline__ float softplus_dev(float x) {
61    return x > 20.0f ? x : sycl::log1p(sycl::native::exp(x));
62}
63
64__dpct_inline__ void gdn_gate_kernel(const float *__restrict__ alpha,
65                                     const float *__restrict__ dt,
66                                     const float *__restrict__ ssm_a,
67                                     float *__restrict__ gate, int64_t h_v) {
68    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
69    const int64_t i =
70        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
71        item_ct1.get_local_id(2);
72    if (i >= h_v) return;
73    const int64_t t = i / h_v;      // `n_tokens` is the leading dim; the real call has one token
74    const int64_t h = i % h_v;
75    gate[i] = softplus_dev(alpha[i] + dt[h]) * ssm_a[h];
76    (void) t;
77}
78
79__dpct_inline__ void scale_kernel(float *__restrict__ x, int64_t n, float s) {
80    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
81    const int64_t i =
82        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
83        item_ct1.get_local_id(2);
84    if (i < n) x[i] *= s;
85}
86
87// `dst[i] += src[i]`.  See the header: this is what lets R4's GPU half and CPU half run at the same
88// time and still add up to one `parts` buffer.
89__dpct_inline__ void add_kernel(float *__restrict__ dst,
90                                const float *__restrict__ src, long long n) {
91    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
92    const long long i =
93        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
94        item_ct1.get_local_id(2);
95    if (i < n) dst[i] += src[i];
96}
97
98__dpct_inline__ void to_f16_kernel(const float *__restrict__ x,
99                                   uint16_t *__restrict__ y, int64_t n) {
100    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
101    const int64_t i =
102        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
103        item_ct1.get_local_id(2);
104    if (i < n) y[i] = f16_from_f32(x[i]);
105}
106
107__dpct_inline__ void to_bf16_kernel(const float *__restrict__ x,
108                                    uint16_t *__restrict__ y, int64_t n) {
109    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
110    const int64_t i =
111        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
112        item_ct1.get_local_id(2);
113    if (i < n) y[i] = bf16_from_f32(x[i]);
114}
115
116__dpct_inline__ void silu_kernel(float *__restrict__ x, int64_t n) {
117    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
118    const int64_t i =
119        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
120        item_ct1.get_local_id(2);
121    if (i >= n) return;
122    // DOUBLE then cast, matching `ref/gdn.py`'s numpy: its arrays are f32 but `np.exp` on an f32 array is
123    // computed to f32 precision by a different algorithm than `expf`, and the reference is the oracle.  The
124    // difference is in the last bits and this is one line.
125    const double v = (double) x[i];
126    x[i] = (float)(v / (1.0 + sycl::exp(-v)));
127}
128
129/// A bounded launch: a zero-length grid is illegal, and `n == 0` is a real call (an empty selection).
130inline unsigned grid_for(int64_t n) { return (unsigned) ((n + THREADS - 1) / THREADS); }
131
132/// One WARP per row, reduced through shuffles.  The rows here are short and few - (24, 256), (2, 256),
133/// (4, 128) - so a block-per-row tree would spend its time in `__syncthreads` for 8 warps of 32, and the whole
134/// call is 30 rows.  A warp reduction with NO shared memory and NO barrier is the shape that fits.
135__dpct_inline__ void rms_norm_weighted_kernel(float *__restrict__ x,
136                                              const float *__restrict__ w,
137                                              int64_t rows, int64_t cols,
138                                              float eps) {
139
140    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
141    const int lane = item_ct1.get_local_id(2) & 31;
142    const int64_t row =
143        ((int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) >> 5)) +
144        (item_ct1.get_local_id(2) >> 5);
145    // **THE ROW GUARD IS NOT DECORATION, AND ITS ABSENCE WAS THE QSA BUG.**  The launcher rounds the grid up to
146    // whole 4-warp blocks, so a call with `rows` = 2 - the QSA k-norm, the only non-multiple-of-4 row count in
147    // the engine - runs EIGHT warps: rows 0 and 1 are the data, and rows 2 and 3 write 2*cols floats PAST the
148    // end of `b.kcur`, which in the arena is exactly where `b.vcur` begins.  `b.vcur` was therefore silently
149    // replaced by two rows of `rms_norm(...) * attn_k_norm`: a normalized vector with l2 ~20.6 against V's
150    // ~5.7, which the attention then attended to.  `rope_neox_kernel` has had this guard all along.
151    if (row >= rows) return;
152    float* r = x + row * cols;
153    float acc = 0.0f;
154#pragma unroll
155    for (int64_t c = lane; c < cols; c += 32) acc += r[c] * r[c];
156    /*
157DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
158masked sub_group function which may not be supported by all compilers or
159runtimes. You may need to adjust the code.
160*/
161#pragma unroll
162    for (int off = 16; off > 0; off >>= 1) acc +=
163        dpct::experimental::shift_sub_group_left(
164            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
165            acc, off);
166    // The MEAN, not the sum: `ref/qsa.py::rms_norm` divides by `np.mean(np.square(x))`.  Broadcasting the
167    // reciprocal from lane 0 keeps all 32 lanes on the same value - computing `rsqrt` per lane would be the
168    // same number but a needless 32-way divergence in the last bit.
169    float inv = 0.0f;
170    if (lane == 0) inv = sycl::rsqrt(acc / (float)cols + eps);
171    /*
172    DPCT1108: '__shfl_sync' was migrated with the experimental feature masked
173    sub_group function which may not be supported by all compilers or runtimes.
174    You may need to adjust the code.
175    */
176    inv = dpct::experimental::select_from_sub_group(
177        0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(), inv,
178        0);
179#pragma unroll
180    for (int64_t c = lane; c < cols; c += 32)
181        r[c] = (w ? r[c] * w[c] : r[c]) * inv;
182}
183
184void sync_if_needed(void *stream, const char *what) try {
185    if (stream != nullptr) return;
186    const dpct::err0 e =
187        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
188}
189catch (sycl::exception const &exc) {
190  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
191            << ", line:" << __LINE__ << std::endl;
192  std::exit(1);
193}
194
195bool check_launch(const char* what) {
196    /*
197    DPCT1010: SYCL uses exceptions to report errors and does not use the
198    error codes. The cudaGetLastError function call was replaced with 0. You
199    need to rewrite this code.
200    */
201    const dpct::err0 e = 0;
202
203    return true;
204}
205
206}  // namespace
207
208void embedding_gather(const uint8_t* codes, const float* scales, const float* offsets,
209                      int64_t n, int code_bits, int code_bias, int group_elems,
210                      float* out, void* stream) {
211    if (n <= 0) return;
212    {
213        auto exp_props = sycl::ext::oneapi::experimental::properties{
214            sycl::ext::oneapi::experimental::use_root_sync};
215
216        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
217            ->template parallel_for<
218                dpct_kernel_name<class embedding_gather_kernel_40b387>>(
219                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
220                                      sycl::range(1, 1, THREADS),
221                                  sycl::range(1, 1, THREADS)),
222                exp_props, [=](sycl::nd_item<3> item_ct1) {
223                    embedding_gather_kernel(codes, scales, offsets, n,
224                                            code_bits, code_bias, group_elems,
225                                            out);
226                });
227    }
228    check_launch("embedding_gather");
229}
230
231void gdn_gate(const float* alpha, const float* dt, const float* ssm_a, float* gate, int64_t n_tokens,
232              int64_t h_v, void* stream) {
233    if (n_tokens <= 0 || h_v <= 0) return;
234    const int64_t n = n_tokens * h_v;
235    {
236        auto exp_props = sycl::ext::oneapi::experimental::properties{
237            sycl::ext::oneapi::experimental::use_root_sync};
238
239        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
240            ->template parallel_for<dpct_kernel_name<class gdn_gate_kernel_de22c0>>(
241                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
242                                      sycl::range(1, 1, THREADS),
243                                  sycl::range(1, 1, THREADS)),
244                exp_props, [=](sycl::nd_item<3> item_ct1) {
245                    gdn_gate_kernel(alpha, dt, ssm_a, gate, h_v);
246                });
247    }
248    check_launch("gdn_gate");
249    sync_if_needed(stream, "gdn_gate");
250}
251
252void scale_inplace(float* x, int64_t n, float s, void* stream) {
253    if (n <= 0) return;
254    {
255        auto exp_props = sycl::ext::oneapi::experimental::properties{
256            sycl::ext::oneapi::experimental::use_root_sync};
257
258        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
259            ->template parallel_for<dpct_kernel_name<class scale_kernel_501571>>(
260                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
261                                      sycl::range(1, 1, THREADS),
262                                  sycl::range(1, 1, THREADS)),
263                exp_props, [=](sycl::nd_item<3> item_ct1) {
264                    scale_kernel(x, n, s);
265                });
266    }
267    check_launch("scale_inplace");
268    sync_if_needed(stream, "scale_inplace");
269}
270
271void add_inplace(float* dst, const float* src, int64_t n, void* stream) {
272    if (n <= 0) return;
273    {
274        auto exp_props = sycl::ext::oneapi::experimental::properties{
275            sycl::ext::oneapi::experimental::use_root_sync};
276
277        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
278            ->template parallel_for<dpct_kernel_name<class add_kernel_95886e>>(
279                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
280                                      sycl::range(1, 1, THREADS),
281                                  sycl::range(1, 1, THREADS)),
282                exp_props, [=](sycl::nd_item<3> item_ct1) {
283                    add_kernel(dst, src, n);
284                });
285    }
286    check_launch("add_inplace");
287    sync_if_needed(stream, "add_inplace");
288}
289
290void f32_to_f16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) {
291    if (n <= 0) return;
292    {
293        auto exp_props = sycl::ext::oneapi::experimental::properties{
294            sycl::ext::oneapi::experimental::use_root_sync};
295
296        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
297            ->template parallel_for<dpct_kernel_name<class to_f16_kernel_ba0968>>(
298                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
299                                      sycl::range(1, 1, THREADS),
300                                  sycl::range(1, 1, THREADS)),
301                exp_props, [=](sycl::nd_item<3> item_ct1) {
302                    to_f16_kernel(x, y, n);
303                });
304    }
305    check_launch("f32_to_f16_bulk");
306    sync_if_needed(stream, "f32_to_f16_bulk");
307}
308
309void f32_to_bf16_bulk(const float* x, uint16_t* y, int64_t n, void* stream) {
310    if (n <= 0) return;
311    {
312        auto exp_props = sycl::ext::oneapi::experimental::properties{
313            sycl::ext::oneapi::experimental::use_root_sync};
314
315        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
316            ->template parallel_for<dpct_kernel_name<class to_bf16_kernel_7b22d1>>(
317                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
318                                      sycl::range(1, 1, THREADS),
319                                  sycl::range(1, 1, THREADS)),
320                exp_props, [=](sycl::nd_item<3> item_ct1) {
321                    to_bf16_kernel(x, y, n);
322                });
323    }
324    check_launch("f32_to_bf16_bulk");
325    sync_if_needed(stream, "f32_to_bf16_bulk");
326}
327
328void silu_inplace(float* x, int64_t n, void* stream) {
329    if (n <= 0) return;
330    {
331        auto exp_props = sycl::ext::oneapi::experimental::properties{
332            sycl::ext::oneapi::experimental::use_root_sync};
333        dpct::has_capability_or_fail(
334            strata::q_of(stream)->get_device(),
335            {sycl::aspect::fp64});
336
337        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
338            ->template parallel_for<dpct_kernel_name<class silu_kernel_4d1386>>(
339                sycl::nd_range<3>(sycl::range(1, 1, grid_for(n)) *
340                                      sycl::range(1, 1, THREADS),
341                                  sycl::range(1, 1, THREADS)),
342                exp_props, [=](sycl::nd_item<3> item_ct1) {
343                    silu_kernel(x, n);
344                });
345    }
346    check_launch("silu_inplace");
347    sync_if_needed(stream, "silu_inplace");
348}
349
350/// THE DOORBELL.  One thread, one INCREMENT - the cost is the launch, and inside a graph that is paid once.
351///
352/// **IT INCREMENTS THE MEMORY, AND IT DOES NOT TAKE THE VALUE AS AN ARGUMENT.**  The first version did -
353/// doorbell_ring(d_seq, *(h_seq) + 1u) - and that is a CLONED LITERAL: the expression is evaluated on the HOST
354/// at CAPTURE time, so the graph rings 1 on every replay and a host waiting for a change waits forever.  It
355/// would have looked like a working doorbell on the first token, which is the worst way for it to be wrong.
356/// **THE FENCE IS NOT DECORATION, AND ITS ABSENCE WAS COSTING ~10 ms PER TOKEN ON THE HOST SIDE.**
357///
358/// The ring PUBLISHES three buffers the host is about to read - `h_x_f`, `h_ids`, `h_weights` - so the increment
359/// must be ordered after their writes, or the host can observe the ring and then read a payload that has not
360/// landed.  `__threadfence_system()` is what orders them, and it covers the HOST as well as the device, which is
361/// the whole point: the reader is the CPU.
362///
363/// Without it the host loop was compensating with a driver call.  `session_loop` polled with `cudaEventQuery`
364/// on EVERY spin iteration, because round 195 had measured that a memory-only spin never saw the datum flip -
365/// and that measurement was right about the symptom and wrong about the cause.  The cause is this missing fence:
366/// the write was not ordered into host-visible memory, so no amount of reading it would show it, and the driver
367/// call was flushing the whole pipeline enough to make it appear.  A 10-22 us driver call per iteration is a
368/// very expensive substitute for one fence instruction.
369///
370/// **THE STORE IS VOLATILE**, like `doorbell_publish_kernel`'s.  On RDNA4 (gfx1201) a plain store to mapped pinned
371/// memory stays in the GPU's L2 until the stream is synchronized - the host never saw the ring (tests/hip/handoff:
372/// 0 of 100 rings seen without a sync; volatile, a system-scope atomic store or a fence after the store: 100 of 100).
373__dpct_inline__ void doorbell_ring_kernel(uint32_t *seq) {
374    /*
375    DPCT1078: Consider replacing memory_order::acq_rel with
376    memory_order::seq_cst for correctness if strong memory order restrictions
377    are needed.
378    */
379    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system);
380    strata::sys_store(seq, strata::sys_load(seq) + 1u);
381#if defined(__HIPCC__)  // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs
382    __threadfence_system();
383#endif
384}
385
386__dpct_inline__ void doorbell_wait_kernel(const volatile uint32_t *flag,
387                                          const volatile uint32_t *seq, uint32_t spin_max) {
388    const uint32_t want = strata::sys_load(seq);
389    for (uint32_t spin = 0; spin < spin_max && strata::sys_load(flag) != want; ++spin) strata_spin_pause();
390    /*
391    DPCT1078: Consider replacing memory_order::acq_rel with
392    memory_order::seq_cst for correctness if strong memory order restrictions
393    are needed.
394    */
395    sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::system);
396}
397
398void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream) {
399    if (d_flag == nullptr || d_seq == nullptr) return;
400    const uint32_t spin_max = strata::spin_max(*strata::q_of(stream));
401    {
402        auto exp_props = sycl::ext::oneapi::experimental::properties{
403            sycl::ext::oneapi::experimental::use_root_sync};
404
405        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
406            ->template parallel_for<dpct_kernel_name<class doorbell_wait_kernel_47b360>>(
407                sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),
408                exp_props, [=](sycl::nd_item<3> item_ct1) {
409                    doorbell_wait_kernel(d_flag, d_seq, spin_max);
410                });
411    }
412    check_launch("doorbell_wait");
413}
414
415/*
416DPCT1052: SYCL does not support the member access for a volatile qualified
417vector type. The volatile qualifier was removed. You may need to rewrite the
418code.
419*/
420__dpct_inline__ void copy_from_mapped_kernel(sycl::float4 *__restrict__ dst,
421                                             const sycl::float4 *src,
422                                             int64_t n4) {
423    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
424    for (int64_t i =
425             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
426             item_ct1.get_local_id(2);
427         i < n4; i += (int64_t)item_ct1.get_group_range(2) *
428                      item_ct1.get_local_range(2)) {
429        const sycl::float4 v = strata::load_mapped_float4(src + i);
430        dst[i] = v;
431    }
432}
433
434// the CPU rows of a verify window, skipping the rows the GPU plan computes itself (the
435// pool writes +0.0 into those, so this writes +0.0 too): block = row, the plan's hit rows `dst[0, *count)`.
436/*
437DPCT1052: SYCL does not support the member access for a volatile qualified
438vector type. The volatile qualifier was removed. You may need to rewrite the
439code.
440*/
441__dpct_inline__ void copy_rows_from_mapped_kernel(
442    sycl::float4 *__restrict__ dst, const sycl::float4 *src, int64_t row4,
443    const int32_t *__restrict__ hit_rows, const int32_t *__restrict__ count) {
444    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
445    const int row = item_ct1.get_group(2);
446    auto &hit = *sycl::ext::oneapi::group_local_memory_for_overwrite<int>(
447        sycl::ext::oneapi::this_work_item::get_work_group<3>());
448    if (item_ct1.get_local_id(2) == 0) {
449        int h = 0;
450        const int c = *count;
451#pragma unroll
452        for (int i = 0; i < c; ++i) h |= hit_rows[i] == row;
453        hit = h;
454    }
455    item_ct1.barrier(sycl::access::fence_space::local_space);
456    sycl::float4 *d = dst + (int64_t)row * row4;
457    if (hit) {
458#pragma unroll
459        for (int64_t i = item_ct1.get_local_id(2); i < row4;
460             i += item_ct1.get_local_range(2))
461            d[i] = sycl::float4(0.0f, 0.0f, 0.0f, 0.0f);
462    } else {
463        /*
464        DPCT1052: SYCL does not support the member access for a volatile
465        qualified vector type. The volatile qualifier was removed. You may need
466        to rewrite the code.
467        */
468        const sycl::float4 *sr = src + (int64_t)row * row4;
469#pragma unroll
470        for (int64_t i = item_ct1.get_local_id(2); i < row4;
471             i += item_ct1.get_local_range(2))
472            d[i] = strata::load_mapped_float4(sr + i);
473    }
474}
475namespace {
476__dpct_inline__ void scatter_rows_kernel(const sycl::float4 *__restrict__ src,
477                                         sycl::float4 *dst,
478                                         const int32_t *__restrict__ rows,
479                                         int64_t w4) {
480    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
481    const int64_t r = item_ct1.get_group(2);
482    const sycl::float4 *s = src + r * w4;
483    sycl::float4 *d = dst + (int64_t)rows[r] * w4;
484#pragma unroll
485    for (int64_t i = item_ct1.get_local_id(2); i < w4;
486         i += item_ct1.get_local_range(2)) d[i] = s[i];
487}
488}  // namespace
489void scatter_rows_f32(const float* src, float* dst, const int32_t* rows, int64_t n, int64_t width, void* stream) {
490    if (n <= 0) return;
491    if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
492        std::fprintf(stderr, "scatter_rows_f32: width must be a multiple of 4 and both pointers 16-byte aligned\n");
493        std::exit(1);
494    }
495    {
496        auto exp_props = sycl::ext::oneapi::experimental::properties{
497            sycl::ext::oneapi::experimental::use_root_sync};
498
499        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
500            ->submit([&](sycl::handler &cgh) {
501                auto width_ct3 = width / 4;
502
503                cgh.parallel_for<
504                    dpct_kernel_name<class scatter_rows_kernel_7d83a1>>(
505                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n) *
506                                          sycl::range(1, 1, 128),
507                                      sycl::range(1, 1, 128)),
508                    exp_props, [=](sycl::nd_item<3> item_ct1) {
509                        scatter_rows_kernel((const sycl::float4 *)src,
510                                            (sycl::float4 *)dst, rows,
511                                            width_ct3);
512                    });
513            });
514    }
515}
516void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,
517                           const int32_t* count, void* stream) {
518    if (rows <= 0) return;
519    if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
520        std::fprintf(stderr, "copy_rows_from_mapped: width must be a multiple of 4 and both pointers 16-byte aligned\n");
521        std::exit(1);
522    }
523    {
524        auto exp_props = sycl::ext::oneapi::experimental::properties{
525            sycl::ext::oneapi::experimental::use_root_sync};
526
527        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
528            ->submit([&](sycl::handler &cgh) {
529                auto width_ct2 = width / 4;
530
531                cgh.parallel_for<dpct_kernel_name<
532                    class copy_rows_from_mapped_kernel_9530d4>>(
533                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)rows) *
534                                          sycl::range(1, 1, 128),
535                                      sycl::range(1, 1, 128)),
536                    exp_props, [=](sycl::nd_item<3> item_ct1) {
537                        copy_rows_from_mapped_kernel(
538                            (sycl::float4 *)dst,
539                            (const sycl::float4 *)src, width_ct2,
540                            hit_rows, count);
541                    });
542            });
543    }
544}
545void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream) {
546    if (n <= 0) return;
547    if ((n & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
548        std::fprintf(stderr, "copy_from_mapped: n must be a multiple of 4 and both pointers 16-byte aligned\n");
549        std::exit(1);
550    }
551    const int64_t n4 = n / 4;
552    const int blocks = (int) ((n4 + 255) / 256 < 64 ? (n4 + 255) / 256 : 64);
553    {
554        auto exp_props = sycl::ext::oneapi::experimental::properties{
555            sycl::ext::oneapi::experimental::use_root_sync};
556
557        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
558            ->template parallel_for<
559                dpct_kernel_name<class copy_from_mapped_kernel_82951a>>(
560                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
561                                      sycl::range(1, 1, 256),
562                                  sycl::range(1, 1, 256)),
563                exp_props, [=](sycl::nd_item<3> item_ct1) {
564                    copy_from_mapped_kernel((sycl::float4 *)dst,
565                                            (const sycl::float4 *)src,
566                                            n4);
567                });
568    }
569    check_launch("copy_from_mapped");
570}
571
572namespace {
573// The published payload's checksum: the wrapping sum of every 32-bit word mixed with its position (murmur3's
574// finalizer).  A plain sum of the words missed a reordering ([3, 7] -> [7, 3] in the expert ids) and cancelling
575// changes; mixed, a stale payload passes only with a chance near 2^-32 per read.  It detects; it does not order -
576// the host keeps reading until the payload it sees matches (doorbell_payload_ready).  Positions: x 0..n-1,
577// ids n..n+k-1, weights n+k..n+2k-1.
578inline uint32_t dbx_payload_mix(uint32_t word, uint32_t pos) {
579    uint32_t h = word ^ (pos * 0x9E3779B9u);
580    h ^= h >> 16; h *= 0x85EBCA6Bu; h ^= h >> 13; h *= 0xC2B2AE35u; h ^= h >> 16;
581    return h;
582}
583inline uint32_t dbx_payload_sum(const float* x, int64_t n, const int32_t* ids, const float* w, int64_t k,
584                                bool has_weights) {
585    uint32_t s = 0;
586    for (int64_t j = 0; j < n; ++j) s += dbx_payload_mix(sycl::bit_cast<uint32_t>(x[j]), (uint32_t) j);
587    for (int64_t j = 0; j < k; ++j) s += dbx_payload_mix((uint32_t) ids[j], (uint32_t) (n + j));
588    if (has_weights)
589        for (int64_t j = 0; j < k; ++j) s += dbx_payload_mix(sycl::bit_cast<uint32_t>(w[j]), (uint32_t) (n + k + j));
590    return s;
591}
592// STRATA_SYCL_A770_FAST=1 (opt-in): pair the activation stores without changing the checksum's word/position
593// order. Odd sizes or unaligned mapped pointers retain the scalar path.
594__dpct_inline__ uint32_t dbx_publish_x(const float* x, float* out, int n, int lane, int threads, bool pair, bool plain) {
595    uint32_t part = 0;
596    if (pair && !plain && ((uintptr_t)out & 7u) == 0) {
597        for (int j = 2 * lane; j + 1 < n; j += 2 * threads) {
598            const uint32_t a = sycl::bit_cast<uint32_t>(x[j]);
599            const uint32_t b = sycl::bit_cast<uint32_t>(x[j + 1]);
600            strata::sys_store_mapped(reinterpret_cast<uint64_t*>(out + j),
601                                     (uint64_t)a | ((uint64_t)b << 32));
602            part += dbx_payload_mix(a, (uint32_t)j) + dbx_payload_mix(b, (uint32_t)(j + 1));
603        }
604        if ((n & 1) && lane == 0) {
605            strata::sys_store_mapped(plain, out + n - 1, x[n - 1]);
606            part += dbx_payload_mix(sycl::bit_cast<uint32_t>(x[n - 1]), (uint32_t)(n - 1));
607        }
608    } else {
609        for (int j = lane; j < n; j += threads) {
610            strata::sys_store_mapped(plain, out + j, x[j]);
611            part += dbx_payload_mix(sycl::bit_cast<uint32_t>(x[j]), (uint32_t)j);
612        }
613    }
614    return part;
615}
616// The ring, its tag and its checksum, in slot r % 4 of the sequence word (elementwise.hpp).  Written last, after a
617// system fence over the uncached payload stores.
618__dpct_inline__ void dbx_ring_commit(uint32_t* seq, uint32_t part, bool group_ok, uint32_t ring) {
619#if defined(__HIPCC__)  // #697: HIP only; on RDNA4 the volatile store alone can sit in L2 until the stream syncs
620    (void) group_ok;
621#endif
622    if (group_ok) {
623        strata::sys_store(seq + 2 + 2 * (ring % 4), part);
624        strata::sys_store(seq + 1 + 2 * (ring % 4), ring);
625        sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system);
626        strata::sys_store(seq, ring);
627    }
628}
629// The payload store (strata::sys_store_mapped(plain, ...)): uncached (sycl_doorbell.hpp) so a host that polls the ring while the kernel still runs reads a
630// whole payload, or a plain store when every reader waits for the kernel to end (doorbell_plain_payload: the stepped
631// verify window reads a segment's payload only after the segment has drained, and the end of a kernel makes its
632// stores visible). The host checksum (doorbell_payload_ready) still guards every read.
633std::atomic<bool> g_plain_payload{false};
634}  // namespace
635
636void doorbell_plain_payload(bool on) { g_plain_payload.store(on, std::memory_order_relaxed); }
637
638__dpct_inline__ void doorbell_publish_kernel(const float *__restrict__ x,
639                                             const int32_t *__restrict__ ids,
640                                             const float *__restrict__ w, int n,
641                                             int k, float *x_out,
642                                             int32_t *ids_out, float *w_out,
643                                             uint32_t *seq, bool plain, bool pair) {
644    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
645    const int i = (int) item_ct1.get_local_id(2);
646    const int nt = (int) item_ct1.get_local_range(2);
647    uint32_t part = dbx_publish_x(x, x_out, n, i, nt, pair, plain);
648    if (i < k) {
649        const int32_t id = ids[i];
650        strata::sys_store_mapped(plain, ids_out + i, id);
651        part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i));
652        if (w_out != nullptr) {
653            const float wv = w[i];
654            strata::sys_store_mapped(plain, w_out + i, wv);
655            part += dbx_payload_mix(sycl::bit_cast<uint32_t>(wv), (uint32_t) (n + k + i));
656        }
657    }
658    const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus<uint32_t>());
659    sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system);
660    item_ct1.barrier();
661    if (i == 0) {
662        const uint32_t next = strata::sys_load(seq) + 1u;
663        dbx_ring_commit(seq, sum, true, next);
664    }
665}
666
667__dpct_inline__ void doorbell_publish_res_kernel(
668    const float *__restrict__ x, const int32_t *__restrict__ ids,
669    const int32_t *__restrict__ d_res, int n_expert, int n, int k, float *x_out,
670    int32_t *ids_out, uint32_t *seq, bool full, bool plain, bool pair) {
671    // full (STRATA_DOORBELL_CHECK=1): the payload is published whole and the checksum covers x and the ids (this
672    // variant publishes no weights). Otherwise d_res/n_expert decide whether x is copied, as before the checksum:
673    // when every routed expert is resident the host never reads x, and an uncached copy of it costs the A750 ~10%
674    // of decode.
675    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
676    if (!full) {
677        int any_miss = 0;
678        if ((int) item_ct1.get_local_id(2) < k) {
679            const int32_t id = ids[item_ct1.get_local_id(2)];
680            strata::sys_store_mapped(plain, ids_out + item_ct1.get_local_id(2), id);
681            if (d_res == nullptr || id < 0 || id >= n_expert || d_res[id] < 0) any_miss = 1;
682        }
683        if ((item_ct1.barrier(), sycl::any_of_group(sycl::ext::oneapi::this_work_item::get_work_group<3>(), any_miss))) {
684            for (int j = (int) item_ct1.get_local_id(2); j < n; j += (int) item_ct1.get_local_range(2))
685                strata::sys_store_mapped(plain, x_out + j, x[j]);
686        }
687        sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system);
688        item_ct1.barrier();
689        if (item_ct1.get_local_id(2) == 0) {
690            const uint32_t next = strata::sys_load(seq) + 1u;
691            dbx_ring_commit(seq, 0u, true, next);
692        }
693        return;
694    }
695    const int i = (int) item_ct1.get_local_id(2);
696    const int nt = (int) item_ct1.get_local_range(2);
697    uint32_t part = dbx_publish_x(x, x_out, n, i, nt, pair, plain);
698    if (i < k) {
699        const int32_t id = ids[i];
700        strata::sys_store_mapped(plain, ids_out + i, id);
701        part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i));
702    }
703    const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus<uint32_t>());
704    sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system);
705    item_ct1.barrier();
706    if (i == 0) {
707        const uint32_t next = strata::sys_load(seq) + 1u;
708        dbx_ring_commit(seq, sum, true, next);
709    }
710}
711
712// #649 (HIP, STRATA_DOORBELL_STORE=1): the same publish, but the ring is STORED (the step's own number, known at
713// capture) instead of read-modify-written over PCIe - one store, no read of host memory from the GPU.
714__dpct_inline__ void doorbell_publish_value_kernel(
715    const float *__restrict__ x, const int32_t *__restrict__ ids,
716    const float *__restrict__ w, int n, int k, float *x_out, int32_t *ids_out,
717    float *w_out, uint32_t *seq, uint32_t value, bool plain, bool pair) {
718    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
719    const int i = (int) item_ct1.get_local_id(2);
720    const int nt = (int) item_ct1.get_local_range(2);
721    uint32_t part = dbx_publish_x(x, x_out, n, i, nt, pair, plain);
722    if (i < k) {
723        const int32_t id = ids[i];
724        strata::sys_store_mapped(plain, ids_out + i, id);
725        part += dbx_payload_mix((uint32_t) id, (uint32_t) (n + i));
726        const float wv = w[i];
727        strata::sys_store_mapped(plain, w_out + i, wv);
728        part += dbx_payload_mix(sycl::bit_cast<uint32_t>(wv), (uint32_t) (n + k + i));
729    }
730    const uint32_t sum = sycl::reduce_over_group(item_ct1.get_group(), part, sycl::plus<uint32_t>());
731    sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::system);
732    item_ct1.barrier();
733    if (i == 0) dbx_ring_commit(seq, sum, true, value);
734}
735
736void doorbell_publish_value(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k,
737                            float* x_out, int32_t* ids_out, float* weights_out, uint32_t* d_seq, uint32_t value,
738                            void* stream) {
739    if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); }
740    const bool plain = strata::doorbell_plain_payload() || g_plain_payload.load(std::memory_order_relaxed);
741    const bool pair = strata::a770_fast();
742    /*
743    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
744    limit. To get the device limit, query info::device::max_work_group_size.
745    Adjust the work-group size if needed.
746    */
747    {
748        auto exp_props = sycl::ext::oneapi::experimental::properties{
749            sycl::ext::oneapi::experimental::use_root_sync};
750
751        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
752            ->template parallel_for<
753                dpct_kernel_name<class doorbell_publish_value_kernel_9bdb22>>(
754                sycl::nd_range<3>(sycl::range(1, 1, 1024),
755                                  sycl::range(1, 1, 1024)),
756                exp_props, [=](sycl::nd_item<3> item_ct1) {
757                    doorbell_publish_value_kernel(x, ids, weights, (int)n,
758                                                  (int)k, x_out, ids_out,
759                                                  weights_out, d_seq, value, plain, pair);
760                });
761    }
762}
763
764void doorbell_publish(const float* x, const int32_t* ids, const float* weights, int64_t n, int64_t k, float* x_out,
765                      int32_t* ids_out, float* weights_out, uint32_t* d_seq, void* stream) {
766    if (k > 1024) { std::fprintf(stderr, "doorbell_publish: k too large\n"); std::exit(1); }
767    const bool plain = strata::doorbell_plain_payload() || g_plain_payload.load(std::memory_order_relaxed);
768    const bool pair = strata::a770_fast();
769    /*
770    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
771    limit. To get the device limit, query info::device::max_work_group_size.
772    Adjust the work-group size if needed.
773    */
774    {
775        auto exp_props = sycl::ext::oneapi::experimental::properties{
776            sycl::ext::oneapi::experimental::use_root_sync};
777
778        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
779            ->template parallel_for<
780                dpct_kernel_name<class doorbell_publish_kernel_8b5bad>>(
781                sycl::nd_range<3>(sycl::range(1, 1, 1024),
782                                  sycl::range(1, 1, 1024)),
783                exp_props, [=](sycl::nd_item<3> item_ct1) {
784                    doorbell_publish_kernel(x, ids, weights, (int)n, (int)k,
785                                            x_out, ids_out, weights_out, d_seq, plain, pair);
786                });
787    }
788    check_launch("doorbell_publish");
789}
790
791void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_res, int n_expert, int64_t n, int64_t k,
792                          float* x_out, int32_t* ids_out, uint32_t* d_seq, void* stream) {
793    if (k > 1024) { std::fprintf(stderr, "doorbell_publish_res: k too large\n"); std::exit(1); }
794    static const bool full = [] { const char* v = std::getenv("STRATA_DOORBELL_CHECK"); return v != nullptr && v[0] == '1'; }();
795    const bool fl = full;
796    const bool plain = strata::doorbell_plain_payload() || g_plain_payload.load(std::memory_order_relaxed);
797    const bool pair = strata::a770_fast();
798    /*
799    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
800    limit. To get the device limit, query info::device::max_work_group_size.
801    Adjust the work-group size if needed.
802    */
803    {
804        auto exp_props = sycl::ext::oneapi::experimental::properties{
805            sycl::ext::oneapi::experimental::use_root_sync};
806
807        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
808            ->template parallel_for<
809                dpct_kernel_name<class doorbell_publish_res_kernel_85b9b3>>(
810                sycl::nd_range<3>(sycl::range(1, 1, 1024),
811                                  sycl::range(1, 1, 1024)),
812                exp_props, [=](sycl::nd_item<3> item_ct1) {
813                    doorbell_publish_res_kernel(x, ids, d_res, n_expert, (int)n,
814                                                (int)k, x_out, ids_out, d_seq, fl, plain, pair);
815                });
816    }
817    check_launch("doorbell_publish_res");
818}
819
820bool doorbell_payload_ready(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids,
821                            const float* h_weights, int64_t k, uint32_t want) {
822    const volatile uint32_t* w = h_seq + 1 + 2 * (want % 4);   // this ring's tag and checksum (elementwise.hpp)
823    if (w[0] != want) return false;
824    std::atomic_thread_fence(std::memory_order_acquire);
825    // the two publish shapes: with the routing weights (doorbell_publish / _value) or without (doorbell_publish_res)
826    return dbx_payload_sum(h_x, n, h_ids, h_weights, k, true) == w[1] ||
827           dbx_payload_sum(h_x, n, h_ids, h_weights, k, false) == w[1];
828}
829
830bool doorbell_wait_payload(const uint32_t* h_seq, const float* h_x, int64_t n, const int32_t* h_ids,
831                           const float* h_weights, int64_t k, uint32_t want, int timeout_ms) {
832    // Opt-in (STRATA_DOORBELL_CHECK=1): on an Arc A750 (i915) the host-side checksum of the whole payload, read from
833    // uncached host memory twice per CPU-expert layer, cost 15-20% of decode (5 interleaved rounds), and the stale
834    // payload it guards against was not seen there. The ring tag is still published by the GPU.
835    static const bool check = [] { const char* v = std::getenv("STRATA_DOORBELL_CHECK"); return v != nullptr && v[0] == '1'; }();
836    if (!check) return true;
837    if (doorbell_payload_ready(h_seq, h_x, n, h_ids, h_weights, k, want)) return true;
838    const auto t0 = std::chrono::steady_clock::now();
839    while (!doorbell_payload_ready(h_seq, h_x, n, h_ids, h_weights, k, want)) {
840        for (int i = 0; i < 64; ++i) __builtin_ia32_pause();
841        if (std::chrono::steady_clock::now() - t0 > std::chrono::milliseconds(timeout_ms)) return false;
842    }
843    return true;
844}
845
846__dpct_inline__ void copy_i32_from_mapped_kernel(int32_t *__restrict__ dst,
847                                                 const volatile int32_t *src,
848                                                 int n) {
849    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
850#pragma unroll
851    for (int i = item_ct1.get_local_id(2); i < n;
852         i += item_ct1.get_local_range(2)) dst[i] = src[i];
853}
854
855#if !defined(__HIPCC__)
856struct MappedCopies {
857    MappedCopy c[8];
858};
859
860__dpct_inline__ void copy_from_mapped_multi_kernel(MappedCopies a) {
861    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
862    const MappedCopy c = a.c[item_ct1.get_group(1)];
863    const int64_t i0 = (int64_t)item_ct1.get_group(2) *
864                           item_ct1.get_local_range(2) +
865                       item_ct1.get_local_id(2),
866                  st = (int64_t)item_ct1.get_group_range(2) *
867                       item_ct1.get_local_range(2);
868    if ((c.words & 3) == 0 && ((uintptr_t) c.dst & 15) == 0 && ((uintptr_t) c.src & 15) == 0) {
869        /*
870        DPCT1052: SYCL does not support the member access for a volatile
871        qualified vector type. The volatile qualifier was removed. You may need
872        to rewrite the code.
873        */
874        const sycl::float4 *s = (const sycl::float4 *)c.src;
875#pragma unroll
876        for (int64_t i = i0; i < c.words / 4; i += st)(
877            (sycl::float4 *)c.dst)[i] = const_cast<const sycl::float4 *>(s)[i];
878    } else {
879        const volatile int32_t* s = (const volatile int32_t*) c.src;
880#pragma unroll
881        for (int64_t i = i0; i < c.words; i += st)((int32_t *)c.dst)[i] = s[i];
882    }
883}
884
885void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {
886    if (n <= 0) return;
887    if (n > 8) { std::fprintf(stderr, "copy_from_mapped_multi: at most 8 copies\n"); std::exit(1); }
888    MappedCopies a;
889    int64_t most = 0;
890    for (int i = 0; i < n; ++i) {
891        a.c[i] = copies[i];
892        most = copies[i].words > most ? copies[i].words : most;
893    }
894    const int64_t units = (most + 3) / 4;
895    const unsigned bx = (unsigned) ((units + 255) / 256 < 32 ? (units + 255) / 256 : 32);
896    {
897        auto exp_props = sycl::ext::oneapi::experimental::properties{
898            sycl::ext::oneapi::experimental::use_root_sync};
899
900        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
901            ->template parallel_for<
902                dpct_kernel_name<class copy_from_mapped_multi_kernel_66c71e>>(
903                sycl::nd_range<3>(sycl::range(1, (unsigned)n, bx < 1 ? 1 : bx) *
904                                      sycl::range(1, 1, 256),
905                                  sycl::range(1, 1, 256)),
906                exp_props, [=](sycl::nd_item<3> item_ct1) {
907                    copy_from_mapped_multi_kernel(a);
908                });
909    }
910    check_launch("copy_from_mapped_multi");
911}
912#endif
913
914void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream) {
915    if (n <= 0) return;
916    {
917        auto exp_props = sycl::ext::oneapi::experimental::properties{
918            sycl::ext::oneapi::experimental::use_root_sync};
919
920        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
921            ->template parallel_for<
922                dpct_kernel_name<class copy_i32_from_mapped_kernel_a44acc>>(
923                sycl::nd_range<3>(sycl::range(1, 1, 128),
924                                  sycl::range(1, 1, 128)),
925                exp_props, [=](sycl::nd_item<3> item_ct1) {
926                    copy_i32_from_mapped_kernel(
927                        dst, (const volatile int32_t *)src, (int)n);
928                });
929    }
930    check_launch("copy_i32_from_mapped");
931}
932
933#if defined(__HIPCC__)   // AMD keeps one copy a launch
934void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {
935    for (int i = 0; i < n; ++i)
936        copy_i32_from_mapped((int32_t*) copies[i].dst, (const int32_t*) copies[i].src, copies[i].words, stream);
937}
938#endif
939
940void doorbell_ring(uint32_t* d_seq, void* stream) {
941    if (d_seq == nullptr) return;
942    {
943        auto exp_props = sycl::ext::oneapi::experimental::properties{
944            sycl::ext::oneapi::experimental::use_root_sync};
945
946        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
947            ->template parallel_for<dpct_kernel_name<class doorbell_ring_kernel_b862a4>>(
948                sycl::nd_range<3>(sycl::range(1, 1, 1), sycl::range(1, 1, 1)),
949                exp_props, [=](sycl::nd_item<3> item_ct1) {
950                    doorbell_ring_kernel(d_seq);
951                });
952    }
953    check_launch("doorbell_ring");
954    sync_if_needed(stream, "doorbell_ring");
955}
956
957void rms_norm_weighted(float* x, const float* w, int64_t rows, int64_t cols, float eps, void* stream) {
958    if (rows <= 0 || cols <= 0) return;
959    // 4 warps per block, so a row count that is not a multiple of 4 wastes at most 3 warps rather than
960    // launching a block per row for a 2-row call.
961    const unsigned warps_per_block = 4;
962    const unsigned grid = (unsigned) ((rows + warps_per_block - 1) / warps_per_block);
963    {
964        auto exp_props = sycl::ext::oneapi::experimental::properties{
965            sycl::ext::oneapi::experimental::use_root_sync};
966
967        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
968            ->template parallel_for<
969                dpct_kernel_name<class rms_norm_weighted_kernel_b603f5>>(
970                sycl::nd_range<3>(sycl::range(1, 1, grid) *
971                                      sycl::range(1, 1, warps_per_block * 32),
972                                  sycl::range(1, 1, warps_per_block * 32)),
973                exp_props,
974                [=](sycl::nd_item<3> item_ct1)
975                    [[sycl::reqd_sub_group_size(32)]] {
976                        rms_norm_weighted_kernel(x, w, rows, cols, eps);
977                    });
978    }
979    check_launch("rms_norm_weighted");
980    sync_if_needed(stream, "rms_norm_weighted");
981}
982
983}  // namespace strata::kernels