okami.mom/strata

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

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
45.8 KiB948 linesraw
1// src/kernels/cuda/router_top10.cu - P2.S2: the MoE router.
2//
3// P2.S2's spec: "BF16 GEMV, softmax / top-k / renormalize per docs/semantics.md; emits (expert_id, weight) x 10
4// per token".  This is the softmax/top-k/renormalize half; the BF16 GEMV that produces the logits is a
5// separate kernel and is NOT here.
6//
7// The semantics are transcribed from `ref/moe.py::router`, which is itself transcribed from llama-graph.cpp:
8//
9//     p   = softmax(logits)                       over ALL experts, not over the selected subset
10//     ids = stable argsort(-p)[:k]                ties break by INDEX, ascending
11//     w   = gather(p, ids)
12//     s   = max(sum(w), 2**-14)                   ggml_clamp(..., 2**-14, INF)
13//     return ids, w / s
14//
15// The two-step structure matters and is not cosmetic: computing softmax over the selected subset instead is
16// mathematically identical (softmax is shift-invariant) but it moves the renormalisation, and the CLAMP is
17// part of the renormalisation.  Reproducing the gather form is what makes the clamp land in the same place.
18//
19// WHY THIS IS NO LONGER "NAIVE BY DESIGN", AND WHAT THE OLD REASONING GOT WRONG.
20//
21// The first version was ONE THREAD PER TOKEN: k passes over the experts, each pass recomputing
22// `exp((double) l[e] - mx)` for every expert.  Its comment justified that with
23//
24//     "5,120 operations per token against 2.36e9 weights of expert matvec - three orders of magnitude smaller
25//      than the thing it feeds, so the simplest correct version is also fast enough"
26//
27// **That is a statement about OPERATION COUNT and it says nothing about TIME, because all 5,120 operations were
28// on ONE THREAD while the matvec has thousands.**  Measured (round 218, stage-by-stage inside one block):
29//
30//     moe_layer   4.077 ms      router_top10   3.387 ms      bf16 gemv   0.270 ms
31//
32// 3.39 ms per layer x 48 layers = 163 ms of a 289 ms token - **56% of the whole forward pass, in a kernel that
33// reads 2.6 MB.**  It was invisible in `router_top10_parity` because that test runs the kernel ONCE and checks
34// the right ids, and invisible in every per-layer test for the same reason.
35//
36// WHAT IS PARALLELISED AND WHAT IS DELIBERATELY NOT:
37//
38//   * the MAX is a tree reduction of `fmaxf`, which is exact and order-independent - bit-identical to the
39//     serial scan it replaces;
40//   * the 512 EXPONENTIALS are computed ONCE each, in parallel.  The old kernel computed them ELEVEN TIMES
41//     (once for the softmax, then again inside every one of the k passes).  This is where the 3.4 ms was;
42//   * the DOUBLE SUM is still accumulated on ONE thread in ASCENDING order.  512 double adds is about a
43//     microsecond and it keeps the accumulation order - and therefore the last bits - identical to the
44//     reference-faithful serial version.  Parallelising it would be a free speedup and a silent change to the
45//     values, and the exp was the cost, not this;
46//   * the SELECTION is by RANK rather than by k repeated maxima:
47//
48//         rank(e) = #{ f : p[f] > p[e] }  +  #{ f < e : p[f] == p[e] }
49//
50//     which IS "stable descending argsort, ties by ascending index" - the same order the repeated-maximum loop
51//     produced - computed in ONE parallel pass over the experts instead of k serial ones.  It is O(n^2)
52//     comparisons and that is the right trade here: n = 512, every comparison is independent, and the old
53//     version was O(k*n) with a serial `exp` inside.
54#define DPCT_PROFILING_ENABLED
55#include <sycl/sycl.hpp>
56#include "strata/kprof.hpp"
57#include <dpct/dpct.hpp>
58#include "strata/sycl_queue.hpp"
59#include "strata/sycl_doorbell.hpp"
60#include "strata/kernels/router_top10.hpp"
61
62#include <cmath>
63#include <algorithm>
64#include <cstdio>
65#include <cstdlib>
66#include <mutex>
67#include <utility>
68#include <vector>
69
70namespace strata::kernels {
71namespace {
72
73constexpr int RT_MAX_THREADS = 512;
74
75// The fork's parity-tested SYCL implementation of the HIP fast router below.
76// A tree sum brackets the serial reciprocal; ambiguous rounding falls back to
77// the original ascending sum. Selection and renormalisation stay in subgroup 0.
78template <bool FORCE_SERIAL>
79void launch_sycl_fast(sycl::queue& q, const float* logits, int n_tokens, int n_expert, int k,
80                      int* ids, float* weights) {
81    const int threads = (std::min(n_expert, RT_MAX_THREADS) + 31) & ~31;
82    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
83        sycl::local_accessor<double, 1> s_ex(sycl::range<1>(n_expert), h);
84        sycl::local_accessor<float, 1> s_red(sycl::range<1>(RT_MAX_THREADS / 32), h);
85        sycl::local_accessor<double, 1> s_dred(sycl::range<1>(RT_MAX_THREADS / 32), h);
86        sycl::local_accessor<float, 1> s_inv(sycl::range<1>(1), h);
87        h.parallel_for(sycl::nd_range<1>(sycl::range<1>((size_t)n_tokens * threads),
88                                        sycl::range<1>(threads)),
89            [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(32)]] {
90                const auto sg = it.get_sub_group();
91                const int t = it.get_group(0), tid = it.get_local_id(0);
92                const int lane = tid & 31, warp = tid >> 5;
93                const int nt = it.get_local_range(0), nw = (nt + 31) >> 5;
94                const float* l = logits + (size_t)t * n_expert;
95                auto bar = [&] { sycl::group_barrier(it.get_group()); };
96                float mx = -INFINITY;
97                for (int e = tid; e < n_expert; e += nt) mx = sycl::fmax(mx, l[e]);
98                for (int off = 16; off > 0; off >>= 1)
99                    mx = sycl::fmax(mx, sycl::shift_group_left(sg, mx, off));
100                if (lane == 0) s_red[warp] = mx;
101                bar();
102                if (tid < 32) {
103                    float v = tid < nw ? s_red[tid] : -INFINITY;
104                    for (int off = 16; off > 0; off >>= 1)
105                        v = sycl::fmax(v, sycl::shift_group_left(sg, v, off));
106                    if (tid == 0) s_red[0] = v;
107                }
108                bar();
109                mx = s_red[0];
110                double part = 0.0;
111                for (int e = tid; e < n_expert; e += nt) {
112                    const double x = sycl::exp((double)l[e] - (double)mx);
113                    s_ex[e] = x;
114                    part += x;
115                }
116                for (int off = 16; off > 0; off >>= 1)
117                    part += sycl::permute_group_by_xor(sg, part, off);
118                if (lane == 0) s_dred[warp] = part;
119                bar();
120                double tot = 0.0;
121                for (int w = 0; w < nw; ++w) tot += s_dred[w];
122                const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40);
123                const float f_lo = (float)(1.0 / hi), f_hi = (float)(1.0 / lo);
124                float inv;
125                if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) {
126                    inv = f_lo;
127                } else {
128                    if (tid == 0) {
129                        double sum = 0.0;
130                        for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
131                        s_inv[0] = (float)(1.0 / sum);
132                    }
133                    bar();
134                    inv = s_inv[0];
135                }
136                if (warp != 0) return;
137                constexpr int PER = 16;
138                float pv[PER];
139                unsigned live = 0;
140                for (int j = 0; j < PER; ++j) {
141                    const int e = lane + 32 * j;
142                    pv[j] = -INFINITY;
143                    if (e < n_expert) { pv[j] = (float)(s_ex[e] * inv); live |= 1u << j; }
144                }
145                float my_w = 0.0f;
146                int my_id = 0, nsel = 0;
147                for (int i = 0; i < k; ++i) {
148                    float bv = -INFINITY;
149                    int bi = n_expert;
150                    for (int j = 0; j < PER; ++j)
151                        if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; }
152                    for (int off = 16; off > 0; off >>= 1) {
153                        const float ov = sycl::permute_group_by_xor(sg, bv, off);
154                        const int oi = sycl::permute_group_by_xor(sg, bi, off);
155                        if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
156                    }
157                    if (bi >= n_expert) break;
158                    if ((bi & 31) == lane) live &= ~(1u << (bi >> 5));
159                    if (lane == i) { my_w = bv; my_id = bi; }
160                    nsel = i + 1;
161                }
162                if (nsel == k) {
163                    double s = 0.0;
164                    for (int i = 0; i < k; ++i) s += (double)sycl::select_from_group(sg, my_w, i);
165                    const double sc = sycl::fmax(s, 6.103515625e-05);
166                    if (lane < k) {
167                        ids[(size_t)t * k + lane] = my_id;
168                        weights[(size_t)t * k + lane] = (float)((double)my_w / sc);
169                    }
170                } else {
171                    if (lane < nsel) { ids[(size_t)t * k + lane] = my_id; weights[(size_t)t * k + lane] = my_w; }
172                    sycl::group_barrier(sg);
173                    if (lane == 0) {
174                        double s = 0.0;
175                        for (int i = 0; i < k; ++i) s += (double)weights[(size_t)t * k + i];
176                        const double sc = sycl::fmax(s, 6.103515625e-05);
177                        for (int i = 0; i < k; ++i)
178                            weights[(size_t)t * k + i] = (float)((double)weights[(size_t)t * k + i] / sc);
179                    }
180                }
181            });
182    });
183}
184
185/// One BLOCK per token, so the reductions have somewhere to happen.  `n_tokens` is 1 in decode; the grid keeps
186/// the batch case working without a second code path.
187/*
188DPCT1110: The total declared local variable size in device function
189router_top10_kernel exceeds 128 bytes and may cause high register pressure.
190Consult with your hardware vendor to find the total register size available and
191adjust the code, or use smaller sub-group size to avoid high register pressure.
192*/
193__dpct_inline__ void router_top10_kernel(const float *__restrict__ logits,
194                                         int n_tokens, int n_expert, int k,
195                                         int *__restrict__ ids,
196                                         float *__restrict__ weights,
197                                         uint8_t *dpct_local) {
198    // **`s_taken` IS FIRST SO THE OTHER TWO KEEP THEIR ALIGNMENT WITHOUT AN OFFSET PARAMETER**, and `s_p`'s
199    // existing `s_ex + n_expert` stays correct because it is relative to `s_ex`.  One byte per expert.
200    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
201    auto s_raw = (unsigned char *)dpct_local;
202    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
203    unsigned char* s_taken = s_raw;
204    double* s_ex = (double*) (s_raw + taken_bytes);
205    auto &s_red = *sycl::ext::oneapi::group_local_memory_for_overwrite<
206        float[RT_MAX_THREADS / 32]>(
207        sycl::ext::oneapi::this_work_item::get_work_group<3>());
208    auto &s_rid = *sycl::ext::oneapi::group_local_memory_for_overwrite<
209        int[RT_MAX_THREADS / 32]>(
210        sycl::ext::oneapi::this_work_item::get_work_group<3>());
211    auto &s_sum = *sycl::ext::oneapi::group_local_memory_for_overwrite<double>(
212        sycl::ext::oneapi::this_work_item::get_work_group<3>());
213
214    const int t = item_ct1.get_group(2);
215    if (t >= n_tokens) return;
216    const int tid = item_ct1.get_local_id(2);
217    const int nt = item_ct1.get_local_range(2);
218    const float* l = logits + (size_t) t * n_expert;
219
220    // ---- softmax over ALL experts, for stability: the max.  A tree of `fmaxf` is EXACT and order-independent,
221    // so this is bit-identical to the serial scan.
222    float mx = -INFINITY;
223#pragma unroll
224    for (int e = tid; e < n_expert; e += nt) mx = sycl::fmax(mx, l[e]);
225    /*
226DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
227masked sub_group function which may not be supported by all compilers or
228runtimes. You may need to adjust the code.
229*/
230#pragma unroll
231    for (int off = 16; off > 0; off >>= 1) mx = sycl::fmax(
232        mx, dpct::experimental::shift_sub_group_left(
233                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
234                mx, off));
235    if ((tid & 31) == 0) s_red[tid >> 5] = mx;
236    /*
237    DPCT1065: Consider replacing sycl::nd_item::barrier() with
238    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
239    performance if there is no access to global memory.
240    */
241    item_ct1.barrier();
242    if (tid < 32) {
243        const int nw = (nt + 31) >> 5;
244        float v = (tid < nw) ? s_red[tid] : -INFINITY;
245        /*
246DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
247masked sub_group function which may not be supported by all compilers or
248runtimes. You may need to adjust the code.
249*/
250#pragma unroll
251        for (int off = 16; off > 0; off >>= 1) v = sycl::fmax(
252            v, dpct::experimental::shift_sub_group_left(
253                   0xffffffffu,
254                   sycl::ext::oneapi::this_work_item::get_sub_group(), v, off));
255        if (tid == 0) s_red[0] = v;
256    }
257    /*
258    DPCT1065: Consider replacing sycl::nd_item::barrier() with
259    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
260    performance if there is no access to global memory.
261    */
262    item_ct1.barrier();
263    mx = s_red[0];
264
265    // ---- THE 512 EXPONENTIALS, ONCE EACH AND IN PARALLEL.  `exp` in double is software-emulated on this die
266    // and was 5,632 serial calls before; it is 512 parallel ones now.
267#pragma unroll
268    for (int e = tid; e < n_expert; e += nt)
269        s_ex[e] = sycl::exp((double)l[e] - (double)mx);
270    /*
271    DPCT1065: Consider replacing sycl::nd_item::barrier() with
272    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
273    performance if there is no access to global memory.
274    */
275    item_ct1.barrier();
276
277    // ---- the sum, ascending, on one thread: see the note above on why this is NOT parallelised.
278    if (tid == 0) {
279        double sum = 0.0;
280#pragma unroll
281        for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
282        s_sum = sum;
283    }
284    /*
285    DPCT1065: Consider replacing sycl::nd_item::barrier() with
286    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
287    performance if there is no access to global memory.
288    */
289    item_ct1.barrier();
290    const float inv = (float) (1.0 / s_sum);
291
292    // ---- the selection, by rank.  `p[e] = (float)(s_ex[e] * inv)` reproduces the old expression exactly:
293    // `(float)(exp((double) l[e] - (double) mx) * inv)` with `inv` a FLOAT.
294    // ---- p[] ONCE.  The rank loop below compares every expert against every other, so computing
295    // `(float) (s_ex[f] * inv)` INSIDE it did **512 x 512 = 262,144** double multiplies and float converts per
296    // token per layer instead of 512 - and a consumer die runs FP64 at a small fraction of FP32, which is why
297    // this was worth more than the branch.  The shared load stays either way; the ARITHMETIC is what goes.
298    //
299    // THIS IS BIT-IDENTICAL, not merely equivalent: `p[e]` is the same expression it was, computed once instead
300    // of 513 times, and the comparisons then see exactly the same floats.
301    float* s_p = (float*) (s_ex + n_expert);
302#pragma unroll
303    for (int e = tid; e < n_expert; e += nt) s_p[e] = (float)(s_ex[e] * inv);
304    /*
305    DPCT1065: Consider replacing sycl::nd_item::barrier() with
306    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
307    performance if there is no access to global memory.
308    */
309    item_ct1.barrier();
310
311    // ================================ THE SELECTION, IN k PASSES ================================
312    //
313    // **THE RANK-BY-COUNTING LOOP COMPARED EVERY EXPERT AGAINST EVERY OTHER**: 512 x 512 = 262,144 shared
314    // loads and compares per token per layer, to choose ten things out of 512 - measured at 34.35 us, 63% of
315    // `moe_route`'s accounted cost and the largest single item in the R3 plan.  The comment above records that
316    // the FP64 ARITHMETIC inside that loop was hoisted out once already ("262,144 double multiplies per token
317    // per layer instead of 512"); **the O(n^2) STRUCTURE was left, and it is the structure that costs.**
318    //
319    // `k` passes of a block-wide argmax is 10 x 512 = 5,120 compares - **51x less work** - and it produces the
320    // SAME ORDER.  That is the whole correctness argument: scanning `e` ascending with a strict `>` keeps the
321    // LOWEST index on a tie, which is exactly the rule the rank loop spelled out as
322    // `else if (f < e && pf == pe) ++rank`.  A stable descending top-k, ties by index.
323#pragma unroll
324    for (int e = tid; e < n_expert; e += nt) s_taken[e] = 0;
325    /*
326    DPCT1065: Consider replacing sycl::nd_item::barrier() with
327    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
328    performance if there is no access to global memory.
329    */
330    item_ct1.barrier();
331
332    for (int i = 0; i < k; ++i) {
333        float bv = -INFINITY;
334        int bi = n_expert;               // a sentinel that loses to every real index
335        for (int e = tid; e < n_expert; e += nt) {
336            if (s_taken[e]) continue;
337            const float pe = s_p[e];
338            if (pe > bv) { bv = pe; bi = e; }
339        }
340        for (int off = 16; off > 0; off >>= 1) {
341            /*
342            DPCT1108: '__shfl_down_sync' was migrated with the experimental
343            feature masked sub_group function which may not be supported by all
344            compilers or runtimes. You may need to adjust the code.
345            */
346            const float ov = dpct::experimental::shift_sub_group_left(
347                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
348                bv, off);
349            /*
350            DPCT1108: '__shfl_down_sync' was migrated with the experimental
351            feature masked sub_group function which may not be supported by all
352            compilers or runtimes. You may need to adjust the code.
353            */
354            const int oi = dpct::experimental::shift_sub_group_left(
355                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
356                bi, off);
357            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
358        }
359        if ((tid & 31) == 0) { s_red[tid >> 5] = bv; s_rid[tid >> 5] = bi; }
360        /*
361        DPCT1118: SYCL group functions and algorithms must be encountered in
362        converged control flow. You may need to adjust the code.
363        */
364        /*
365        DPCT1065: Consider replacing sycl::nd_item::barrier() with
366        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
367        better performance if there is no access to global memory.
368        */
369        item_ct1.barrier();
370        if (tid < 32) {
371            const int nw = (nt + 31) >> 5;
372            float v = (tid < nw) ? s_red[tid] : -INFINITY;
373            int ix = (tid < nw) ? s_rid[tid] : n_expert;
374            for (int off = 16; off > 0; off >>= 1) {
375                /*
376                DPCT1108: '__shfl_down_sync' was migrated with the
377                experimental feature masked sub_group function which may not be
378                supported by all compilers or runtimes. You may need to adjust
379                the code.
380                */
381                const float ov = dpct::experimental::shift_sub_group_left(
382                    0xffffffffu,
383                    sycl::ext::oneapi::this_work_item::get_sub_group(), v, off);
384                /*
385                DPCT1108: '__shfl_down_sync' was migrated with the
386                experimental feature masked sub_group function which may not be
387                supported by all compilers or runtimes. You may need to adjust
388                the code.
389                */
390                const int oi = dpct::experimental::shift_sub_group_left(
391                    0xffffffffu,
392                    sycl::ext::oneapi::this_work_item::get_sub_group(), ix,
393                    off);
394                if (ov > v || (ov == v && oi < ix)) { v = ov; ix = oi; }
395            }
396            if (tid == 0 && ix < n_expert) {
397                ids[(size_t) t * k + i] = ix;
398                weights[(size_t) t * k + i] = v;
399                s_taken[ix] = 1;
400            }
401        }
402        /*
403        DPCT1118: SYCL group functions and algorithms must be encountered in
404        converged control flow. You may need to adjust the code.
405        */
406        /*
407        DPCT1065: Consider replacing sycl::nd_item::barrier() with
408        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
409        better performance if there is no access to global memory.
410        */
411        item_ct1.barrier();
412    }
413    /*
414    DPCT1065: Consider replacing sycl::nd_item::barrier() with
415    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
416    performance if there is no access to global memory.
417    */
418    item_ct1.barrier();
419
420    // ---- renormalise, with ggml's lower clamp.  Order preserved.
421    if (tid == 0) {
422        double s = 0.0;
423#pragma unroll
424        for (int i = 0; i < k; ++i) s += (double)weights[(size_t)t * k + i];
425        const double sc = sycl::fmax(s, 6.103515625e-05); // 2**-14
426#pragma unroll
427        for (int i = 0; i < k; ++i)
428            weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
429    }
430}
431
432
433/// THE SAME ROUTER IN FP32, FOR A CARD WITHOUT FP64 (Intel Arc A- and B-series: the runtime refuses a kernel that uses
434/// double there, "'double' is not supported in ... device").  The Flash-Next shapes (512 or 256 experts, top-10) take
435/// the native router and never come here; a model of another shape (Qwen4 day: top-8, 256 experts) does, and on an
436/// Arc the double kernel above ended the engine at its first routed token.  This kernel is the one above with every
437/// double made a float: the exponentials in fp32 of the same differences, the ascending serial sum with a Kahan
438/// compensation (so the total is as close to the double one as fp32 allows), the same p = e * inv, the same
439/// selection passes (stable descending, ties by index), and the renormalisation with the same 2**-14 clamp.  A card
440/// WITH fp64 keeps the double kernels, bit for bit.
441__dpct_inline__ void router_top10_f32_kernel(const float *__restrict__ logits, int n_tokens, int n_expert, int k,
442                                             int *__restrict__ ids, float *__restrict__ weights, uint8_t *dpct_local) {
443    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
444    auto sg = sycl::ext::oneapi::this_work_item::get_sub_group();
445    auto s_raw = (unsigned char *) dpct_local;
446    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
447    unsigned char* s_taken = s_raw;
448    float* s_ex = (float*) (s_raw + taken_bytes);
449    float* s_p = s_ex + n_expert;
450    auto &s_red = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[RT_MAX_THREADS / 32]>(
451        sycl::ext::oneapi::this_work_item::get_work_group<3>());
452    auto &s_rid = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[RT_MAX_THREADS / 32]>(
453        sycl::ext::oneapi::this_work_item::get_work_group<3>());
454    auto &s_sum = *sycl::ext::oneapi::group_local_memory_for_overwrite<float>(
455        sycl::ext::oneapi::this_work_item::get_work_group<3>());
456    const int t = item_ct1.get_group(2);
457    if (t >= n_tokens) return;
458    const int tid = item_ct1.get_local_id(2);
459    const int nt = item_ct1.get_local_range(2);
460    const int nw = (nt + 31) >> 5;
461    const float* l = logits + (size_t) t * n_expert;
462    // the max: exact and order-independent, as above
463    float mx = -INFINITY;
464    for (int e = tid; e < n_expert; e += nt) mx = sycl::fmax(mx, l[e]);
465    for (int off = 16; off > 0; off >>= 1) mx = sycl::fmax(mx, sycl::shift_group_left(sg, mx, off));
466    if ((tid & 31) == 0) s_red[tid >> 5] = mx;
467    item_ct1.barrier();
468    if (tid < 32) {
469        float v = (tid < nw) ? s_red[tid] : -INFINITY;
470        for (int off = 16; off > 0; off >>= 1) v = sycl::fmax(v, sycl::shift_group_left(sg, v, off));
471        if (tid == 0) s_red[0] = v;
472    }
473    item_ct1.barrier();
474    mx = s_red[0];
475    for (int e = tid; e < n_expert; e += nt) s_ex[e] = sycl::exp(l[e] - mx);
476    item_ct1.barrier();
477    // the sum, ascending, on one thread (as above), compensated
478    if (tid == 0) {
479        float sum = 0.0f, c = 0.0f;
480        for (int e = 0; e < n_expert; ++e) {
481            const float y = s_ex[e] - c;
482            const float u = sum + y;
483            c = (u - sum) - y;
484            sum = u;
485        }
486        s_sum = sum;
487    }
488    item_ct1.barrier();
489    const float inv = 1.0f / s_sum;
490    for (int e = tid; e < n_expert; e += nt) { s_p[e] = s_ex[e] * inv; s_taken[e] = 0; }
491    item_ct1.barrier();
492    for (int i = 0; i < k; ++i) {
493        float bv = -INFINITY;
494        int bi = n_expert;               // a sentinel that loses to every real index
495        for (int e = tid; e < n_expert; e += nt) {
496            if (s_taken[e]) continue;
497            const float pe = s_p[e];
498            if (pe > bv) { bv = pe; bi = e; }
499        }
500        for (int off = 16; off > 0; off >>= 1) {
501            const float ov = sycl::shift_group_left(sg, bv, off);
502            const int oi = sycl::shift_group_left(sg, bi, off);
503            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
504        }
505        if ((tid & 31) == 0) { s_red[tid >> 5] = bv; s_rid[tid >> 5] = bi; }
506        item_ct1.barrier();
507        if (tid < 32) {
508            float v = (tid < nw) ? s_red[tid] : -INFINITY;
509            int ix = (tid < nw) ? s_rid[tid] : n_expert;
510            for (int off = 16; off > 0; off >>= 1) {
511                const float ov = sycl::shift_group_left(sg, v, off);
512                const int oi = sycl::shift_group_left(sg, ix, off);
513                if (ov > v || (ov == v && oi < ix)) { v = ov; ix = oi; }
514            }
515            if (tid == 0 && ix < n_expert) {
516                ids[(size_t) t * k + i] = ix;
517                weights[(size_t) t * k + i] = v;
518                s_taken[ix] = 1;
519            }
520        }
521        item_ct1.barrier();
522    }
523    item_ct1.barrier();
524    if (tid == 0) {                      // renormalise with ggml's lower clamp, compensated
525        float s = 0.0f, c = 0.0f;
526        for (int i = 0; i < k; ++i) {
527            const float y = weights[(size_t) t * k + i] - c;
528            const float u = s + y;
529            c = (u - s) - y;
530            s = u;
531        }
532        const float sc = sycl::fmax(s, 6.103515625e-05f);   // 2**-14
533        for (int i = 0; i < k; ++i) weights[(size_t) t * k + i] = weights[(size_t) t * k + i] / sc;
534    }
535}
536
537/// The fp32 router's launch (router_top10_f32_kernel); `variant` 3 of router_top10_variant runs it on any card (the parity test).
538void launch_sycl_f32(sycl::queue& q, const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights) {
539    const int threads = (std::min(n_expert, RT_MAX_THREADS) + 31) & ~31;
540    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
541    const size_t smem = taken_bytes + (size_t) n_expert * 2 * sizeof(float);
542    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
543        sycl::local_accessor<uint8_t, 1> local(sycl::range<1>(smem), h);
544        h.parallel_for<class router_top10_f32_q4ready>(
545            sycl::nd_range<3>(sycl::range<3>(1, 1, (size_t) n_tokens * threads), sycl::range<3>(1, 1, threads)),
546            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
547                router_top10_f32_kernel(logits, n_tokens, n_expert, k, ids, weights,
548                                        local.get_multi_ptr<sycl::access::decorated::no>().get());
549            });
550    });
551}
552
553/// Does this queue's device run fp64 kernels? (Asked once per device; Intel Arc A- and B-series do not.)
554bool device_has_fp64(sycl::queue& q) {
555    static std::mutex mu;
556    static std::vector<std::pair<sycl::device, bool>> seen;
557    const sycl::device d = q.get_device();
558    std::lock_guard<std::mutex> lock(mu);
559    for (const auto& [dev, has] : seen)
560        if (dev == d) return has;
561    const bool has = d.has(sycl::aspect::fp64);
562    seen.emplace_back(d, has);
563    return has;
564}
565
566#if defined(STRATA_HIP_GFX906)
567// AMD (wave64): the same routing in ONE wavefront per token.  The block-wide kernel above spends its time in
568// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per
569// token on gfx906).  Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane
570// butterfly argmax: no LDS round trip, no block barrier.  Bit-identical to the kernel above: fmaxf trees are
571// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending
572// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free).
573constexpr int RW_PER = 8;   // n_expert <= 64 * 8
574__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens,
575                                                               int n_expert, int k, int* __restrict__ ids,
576                                                               float* __restrict__ weights) {
577    __shared__ double s_ex[64 * RW_PER];
578    __shared__ double s_sum;
579    const int t = blockIdx.x;
580    if (t >= n_tokens) return;
581    const int lane = threadIdx.x;
582    const float* l = logits + (size_t) t * n_expert;
583    float lv[RW_PER];
584    float mx = -INFINITY;
585#pragma unroll
586    for (int j = 0; j < RW_PER; ++j) {
587        const int e = lane + 64 * j;
588        lv[j] = e < n_expert ? l[e] : -INFINITY;
589        mx = fmaxf(mx, lv[j]);
590    }
591#pragma unroll
592    for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64));
593#pragma unroll
594    for (int j = 0; j < RW_PER; ++j) {
595        const int e = lane + 64 * j;
596        if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx);
597    }
598    __syncthreads();
599    if (lane == 0) {
600        double sum = 0.0;
601        for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
602        s_sum = sum;
603    }
604    __syncthreads();
605    const float inv = (float) (1.0 / s_sum);
606    float p[RW_PER];
607#pragma unroll
608    for (int j = 0; j < RW_PER; ++j) {
609        const int e = lane + 64 * j;
610        p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY;
611    }
612    unsigned taken = 0;
613    for (int i = 0; i < k; ++i) {
614        float bv = -INFINITY;
615        int bi = n_expert;
616#pragma unroll
617        for (int j = 0; j < RW_PER; ++j) {
618            const int e = lane + 64 * j;
619            if (e >= n_expert || (taken >> j & 1u)) continue;
620            if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; }
621        }
622#pragma unroll
623        for (int off = 32; off > 0; off >>= 1) {
624            const float ov = __shfl_xor(bv, off, 64);
625            const int oi = __shfl_xor(bi, off, 64);
626            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
627        }
628        if (bi >= n_expert) break;
629        if ((bi & 63) == lane) taken |= 1u << (bi >> 6);
630        if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; }
631    }
632    if (lane == 0) {
633        double s = 0.0;
634        for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
635        const double sc = fmax(s, 6.103515625e-05);       // 2**-14
636        for (int i = 0; i < k; ++i)
637            weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
638    }
639}
640#endif  // STRATA_HIP_GFX906
641
642#if defined(__HIPCC__)
643// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel
644// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64
645// adds (~50 cycles each there), the ten selection passes are 20 block barriers, and the renormalisation re-reads its
646// ten weights from global memory one by one.  Here:
647//   * the sum's ONLY use is inv = (float) (1.0 / sum).  Every term is positive and the largest is exactly 1
648//     (exp(0)), so the serial sum and any other summation order both lie within 2^-43 (relative) of the exact sum
649//     (|serial - exact| <= 511u, |tree - exact| <= 21u, u = 2^-53).  1.0 / x and the float cast are monotone: when
650//     the bracket [tree (1 - 2^-40), tree (1 + 2^-40)] maps to ONE float, that float is the serial sum's.  Otherwise
651//     (about 1 row in 1000 in the parity test, or a non-finite sum) thread 0 runs the serial sum as before;
652//   * the selection runs on wave 0 alone with the probabilities in registers (16 per lane): the largest p with the
653//     lowest index on ties is unique, so the butterfly finds the same expert as the block reduction did;
654//   * the renormalisation sums the ten weights in rank order from registers and divides them in parallel.
655// Same expressions, same operands: the ids and weights are bitwise those of router_top10_kernel (hip_router_fast
656// checks it on 65,536 rows with ties, near-ties, NaN rows and the forced serial path). STRATA_HIP_ROUTER_OLD=1: the
657// kernel above.
658template <bool FORCE_SERIAL>
659__global__ void router_top10_fast_kernel(const float* __restrict__ logits, int n_tokens, int n_expert, int k,
660                                         int* __restrict__ ids, float* __restrict__ weights) {
661    extern __shared__ unsigned char s_raw[];
662    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
663    double* s_ex = (double*) (s_raw + taken_bytes);
664    __shared__ float s_red[RT_MAX_THREADS / 32];
665    __shared__ double s_dred[RT_MAX_THREADS / 32];
666    __shared__ float s_inv;
667    const int t = blockIdx.x;
668    if (t >= n_tokens) return;
669    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
670    const int nt = blockDim.x, nw = (nt + 31) >> 5;
671    const float* l = logits + (size_t) t * n_expert;
672    // the max: as router_top10_kernel (exact, order-independent)
673    float mx = -INFINITY;
674    for (int e = tid; e < n_expert; e += nt) mx = fmaxf(mx, l[e]);
675    for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_down_sync(0xffffffffu, mx, off));
676    if (lane == 0) s_red[warp] = mx;
677    __syncthreads();
678    if (tid < 32) {
679        float v = (tid < nw) ? s_red[tid] : -INFINITY;
680        for (int off = 16; off > 0; off >>= 1) v = fmaxf(v, __shfl_down_sync(0xffffffffu, v, off));
681        if (tid == 0) s_red[0] = v;
682    }
683    __syncthreads();
684    mx = s_red[0];
685    // the exponentials (the same expression), and a tree sum of them for the bracket
686    double part = 0.0;
687    for (int e = tid; e < n_expert; e += nt) {
688        const double x = exp((double) l[e] - (double) mx);
689        s_ex[e] = x;
690        part += x;
691    }
692    for (int off = 16; off > 0; off >>= 1) part += __shfl_xor_sync(0xffffffffu, part, off);
693    if (lane == 0) s_dred[warp] = part;
694    __syncthreads();
695    double tot = 0.0;
696    for (int w = 0; w < nw; ++w) tot += s_dred[w];
697    const double lo = tot * (1.0 - 0x1p-40), hi = tot * (1.0 + 0x1p-40);
698    const float f_lo = (float) (1.0 / hi), f_hi = (float) (1.0 / lo);
699    float inv;
700    if (!FORCE_SERIAL && tot >= 1.0 && hi < 1e300 && f_lo == f_hi) {
701        inv = f_lo;
702    } else {   // block-uniform (every thread computed the same tot): the serial sum, exactly as router_top10_kernel
703        if (tid == 0) {
704            double sum = 0.0;
705            for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
706            s_inv = (float) (1.0 / sum);
707        }
708        __syncthreads();
709        inv = s_inv;
710    }
711    if (warp != 0) return;
712    // wave 0: lane holds experts lane + 32 j; p is router_top10_kernel's expression
713    constexpr int PER = 16;
714    float pv[PER];
715    unsigned live = 0;
716#pragma unroll
717    for (int j = 0; j < PER; ++j) {
718        const int e = lane + 32 * j;
719        pv[j] = -INFINITY;
720        if (e < n_expert) { pv[j] = (float) (s_ex[e] * inv); live |= 1u << j; }
721    }
722    float my_w = 0.0f;
723    int my_id = 0, nsel = 0;
724    for (int i = 0; i < k; ++i) {
725        float bv = -INFINITY;
726        int bi = n_expert;   // a sentinel that loses to every real index
727#pragma unroll
728        for (int j = 0; j < PER; ++j)
729            if (((live >> j) & 1u) && pv[j] > bv) { bv = pv[j]; bi = lane + 32 * j; }
730        for (int off = 16; off > 0; off >>= 1) {
731            const float ov = __shfl_xor_sync(0xffffffffu, bv, off);
732            const int oi = __shfl_xor_sync(0xffffffffu, bi, off);
733            if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
734        }
735        if (bi >= n_expert) break;   // as router_top10_kernel: no rank i or later is written (every p left is NaN)
736        if ((bi & 31) == lane) live &= ~(1u << (bi >> 5));
737        if (lane == i) { my_w = bv; my_id = bi; }
738        nsel = i + 1;
739    }
740    if (nsel == k) {
741        double s = 0.0;
742        for (int i = 0; i < k; ++i) s += (double) __shfl_sync(0xffffffffu, my_w, i);
743        const double sc = fmax(s, 6.103515625e-05);       // 2**-14
744        if (lane < k) {
745            ids[(size_t) t * k + lane] = my_id;
746            weights[(size_t) t * k + lane] = (float) ((double) my_w / sc);
747        }
748    } else {   // router_top10_kernel's tail exactly: unwritten ranks keep what the buffer held and are renormalised too
749        if (lane < nsel) { ids[(size_t) t * k + lane] = my_id; weights[(size_t) t * k + lane] = my_w; }
750        __threadfence();
751        if (lane == 0) {
752            double s = 0.0;
753            for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
754            const double sc = fmax(s, 6.103515625e-05);
755            for (int i = 0; i < k; ++i)
756                weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
757        }
758    }
759}
760
761void launch_generic(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights, void* stream,
762                    int mode) {   // mode 0: router_top10_kernel, 1: the HIP fast kernel, 2: the fast kernel's serial path
763    int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
764    threads = (threads + 31) & ~31;
765    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
766    const size_t smem = taken_bytes + (size_t) n_expert * sizeof(double) + (size_t) n_expert * sizeof(float);
767    if (mode == 1) {
768        router_top10_fast_kernel<false><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
769            logits, n_tokens, n_expert, k, ids, weights);
770        return;
771    }
772    if (mode == 2) {
773        router_top10_fast_kernel<true><<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
774            logits, n_tokens, n_expert, k, ids, weights);
775        return;
776    }
777    router_top10_kernel<<<(unsigned) n_tokens, threads, smem, (cudaStream_t) stream>>>(
778        logits, n_tokens, n_expert, k, ids, weights);
779}
780#endif
781
782}  // namespace
783
784bool router_top10_variant(const float* logits, int n_tokens, int n_expert, int k, int* ids, float* weights,
785                          void* stream, int variant) {
786#if defined(__HIPCC__)
787    if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32) return false;
788    if (variant < 0 || variant > 2) return false;
789    launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, variant);
790    return cudaGetLastError() == cudaSuccess;
791#else
792    if (n_tokens <= 0 || n_expert <= 64 || n_expert > 512 || k <= 0 || k > 32 || variant < 0 || variant > 3)
793        return false;
794    auto& q = *strata::q_of(stream);
795    if (variant == 3) launch_sycl_f32(q, logits, n_tokens, n_expert, k, ids, weights);
796    else if (variant == 1) launch_sycl_fast<false>(q, logits, n_tokens, n_expert, k, ids, weights);
797    else if (variant == 2) launch_sycl_fast<true>(q, logits, n_tokens, n_expert, k, ids, weights);
798    else {
799        const int threads = (std::min(n_expert, RT_MAX_THREADS) + 31) & ~31;
800        const size_t taken_bytes = ((size_t)n_expert + 15u) & ~size_t(15);
801        const size_t smem = taken_bytes + n_expert * (sizeof(double) + sizeof(float));
802        strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
803            sycl::local_accessor<uint8_t, 1> local(sycl::range<1>(smem), h);
804            h.parallel_for(sycl::nd_range<3>(sycl::range<3>(1, 1, (size_t)n_tokens * threads),
805                                             sycl::range<3>(1, 1, threads)),
806                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
807                    router_top10_kernel(logits, n_tokens, n_expert, k, ids, weights,
808                        local.get_multi_ptr<sycl::access::decorated::no>().get());
809                });
810        });
811    }
812    if (stream == nullptr) q.wait_and_throw();
813    return true;
814#endif
815}
816
817void router_top10(const float *logits, int n_tokens, int n_expert, int k,
818                  int *ids, float *weights, void *stream) try {
819#if !defined(__HIPCC__)
820    // a card without fp64 (Intel Arc): the fp32 router; the double kernels below are refused at their launch there
821    if (n_tokens > 0 && n_expert > 0 && n_expert <= RT_MAX_THREADS * 64 && k > 0 && k <= 64 && !device_has_fp64(*strata::q_of(stream))) {
822        auto& q = *strata::q_of(stream);
823        launch_sycl_f32(q, logits, n_tokens, n_expert, k, ids, weights);
824        if (stream == nullptr) q.wait_and_throw();
825        return;
826    }
827#endif
828    if (strata::a770_fast() && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
829        auto& q = *strata::q_of(stream);
830        launch_sycl_fast<false>(q, logits, n_tokens, n_expert, k, ids, weights);
831        if (stream == nullptr) q.wait_and_throw();
832        return;
833    }
834#if defined(__HIPCC__)
835    {
836#if defined(STRATA_HIP_GFX906)
837        // gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only
838        // runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card
839        static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr;
840#else
841        static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;
842#endif
843        if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
844            launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);
845            const cudaError_t e = cudaGetLastError();
846            if (e != cudaSuccess) {
847                std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
848                std::exit(1);
849            }
850            if (stream == nullptr) {
851                const cudaError_t s = cudaDeviceSynchronize();
852                if (s != cudaSuccess) {
853                    std::fprintf(stderr, "router_top10: %s\n", cudaGetErrorString(s));
854                    std::exit(1);
855                }
856            }
857            return;
858        }
859    }
860#endif
861    if (n_tokens <= 0 || n_expert <= 0 || k <= 0) return;
862    if (k > 64) {
863        std::fprintf(stderr, "router_top10: k %d exceeds the kernel's 64\n", k);
864        std::exit(1);
865    }
866    if (n_expert > RT_MAX_THREADS * 64) {
867        std::fprintf(stderr, "router_top10: n_expert %d is past the kernel's %d\n", n_expert,
868                     RT_MAX_THREADS * 64);
869        std::exit(1);
870    }
871#if defined(STRATA_HIP_GFX906)
872    if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) {
873        router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k,
874                                                                                       ids, weights);
875        const cudaError_t e = cudaGetLastError();
876        if (e != cudaSuccess) {
877            std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
878            std::exit(1);
879        }
880        if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1);
881        return;
882    }
883#endif
884    int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
885    threads = (threads + 31) & ~31;                  // at least one full warp, for the reductions
886    // the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the
887    // probabilities.  The mask is first so the two aligned arrays need no offset parameter.
888    const size_t taken_bytes = ((size_t) n_expert + 15u) & ~(size_t) 15u;
889    const size_t smem =
890        /*
891        DPCT1083: The size of local memory in the migrated code may be
892        different from the original code. Check that the allocated memory size
893        in the migrated code is correct.
894        */
895        taken_bytes + (size_t)n_expert * sizeof(double) +
896        (size_t)n_expert * sizeof(float);
897    /*
898    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
899    limit. To get the device limit, query info::device::max_work_group_size.
900    Adjust the work-group size if needed.
901    */
902    {
903        auto exp_props = sycl::ext::oneapi::experimental::properties{
904            sycl::ext::oneapi::experimental::use_root_sync};
905        dpct::has_capability_or_fail(
906            strata::q_of(stream)->get_device(),
907            {sycl::aspect::fp64});
908
909        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
910            ->submit([&](sycl::handler &cgh) {
911                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
912                    sycl::range(smem), cgh);
913
914                cgh.parallel_for<
915                    dpct_kernel_name<class router_top10_kernel_3e0655>>(
916                    sycl::nd_range<3>(sycl::range(1, 1, (unsigned)n_tokens) *
917                                          sycl::range(1, 1, threads),
918                                      sycl::range(1, 1, threads)),
919                    exp_props,
920                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
921                        32)]] {
922                        router_top10_kernel(
923                            logits, n_tokens, n_expert, k, ids, weights,
924                            dpct_local_acc_ct1
925                                .get_multi_ptr<sycl::access::decorated::no>()
926                                .get());
927                    });
928            });
929    }
930    /*
931    DPCT1010: SYCL uses exceptions to report errors and does not use the
932    error codes. The cudaGetLastError function call was replaced with 0. You
933    need to rewrite this code.
934    */
935    const dpct::err0 e = 0;
936
937    if (stream == nullptr) {
938        const dpct::err0 s = DPCT_CHECK_ERROR(
939            dpct::get_current_device().queues_wait_and_throw());
940    }
941}
942catch (sycl::exception const &exc) {
943  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
944            << ", line:" << __LINE__ << std::endl;
945  std::exit(1);
946}
947
948}  // namespace strata::kernels