okami.mom/strata

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

Niko1221Merge f-q4-sycl (41717f29c): the Intel Arc (SYCL) engine follows the compiled geometry, so q4_lite/q4_mid/q4_big build; default build unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 string offsets only, Metal 85/85 objects, SYCL 22/22 checksums); A750 gate 2 q4_lite 0.00021 vs floor 0.00017; one conflict with f-clean-6-0 in sycl/src/prefill/prefill.cpp resolved as tested by Q4-SYMERGE (Qwen4 prep)db137d917

main
92.4 KiB1882 linesraw
1// src/kernels/cuda/s2_expert_grouped.cu - R4's grouped GPU expert.  Read the header first.
2//
3// THE ARITHMETIC IS `src/kernels/cpu/expert.cpp`'s, over the same bytes, one warp per output row.
4//
5//     sum_j (c_j - 1) * d_w * xhat_j * d_x   ==   d_w * d_x * ( sum_j c_j*xhat_j  -  sum_j xhat_j )
6//
7// Both sums are INT8 x INT8, so both are `__dp4a` - four multiply-accumulates per instruction, exact in
8// integer and with no dequantization inside the loop.  The weight scale `d_w` is fp16 (one per 64 elements)
9// and the activation scale `d_x` is fp16 (one per 32 elements), so the float work is one multiply-add per
10// 32-element chunk rather than one per element.
11//
12// **THE SUMMATION ORDER IS NOT THE CPU's AND CANNOT BE.**  Lane `L` takes chunks `L, L+32, ...` and the
13// partials are reduced through shuffle; the CPU walks every chunk in order with its own accumulator shape.
14// The two agree to float rounding and not to the bit, which is the same contract `s_gemv_parity` carries for
15// the same reason.  `bench/micro/moe_hit_parity.cu` is the check.
16#define DPCT_PROFILING_ENABLED
17#include <sycl/sycl.hpp>
18#include "strata/kprof.hpp"
19#include "strata/core/geometry.hpp"
20#include <dpct/dpct.hpp>
21#include "strata/sycl_math.hpp"
22#include "strata/sycl_queue.hpp"
23#include "strata/kernels/s2_expert_grouped.hpp"
24#include "strata/kernels/dp4a.hpp"
25#include "strata/kernels/f16_bits.hpp"
26
27#include "strata/kernels/quantize_act.hpp"
28#include "strata/kernels/verify_kernels.hpp"
29
30#include <atomic>
31#include <cstdint>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35
36namespace strata::kernels {
37namespace {
38
39// THE BLOB'S OWN GEOMETRY, from `include/strata/kernels/cpu/expert.hpp`.  Restated as literals because that
40// header is the CPU path's and this file must not silently follow it if the two ever disagree: the sizes below
41// are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end.
42constexpr int H = strata::core::kCompiledGeometry.n_embd;
43constexpr int FF = strata::core::kCompiledGeometry.n_ff;
44static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff, "s2_expert_grouped is compiled for core/geometry.hpp");
45constexpr int QK = 64;                       // Q2_0's group: one fp16 scale per 64 weights
46constexpr int ROW_GU = H / 4;                // 640 B of codes per gate/up row (2 bits per element)
47constexpr int ROW_D = FF / 4;                // 160 B per down row
48constexpr int SC_GU = H / QK;                // 40 fp16 scales per gate/up row
49constexpr int SC_D = FF / QK;                // 10 per down row
50constexpr size_t O_D_CODES = (size_t) 2 * FF * ROW_GU;
51constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D;
52constexpr size_t O_D_SCALES = O_GU_SCALES + (size_t) 2 * FF * SC_GU * 2;
53
54__dpct_inline__ float f16_at(const uint8_t *p) {
55    return sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
56                                        (uint16_t)(p[0] | (p[1] << 8))))
57        .convert<float, sycl::rounding_mode::automatic>()[0];
58}
59
60/// **ONE S2 ROW AGAINST A Q8_0 ACTIVATION, WARP-WIDE.**  Every lane accumulates its own float partial over a
61/// strided set of 32-element chunks and the caller reduces; `chunk` indices are absolute so the caller can
62/// start the lane at any offset.
63///
64/// Returns the lane's partial.  `codes` is `n_in/4` bytes and `scales` `n_in/QK` fp16, both for THIS row.
65///
66/// **`x_scales` IS R4.2h AND IT IS OPTIONAL ON PURPOSE.**  When it is non-null the activation's multiplier
67/// comes from an fp32 array instead of the block's fp16 `d`.  The CPU pool multiplies by the fp32
68/// `ActQ::scale` (`cpu/expert.cpp:92`), and the two disagreed by **4.761e-04 relative on 80 of 80 chunks**
69/// (`bench/micro/act_quant_parity.cu`), which is what made a cache hit compute a different expert from a
70/// cache miss.  Null keeps the previous fp16 behaviour **exactly**, so `moe_hit_parity` - which passes no
71/// scales - still measures the kernel it always measured.
72__dpct_inline__ float
73row_dot_s2_q8(const uint8_t *__restrict__ codes,
74              const uint8_t *__restrict__ scales,
75              const uint8_t *__restrict__ x_q8_0, int n_chunks, int lane,
76              const float *__restrict__ x_scales = nullptr) {
77    float acc = 0.0f;
78    for (int c = lane; c < n_chunks; c += 32) {
79        const uint8_t* cb = codes + (size_t) c * 8;             // 8 code bytes = 32 elements
80        const uint8_t* xb = x_q8_0 + (size_t) c * 34;           // one block_q8_0
81        const float dx = x_scales ? x_scales[c] : f16_at(xb);
82        const int8_t* xq = (const int8_t*) (xb + 2);
83
84        // ---- THE CODES, EXPANDED TO ONE BYTE PER ELEMENT, THEN FOUR AT A TIME INTO `dp4a`.
85        //
86        // The packed form is LSB-first: element 4j+k is bits [2k, 2k+2) of code byte j.  `dp4a` needs both
87        // operands as packed int8, so each code byte becomes a word whose four bytes are its four 2-bit
88        // fields - which is exactly `(c & 3) | ((c>>2)&3)<<8 | ((c>>4)&3)<<16 | ((c>>6)&3)<<24`.
89        int s = 0;      // sum of code * x
90        int hx = 0;     // sum of x        - the weight-independent term, as ones * x
91        const int ones = 0x01010101;
92#pragma unroll
93        for (int j = 0; j < 8; ++j) {
94            const unsigned cbyte = cb[j];
95            const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) |
96                                  (((cbyte >> 6) & 3u) << 24));
97            // **`memcpy`, NOT A CAST.**  A `block_q8_0` is 34 BYTES - two of header then 32 of int8 - so the
98            // activation data at offset 2 is never 4-byte aligned, and `*(const int*)(xq + 4*j)` faults with
99            // "misaligned address".  It faulted exactly that way on this kernel's first run.  `memcpy` of a
100            // known 4 bytes compiles to whatever load is legal for the alignment, which is the point of using
101            // it rather than reasoning about which cast happens to work.
102            int xw;
103            memcpy(&xw, xq + 4 * j, 4);
104            s = strata::dp4a(cw, xw, s);
105            hx = strata::dp4a(ones, xw, hx);
106        }
107        // One weight scale per 64 elements, so per TWO 32-element chunks.
108        const float dw = f16_at(scales + (size_t) (c >> 1) * 2);
109        acc += dw * dx * (float) (s - hx);
110    }
111    return acc;
112}
113
114__dpct_inline__ float warp_sum(float v) {
115#pragma unroll
116    /*
117    DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
118    masked sub_group function which may not be supported by all compilers or
119    runtimes. You may need to adjust the code.
120    */
121    /*
122    DPCT1121: Make sure that the "v" which is used in the SYCL group
123    function/algorithm is initialized.
124    */
125    for (int off = 16; off > 0; off >>= 1) v +=
126        dpct::experimental::shift_sub_group_left(
127            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(), v,
128            off);
129    return v;
130}
131
132/// GATE AND UP, ONE WARP PER ROW.
133///
134/// **THE ROWS ARE INTERLEAVED AND THE FIRST VERSION OF THIS GOT IT WRONG.**  In the blob, row-SLOT `i` of the
135/// `2*FF` gate/up rows is gate row `i/2` when `i` is even and up row `(i-1)/2` when it is odd - that is what
136/// `O_GU_CODES + (2r)*ROW_GU` and `+ (2r+1)*ROW_GU` mean in `expert.cpp`.  This kernel decoded the correct
137/// code row for slot `i` and then wrote it to output slot `i` of a layout whose first `FF` entries are gate and
138/// whose last `FF` are up, which pairs `silu(gate[r]) * up[r]` with the WRONG `up` for every `r`.  It produced
139/// finite, plausible numbers.  `moe_hit_parity` caught it on the first run, at worst relative error 2.2e+03.
140///
141/// So slot `i` is DECODED from row-slot `i` and WRITTEN to the output slot its parity says it belongs to.
142__dpct_inline__ void
143gu_kernel(const uint8_t *__restrict__ blob_base,
144          const int32_t *__restrict__ slot_index, long long blob_bytes,
145          const uint8_t *__restrict__ x_q8_0,
146          const float *__restrict__ x_scales, float *__restrict__ gate_up,
147          int n_hits, const int32_t *__restrict__ d_count = nullptr,
148          const int32_t *__restrict__ dst_index = nullptr, int tok_div = 0) {
149    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
150    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
151    const long long slot = (long long)item_ct1.get_group(2) * warps_per_block +
152                           (item_ct1.get_local_id(2) >> 5);
153    const long long rows_per_hit = 2LL * FF;
154    const long long total = (long long) n_hits * rows_per_hit;
155    if (slot >= total) return;
156    const int h = (int) (slot / rows_per_hit);
157    if (d_count != nullptr && h >= *d_count) return;     // token graph: capacity layout, device count
158    const int i = (int) (slot % rows_per_hit);
159    const int lane = item_ct1.get_local_id(2) & 31;
160
161    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
162    if (tok_div > 0) {   // plan v0.3 P6 verify window: each hit reads its own token's activation
163        const int tok = dst_index[h] / tok_div;
164        x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34;
165        if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32);
166    }
167    const float acc = row_dot_s2_q8(blob + (size_t) i * ROW_GU,
168                                    blob + O_GU_SCALES + (size_t) i * SC_GU * 2, x_q8_0, H / 32, lane, x_scales);
169    const float s = warp_sum(acc);
170    if (lane != 0) return;
171    // ---- THE OUTPUT LAYOUT IS GATE-MAJOR, AND THAT IS NOT COSMETIC.
172    //
173    // The first version wrote `gate_up[h*2FF + {0..FF-1}] = gate` and `[h*2FF + FF..] = up`, i.e. a per-hit
174    // [gate | up] pair, and then called the shared `swiglu_kernel` and `quantize_q8_0` over the whole buffer.
175    // Both of those walk a CONTIGUOUS range, so with more than one hit they read hit 0's UP rows where they
176    // wanted hit 1's GATE rows - finite numbers, wrong expert.  With one hit it would have passed.
177    //
178    // Gate-major removes the mismatch instead of adding a stride to two other kernels: every hit's gate rows
179    // are contiguous from 0, every hit's up rows are contiguous from `n_hits * FF`, and the swiglu's output
180    // lands in the first `n_hits * FF` floats exactly where `quantize_q8_0` reads it.
181    const int r = i >> 1;
182    const size_t base = (i & 1) ? ((size_t) n_hits * FF + (size_t) h * FF) : ((size_t) h * FF);
183    gate_up[base + (size_t) r] = s;
184}
185
186/// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and
187/// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`.
188///
189/// SiLU on the GATE and multiplied by up - the reading `docs/semantics.md` records, and the one that is wrong
190/// the other way round in a way that still produces a finite number.
191__dpct_inline__ void swiglu_kernel(float *__restrict__ gate_up,
192                                   long long n_pairs) {
193    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
194    const long long i =
195        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
196        item_ct1.get_local_id(2);
197    if (i >= n_pairs) return;
198    const float g = gate_up[i];
199    const float u = gate_up[n_pairs + i];
200    gate_up[i] = (g / (1.0f + sycl::native::exp(-g))) * u;
201}
202
203__dpct_inline__ void swiglu_quantize_q8_0_scaled_kernel(
204    float *__restrict__ gate_up, long long n_pairs,
205    uint8_t *__restrict__ blocks, float *__restrict__ scales) {
206    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
207    const long long n_blocks = n_pairs >> 5;
208    const long long b =
209        ((long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
210         item_ct1.get_local_id(2)) >>
211        5;
212    if (b >= n_blocks) return;
213    const int lane = item_ct1.get_local_id(2) & 31;
214    const long long idx = b * 32 + lane;
215    const float g = gate_up[idx];
216    const float u = gate_up[n_pairs + idx];
217    const float xv = (g / (1.0f + sycl::native::exp(-g))) * u;
218    gate_up[idx] = xv;
219    uint8_t* out = blocks + b * 34;
220
221    float amax = sycl::fabs(xv);
222#pragma unroll
223    /*
224    DPCT1108: '__shfl_xor_sync' was migrated with the experimental feature
225    masked sub_group function which may not be supported by all compilers or
226    runtimes. You may need to adjust the code.
227    */
228    for (int off = 16; off > 0; off >>= 1) amax =
229        sycl::fmax(amax, dpct::experimental::permute_sub_group_by_xor(
230                             0xffffffffu,
231                             sycl::ext::oneapi::this_work_item::get_sub_group(),
232                             amax, off));
233    const float s = amax > 0.f ? amax / 127.f : 0.f;
234    const float inv = s > 0.f ? 1.f / s : 0.f;
235    if (lane == 0) {
236        scales[b] = s;
237        const uint16_t d16bits = f16_from_f32(s);
238        out[0] = (uint8_t) (d16bits & 0xFF);
239        out[1] = (uint8_t) (d16bits >> 8);
240    }
241    const float t = xv * inv;
242    const float r = t + (t >= 0.f ? 0.5f : -0.5f);
243    int v = (int) r;
244    v = v < -127 ? -127 : (v > 127 ? 127 : v);
245    out[2 + lane] = (uint8_t) (int8_t) v;
246}
247
248/// DOWN, ONE WARP PER ROW, reading the quantized intermediate the caller produced.
249///
250/// `dst_index[h]` is which row of the shared output buffer hit `h` fills - see the header.  It is the router's
251/// slot, not `h`, and the two differ on every layer where some experts are resident and some are not.
252__dpct_inline__ void
253down_kernel(const uint8_t *__restrict__ blob_base,
254            const int32_t *__restrict__ slot_index,
255            const int32_t *__restrict__ dst_index, long long blob_bytes,
256            const uint8_t *__restrict__ h_q8_0,
257            const float *__restrict__ h_scales, float *__restrict__ out,
258            int n_hits, const int32_t *__restrict__ d_count = nullptr) {
259    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
260    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
261    const long long row = (long long)item_ct1.get_group(2) * warps_per_block +
262                          (item_ct1.get_local_id(2) >> 5);
263    const long long total = (long long) n_hits * H;
264    if (row >= total) return;
265    const int h = (int) (row / H);
266    if (d_count != nullptr && h >= *d_count) return;
267    const int r = (int) (row % H);
268    const int lane = item_ct1.get_local_id(2) & 31;
269
270    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
271    const uint8_t* xb = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34;
272    const float acc = row_dot_s2_q8(blob + O_D_CODES + (size_t) r * ROW_D,
273                                    blob + O_D_SCALES + (size_t) r * SC_D * 2, xb, FF / 32, lane,
274                                    h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr);
275    const float s = warp_sum(acc);
276    if (lane == 0) out[(size_t) dst_index[h] * H + r] = s;
277}
278
279// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS.  `STRATA_OLD_GROUPED=1` keeps the kernels above.
280//
281// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.**  `s = sum_e code_e * x_e` and
282// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words
283// gives the same two integers.  The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303`
284// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is
285// the ACTIVATIONS that are regrouped, once per chunk, into
286//
287//     X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] }
288//
289// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`.  The kernels above spend seven integer
290// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16
291// elements and `hx` is summed once per chunk.  `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are
292// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that.
293
294// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value.
295__dpct_inline__ float f16_ld(const uint8_t *p) {
296    return sycl::vec<sycl::half, 1>(sycl::bit_cast<sycl::half, unsigned short>(
297                                        *(const unsigned short *)p))
298        .convert<float, sycl::rounding_mode::automatic>()[0];
299}
300
301// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the
302// code of element `16h + 4b + f`.
303__dpct_inline__ void expand_codes(sycl::uint2 cb, int m[8]) {
304    const unsigned M = 0x03030303u;
305    m[0] = (int)(cb.x() & M);
306    m[1] = (int)((cb.x() >> 2) & M);
307    m[2] = (int)((cb.x() >> 4) & M);
308    m[3] = (int)((cb.x() >> 6) & M);
309    m[4] = (int)(cb.y() & M);
310    m[5] = (int)((cb.y() >> 2) & M);
311    m[6] = (int)((cb.y() >> 4) & M);
312    m[7] = (int)((cb.y() >> 6) & M);
313}
314
315// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`.
316//
317// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.**  The caller guarantees a 4-byte aligned activation row, so
318// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the
319// words are read aligned and funnel-shifted into place.  The ninth word is read only in the 2-byte case, and then
320// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is
321// never a row's last.
322__dpct_inline__ int load_x_chunk(const uint8_t *__restrict__ xb, int X[8]) {
323    const uint8_t* q = xb + 2;
324    const int off = (int) ((uintptr_t) q & 3);
325    const unsigned* p = (const unsigned*) (q - off);
326    const unsigned sh = (unsigned) off * 8;
327    unsigned v[9];
328#pragma unroll
329    /*
330    DPCT1098: The '*' expression is used instead of the __ldg call. These
331    two expressions do not provide the exact same functionality. Check the
332    generated code for potential precision and/or performance issues.
333    */
334    for (int j = 0; j < 8; ++j) v[j] = *(p + j);
335    /*
336    DPCT1098: The '*' expression is used instead of the __ldg call. These
337    two expressions do not provide the exact same functionality. Check the
338    generated code for potential precision and/or performance issues.
339    */
340    v[8] = off != 0 ? *(p + 8) : 0u;
341    unsigned n[8];
342    int hx = 0;
343#pragma unroll
344    for (int j = 0; j < 8; ++j) {
345        // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same
346        // source needs no CUDA-only intrinsic.
347        n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh);
348        hx = strata::dp4a(0x01010101, (int) n[j], hx);
349    }
350#pragma unroll
351    for (int h = 0; h < 2; ++h) {
352        const unsigned t0 = dpct::byte_level_permute(n[4 * h], n[4 * h + 1],
353                                                     0x5140); // a0 b0 a1 b1
354        const unsigned t1 = dpct::byte_level_permute(n[4 * h], n[4 * h + 1],
355                                                     0x7362); // a2 b2 a3 b3
356        const unsigned t2 = dpct::byte_level_permute(n[4 * h + 2], n[4 * h + 3],
357                                                     0x5140); // c0 d0 c1 d1
358        const unsigned t3 = dpct::byte_level_permute(n[4 * h + 2], n[4 * h + 3],
359                                                     0x7362); // c2 d2 c3 d3
360        X[4 * h + 0] =
361            (int)dpct::byte_level_permute(t0, t2, 0x5410); // a0 b0 c0 d0
362        X[4 * h + 1] =
363            (int)dpct::byte_level_permute(t0, t2, 0x7632); // a1 b1 c1 d1
364        X[4 * h + 2] =
365            (int)dpct::byte_level_permute(t1, t3, 0x5410); // a2 b2 c2 d2
366        X[4 * h + 3] =
367            (int)dpct::byte_level_permute(t1, t3, 0x7632); // a3 b3 c3 d3
368    }
369    return hx;
370}
371
372// `s` for one chunk: the eight expanded code words against the eight regrouped activation words.
373__dpct_inline__ int chunk_s(const int m[8], const int X[8]) {
374    int s = 0;
375#pragma unroll
376    for (int j = 0; j < 8; ++j) s = strata::dp4a(m[j], X[j], s);
377    return s;
378}
379
380/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each
381/// activation chunk is loaded and regrouped once for both rows.  Per row, the lane's chunks, their order, the float
382/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them.
383/*
384DPCT1110: The total declared local variable size in device function
385gu_pair_kernel exceeds 128 bytes and may cause high register pressure. Consult
386with your hardware vendor to find the total register size available and adjust
387the code, or use smaller sub-group size to avoid high register pressure.
388*/
389__dpct_inline__ void
390gu_pair_kernel(const uint8_t *__restrict__ blob_base,
391               const int32_t *__restrict__ slot_index, long long blob_bytes,
392               const uint8_t *__restrict__ x_q8_0,
393               const float *__restrict__ x_scales, float *__restrict__ gate_up,
394               int n_hits, const int32_t *__restrict__ d_count,
395               const int32_t *__restrict__ dst_index, int tok_div) {
396    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
397    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
398    const long long pair = (long long)item_ct1.get_group(2) * warps_per_block +
399                           (item_ct1.get_local_id(2) >> 5);
400    const long long total = (long long) n_hits * FF;
401    if (pair >= total) return;
402    const int h = (int) (pair / FF);
403    if (d_count != nullptr && h >= *d_count) return;
404    const int r = (int) (pair % FF);
405    const int lane = item_ct1.get_local_id(2) & 31;
406
407    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
408    if (tok_div > 0) {
409        const int tok = dst_index[h] / tok_div;
410        x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34;
411        if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32);
412    }
413    const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU;               // gate row; the up row follows it
414    const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2;
415    float acc_g = 0.0f, acc_u = 0.0f;
416    for (int c = lane; c < H / 32; c += 32) {
417        const uint8_t* xb = x_q8_0 + (size_t) c * 34;
418        const float dx = x_scales ? x_scales[c] : f16_ld(xb);
419        int X[8], m[8];
420        const int hx = load_x_chunk(xb, X);
421        expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m);
422        const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2);
423        acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx);
424        expand_codes(*(const sycl::uint2 *)(codes + ROW_GU + (size_t)c * 8), m);
425        const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
426        acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx);
427    }
428    const float sg = warp_sum(acc_g);
429    const float su = warp_sum(acc_u);
430    if (lane != 0) return;
431    gate_up[(size_t) h * FF + (size_t) r] = sg;                                // gate-major, as in `gu_kernel`
432    gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su;
433}
434
435/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both.
436/*
437DPCT1110: The total declared local variable size in device function
438down_pair_kernel exceeds 128 bytes and may cause high register pressure. Consult
439with your hardware vendor to find the total register size available and adjust
440the code, or use smaller sub-group size to avoid high register pressure.
441*/
442__dpct_inline__ void down_pair_kernel(const uint8_t *__restrict__ blob_base,
443                                      const int32_t *__restrict__ slot_index,
444                                      const int32_t *__restrict__ dst_index,
445                                      long long blob_bytes,
446                                      const uint8_t *__restrict__ h_q8_0,
447                                      const float *__restrict__ h_scales,
448                                      float *__restrict__ out, int n_hits,
449                                      const int32_t *__restrict__ d_count) {
450    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
451    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
452    const long long pair = (long long)item_ct1.get_group(2) * warps_per_block +
453                           (item_ct1.get_local_id(2) >> 5);
454    const long long total = (long long) n_hits * (H / 2);
455    if (pair >= total) return;
456    const int h = (int) (pair / (H / 2));
457    if (d_count != nullptr && h >= *d_count) return;
458    const int r = 2 * (int) (pair % (H / 2));
459    const int lane = item_ct1.get_local_id(2) & 31;
460
461    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
462    const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34;
463    const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr;
464    const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
465    const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
466    float acc0 = 0.0f, acc1 = 0.0f;
467    for (int c = lane; c < FF / 32; c += 32) {
468        const uint8_t* xb = xrow + (size_t) c * 34;
469        const float dx = xs ? xs[c] : f16_ld(xb);
470        int X[8], m[8];
471        const int hx = load_x_chunk(xb, X);
472        expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m);
473        const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
474        acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx);
475        expand_codes(*(const sycl::uint2 *)(codes + ROW_D + (size_t)c * 8), m);
476        const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
477        acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx);
478    }
479    const float s0 = warp_sum(acc0);
480    const float s1 = warp_sum(acc1);
481    if (lane != 0) return;
482    const size_t o = (size_t) dst_index[h] * H + (size_t) r;
483    out[o] = s0;
484    out[o + 1] = s1;
485}
486
487// The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the
488// subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales.
489__dpct_inline__ void activation_correction_kernel(const uint8_t *q8,
490                                                  const float *scales,
491                                                  float *hx, int chunks) {
492    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
493    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
494                  item_ct1.get_local_id(2);
495    if (c >= chunks) return;
496    const int8_t* q = (const int8_t*) (q8 + (size_t) c * 34 + 2);
497    int sum = 0;
498#pragma unroll
499    for (int j = 0; j < 32; ++j) sum += q[j];
500    /*
501    DPCT1013: The rounding mode could not be specified and the generated
502    code may have different accuracy than the original code. Verify the
503    correctness. SYCL math built-in function rounding mode is aligned with
504    OpenCL C 1.2 standard.
505    */
506    hx[c] = scales[c] * (float)sum;
507}
508
509__dpct_inline__ int dot4(const uint8_t *codes, const int8_t *q) {
510    const unsigned c = *codes;
511    const int cw = (int) ((c & 3u) | (((c >> 2) & 3u) << 8) |
512                          (((c >> 4) & 3u) << 16) | (((c >> 6) & 3u) << 24));
513    int xw;
514    memcpy(&xw, q, sizeof xw);
515    return strata::dp4a(cw, xw, 0);
516}
517
518__dpct_inline__ float row_dot_cpu_order(const uint8_t *codes,
519                                        const uint8_t *scales,
520                                        const uint8_t *xq, const float *xs,
521                                        const float *hx, int blocks, int lane) {
522    float acc = 0.0f;
523    float corr = 0.0f;
524    for (int b = 0; b < blocks; ++b) {
525        const float d = f16_at(scales + 2 * b);
526        const int lo = dot4(codes + b * 16 + lane,
527                           (const int8_t*) (xq + (size_t) (2 * b) * 34 + 2) + lane * 4);
528        const int hi = dot4(codes + b * 16 + 8 + lane,
529                           (const int8_t*) (xq + (size_t) (2 * b + 1) * 34 + 2) + lane * 4);
530        /*
531        DPCT1013: The rounding mode could not be specified and the generated
532        code may have different accuracy than the original code. Verify the
533        correctness. SYCL math built-in function rounding mode is aligned with
534        OpenCL C 1.2 standard.
535        */
536        acc = sycl::fma(d * xs[2 * b], (float)lo, acc);
537        /*
538        DPCT1013: The rounding mode could not be specified and the generated
539        code may have different accuracy than the original code. Verify the
540        correctness. SYCL math built-in function rounding mode is aligned with
541        OpenCL C 1.2 standard.
542        */
543        acc = sycl::fma(d * xs[2 * b + 1], (float)hi, acc);
544        if (lane == 0)
545            /*
546            DPCT1013: The rounding mode could not be specified and the
547            generated code may have different accuracy than the original code.
548            Verify the correctness. SYCL math built-in function rounding mode is
549            aligned with OpenCL C 1.2 standard.
550            */
551            corr = corr + d * hx[2 * b] + hx[2 * b + 1];
552    }
553    // _mm_add_ps(low128, high128), then two _mm_hadd_ps. The pair order is 4, 1, 2;
554    // a standard shuffle tree in the order 4, 2, 1 is a different floating-point expression.
555    constexpr unsigned mask = 0xffffffffu;
556    /*
557    DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
558    masked sub_group function which may not be supported by all compilers or
559    runtimes. You may need to adjust the code.
560    */
561    /*
562    DPCT1013: The rounding mode could not be specified and the generated
563    code may have different accuracy than the original code. Verify the
564    correctness. SYCL math built-in function rounding mode is aligned with
565    OpenCL C 1.2 standard.
566    */
567    acc = acc + dpct::experimental::shift_sub_group_left(
568                    mask, sycl::ext::oneapi::this_work_item::get_sub_group(),
569                    acc, 4, 8);
570    /*
571    DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
572    masked sub_group function which may not be supported by all compilers or
573    runtimes. You may need to adjust the code.
574    */
575    /*
576    DPCT1013: The rounding mode could not be specified and the generated
577    code may have different accuracy than the original code. Verify the
578    correctness. SYCL math built-in function rounding mode is aligned with
579    OpenCL C 1.2 standard.
580    */
581    acc = acc + dpct::experimental::shift_sub_group_left(
582                    mask, sycl::ext::oneapi::this_work_item::get_sub_group(),
583                    acc, 1, 8);
584    /*
585    DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
586    masked sub_group function which may not be supported by all compilers or
587    runtimes. You may need to adjust the code.
588    */
589    /*
590    DPCT1013: The rounding mode could not be specified and the generated
591    code may have different accuracy than the original code. Verify the
592    correctness. SYCL math built-in function rounding mode is aligned with
593    OpenCL C 1.2 standard.
594    */
595    acc = acc + dpct::experimental::shift_sub_group_left(
596                    mask, sycl::ext::oneapi::this_work_item::get_sub_group(),
597                    acc, 2, 8);
598    /*
599    DPCT1013: The rounding mode could not be specified and the generated
600    code may have different accuracy than the original code. Verify the
601    correctness. SYCL math built-in function rounding mode is aligned with
602    OpenCL C 1.2 standard.
603    */
604    return acc - corr; // Only lane zero is consumed.
605}
606
607template <bool DOWN>
608__dpct_inline__ void
609cpu_order_projection_kernel(const uint8_t *blob_base, const int32_t *slots,
610                            const int32_t *destinations, long long blob_bytes,
611                            const uint8_t *xq, const float *xs, const float *hx,
612                            float *out, int n_hits) {
613    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
614    constexpr int rows_per_hit = DOWN ? H : 2 * FF;
615    const int row = item_ct1.get_group(2) * (item_ct1.get_local_range(2) / 8) +
616                    item_ct1.get_local_id(2) / 8;
617    if (row >= n_hits * rows_per_hit) return;
618    const int h = row / rows_per_hit;
619    const int r = row % rows_per_hit;
620    const int lane = item_ct1.get_local_id(2) & 7;
621    const uint8_t* blob = blob_base + (size_t) slots[h] * (size_t) blob_bytes;
622    const int chunks_offset = DOWN ? h * (FF / 32) : 0;
623    const uint8_t* codes = DOWN ? blob + O_D_CODES + (size_t) r * ROW_D : blob + (size_t) r * ROW_GU;
624    const uint8_t* scales = DOWN ? blob + O_D_SCALES + (size_t) r * SC_D * 2
625                                 : blob + O_GU_SCALES + (size_t) r * SC_GU * 2;
626    const float value = row_dot_cpu_order(codes, scales, xq + (size_t) chunks_offset * 34,
627                                           xs + chunks_offset, hx + chunks_offset,
628                                           DOWN ? SC_D : SC_GU, lane);
629    if (lane != 0) return;
630    if (DOWN) out[(size_t) destinations[h] * H + r] = value;
631    else out[((r & 1) ? (size_t) n_hits * FF : 0) + (size_t) h * FF + (r >> 1)] = value;
632}
633
634__dpct_inline__ void cpu_order_swiglu_kernel(float *gu, int pairs) {
635    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
636    const int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
637                  item_ct1.get_local_id(2);
638    if (i >= pairs) return;
639    const float g = gu[i];
640    // Accurate fp32 exponential; __expf's approximation would introduce an additional source of error.
641    // CPU/GPU libc last-bit differences are diagnosed separately by the micro, not hidden with FP64 here.
642    const float eg = sycl::native::exp(-g);
643    /*
644    DPCT1013: The rounding mode could not be specified and the generated
645    code may have different accuracy than the original code. Verify the
646    correctness. SYCL math built-in function rounding mode is aligned with
647    OpenCL C 1.2 standard.
648    */
649    gu[i] = g / (1.0f + eg) * gu[pairs + i];
650}
651
652__dpct_inline__ void cpu_order_quantize_kernel(const float *x, uint8_t *blocks,
653                                               float *scales, float *hx,
654                                               int chunks) {
655    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
656    const int c = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
657                  item_ct1.get_local_id(2);
658    if (c >= chunks) return;
659    const float* xb = x + c * 32;
660    uint8_t* out = blocks + (size_t) c * 34;
661    float amax = 0.0f;
662#pragma unroll
663    for (int j = 0; j < 32; ++j) amax = sycl::fmax(amax, sycl::fabs(xb[j]));
664    /*
665    DPCT1013: The rounding mode could not be specified and the generated
666    code may have different accuracy than the original code. Verify the
667    correctness. SYCL math built-in function rounding mode is aligned with
668    OpenCL C 1.2 standard.
669    */
670    const float s = amax > 0.0f ? amax / 127.0f : 0.0f;
671    /*
672    DPCT1013: The rounding mode could not be specified and the generated
673    code may have different accuracy than the original code. Verify the
674    correctness. SYCL math built-in function rounding mode is aligned with
675    OpenCL C 1.2 standard.
676    */
677    const float inv = s > 0.0f ? 1.0f / s : 0.0f;
678    scales[c] = s;
679    const uint16_t bits = sycl::bit_cast<unsigned short, sycl::half>(
680        sycl::vec<float, 1>(s)
681            .convert<sycl::half, sycl::rounding_mode::rte>()[0]);
682    out[0] = (uint8_t) bits;
683    out[1] = (uint8_t) (bits >> 8);
684    int sum = 0;
685    for (int j = 0; j < 32; ++j) {
686        /*
687        DPCT1013: The rounding mode could not be specified and the generated
688        code may have different accuracy than the original code. Verify the
689        correctness. SYCL math built-in function rounding mode is aligned with
690        OpenCL C 1.2 standard.
691        */
692        const float t = xb[j] * inv;
693        /*
694        DPCT1013: The rounding mode could not be specified and the generated
695        code may have different accuracy than the original code. Verify the
696        correctness. SYCL math built-in function rounding mode is aligned with
697        OpenCL C 1.2 standard.
698        */
699        int v = (int) (t + (t >= 0.0f ? 0.5f : -0.5f));   // SYCL port: dpct dropped the parentheses (it rounded every value to 0)
700        v = v < -127 ? -127 : (v > 127 ? 127 : v);
701        out[2 + j] = (uint8_t) (int8_t) v;
702        sum += v;
703    }
704    /*
705    DPCT1013: The rounding mode could not be specified and the generated
706    code may have different accuracy than the original code. Verify the
707    correctness. SYCL math built-in function rounding mode is aligned with
708    OpenCL C 1.2 standard.
709    */
710    hx[c] = s * (float)sum;
711}
712
713constexpr int THREADS = 256;
714
715void check(const char* who, void* stream) {
716    /*
717    DPCT1010: SYCL uses exceptions to report errors and does not use the
718    error codes. The cudaGetLastError function call was replaced with 0. You
719    need to rewrite this code.
720    */
721    const dpct::err0 e = 0;
722
723    // Deliberately NOT synchronising for a non-null stream: this is called once per layer from a captured
724    // graph's worth of work, and `finish()`'s null-stream sync in `s_gemv.cu` is the pattern that made a whole
725    // round of measurements the driver's cost instead of the kernel's (Memory/ERRORS.md RC-7).
726    (void) stream;
727}
728
729// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or
730// `moe_grouped_select_old` (the parity test runs both in one process).  The environment is read once, on first use;
731// the choice is made at each launch, so a captured graph keeps the kernels it was captured with.
732std::atomic<int> g_select_old{-1};
733// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query.
734std::atomic<int> g_last_path{-1};
735
736bool old_kernels() {
737    const int s = g_select_old.load(std::memory_order_relaxed);
738    if (s >= 0) return s != 0;
739    static const bool env = [] {
740        const char* e = std::getenv("STRATA_OLD_GROUPED");
741        return e != nullptr && e[0] == '1';
742    }();
743    return env;
744}
745
746// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of
747// capacity.  The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer
748// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures.  Bitwise
749// the same either way; default 0 (always the new kernels).  Ignored while `moe_grouped_select_old` forces a choice.
750long long pair_min_hits() {
751    if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0;
752    static const long long n = [] {
753        const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS");
754        return e != nullptr ? std::atoll(e) : 0LL;
755    }();
756    return n;
757}
758
759// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation
760// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which
761// needs an 8-byte aligned arena and slot size (the grouped kernels above already did).  Anything else keeps the
762// previous kernels rather than issuing a misaligned load.
763bool new_grouped(const void* x_q8_0, const void* scratch) {
764    const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0;
765    g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
766    return fast;
767}
768
769bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) {
770    const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 &&
771                      cap >= pair_min_hits();
772    g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
773    return fast;
774}
775
776// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows).
777void launch_hit_gu(bool fast, const uint8_t *blob_base,
778                   const int32_t *slot_index, long long blob_bytes,
779                   const uint8_t *x_q8_0, const float *x_scales, float *gate_up,
780                   long long cap, const int32_t *d_count,
781                   const int32_t *dst_index, int tok_div, dpct::queue_ptr cs) {
782    const int warps = THREADS / 32;
783    if (fast) {
784        const long long pairs = cap * (long long) FF;
785        {
786            auto exp_props = sycl::ext::oneapi::experimental::properties{
787                sycl::ext::oneapi::experimental::use_root_sync};
788
789            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gu_pair_kernel_787004>>(
790                sycl::nd_range<3>(
791                    sycl::range(1, 1, (unsigned)((pairs + warps - 1) / warps)) *
792                        sycl::range(1, 1, THREADS),
793                    sycl::range(1, 1, THREADS)),
794                exp_props,
795                [=](sycl::nd_item<3> item_ct1)
796                    [[sycl::reqd_sub_group_size(32)]] {
797                        gu_pair_kernel(blob_base, slot_index, blob_bytes,
798                                       x_q8_0, x_scales, gate_up, (int)cap,
799                                       d_count, dst_index, tok_div);
800                    });
801        }
802    } else {
803        const long long rows = cap * 2LL * FF;
804        {
805            auto exp_props = sycl::ext::oneapi::experimental::properties{
806                sycl::ext::oneapi::experimental::use_root_sync};
807
808            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gu_kernel_55bc52>>(
809                sycl::nd_range<3>(
810                    sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
811                        sycl::range(1, 1, THREADS),
812                    sycl::range(1, 1, THREADS)),
813                exp_props,
814                [=](sycl::nd_item<3> item_ct1)
815                    [[sycl::reqd_sub_group_size(32)]] {
816                        gu_kernel(blob_base, slot_index, blob_bytes, x_q8_0,
817                                  x_scales, gate_up, (int)cap, d_count,
818                                  dst_index, tok_div);
819                    });
820        }
821    }
822}
823
824void launch_hit_down(bool fast, const uint8_t *blob_base,
825                     const int32_t *slot_index, const int32_t *dst_index,
826                     long long blob_bytes, const uint8_t *h_q8_0,
827                     const float *h_scales, float *out, long long cap,
828                     const int32_t *d_count, dpct::queue_ptr cs) {
829    const int warps = THREADS / 32;
830    if (fast) {
831        const long long pairs = cap * (long long) (H / 2);
832        {
833            auto exp_props = sycl::ext::oneapi::experimental::properties{
834                sycl::ext::oneapi::experimental::use_root_sync};
835
836            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class down_pair_kernel_7d15d9>>(
837                sycl::nd_range<3>(
838                    sycl::range(1, 1, (unsigned)((pairs + warps - 1) / warps)) *
839                        sycl::range(1, 1, THREADS),
840                    sycl::range(1, 1, THREADS)),
841                exp_props,
842                [=](sycl::nd_item<3> item_ct1)
843                    [[sycl::reqd_sub_group_size(32)]] {
844                        down_pair_kernel(blob_base, slot_index, dst_index,
845                                         blob_bytes, h_q8_0, h_scales, out,
846                                         (int)cap, d_count);
847                    });
848        }
849    } else {
850        const long long rows = cap * (long long) H;
851        {
852            auto exp_props = sycl::ext::oneapi::experimental::properties{
853                sycl::ext::oneapi::experimental::use_root_sync};
854
855            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class down_kernel_b3587f>>(
856                sycl::nd_range<3>(
857                    sycl::range(1, 1, (unsigned)((rows + warps - 1) / warps)) *
858                        sycl::range(1, 1, THREADS),
859                    sycl::range(1, 1, THREADS)),
860                exp_props,
861                [=](sycl::nd_item<3> item_ct1)
862                    [[sycl::reqd_sub_group_size(32)]] {
863                        down_kernel(blob_base, slot_index, dst_index,
864                                    blob_bytes, h_q8_0, h_scales, out, (int)cap,
865                                    d_count);
866                    });
867        }
868    }
869}
870
871}  // namespace
872
873void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); }
874
875int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); }
876
877uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) {
878    if (n_hits <= 0) return 0;
879    const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4;
880    const uint64_t q8 = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 34;
881    // R4.2h: the fp32 scales for the INTERMEDIATE's own quantization, one per 32-element chunk per hit.
882    const uint64_t hs = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 4;
883    const uint64_t xh = (uint64_t) (n_embd / 32) * 4;
884    return ((gu + 15) & ~15ull) + ((q8 + 15) & ~15ull) + 2 * ((hs + 15) & ~15ull) +
885           ((xh + 15) & ~15ull);
886}
887
888void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
889                        int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out,
890                        void* stream, const float* x_scales) {
891    if (n_hits <= 0) return;
892    dpct::queue_ptr cs = strata::q_of(stream);
893    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits);
894
895    const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
896    const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
897    float* gate_up = (float*) scratch;
898    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
899    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
900
901    // 1. gate + up, one launch for every row of every hit.
902    {
903        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr,
904                      0, cs);
905        check("moe_hit_grouped_s2/gu", stream);
906    }
907    // 2. silu(gate) * up.
908    {
909        const long long pairs = n_hits * (long long) FF;
910        const unsigned blocks = (unsigned) ((pairs + THREADS - 1) / THREADS);
911        {
912            auto exp_props = sycl::ext::oneapi::experimental::properties{
913                sycl::ext::oneapi::experimental::use_root_sync};
914
915            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class swiglu_kernel_792534>>(
916                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
917                                      sycl::range(1, 1, THREADS),
918                                  sycl::range(1, 1, THREADS)),
919                exp_props, [=](sycl::nd_item<3> item_ct1) {
920                    swiglu_kernel(gate_up, pairs);
921                });
922        }
923        check("moe_hit_grouped_s2/swiglu", stream);
924    }
925    // 3. the intermediate's own contract, which is `ggml_mul_mat`'s rule and NOT a choice: the down weight is
926    //    Q2_0, whose `vec_dot_type` is Q8_0.  `gate_up` holds the pairs; the product went into the first half.
927    //    **R4.2h: the CPU quantizes this intermediate into `a2` with fp32 scales too** (`expert.cpp:232`), so
928    //    when the caller supplies `x_scales` the intermediate gets the CPU's contract as well - otherwise the
929    //    down projection would keep the very disagreement the gate/up projection just had removed.
930    if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, n_hits * (int64_t) FF, stream);
931    else quantize_q8_0(gate_up, h_q8_0, n_hits * (int64_t) FF, stream);
932    // 4. down.
933    {
934        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
935                        x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs);
936        check("moe_hit_grouped_s2/down", stream);
937    }
938}
939
940namespace {
941// Plan v0.3 P4 token graph: which of this layer's routed experts are resident, decided ON THE DEVICE from the
942// static residency row, so no host step sits between the ring and the hit kernels.  One warp; k <= 32.
943__dpct_inline__ void hit_select_kernel(const int32_t *__restrict__ ids,
944                                       const int32_t *__restrict__ res_row,
945                                       int k, int n_expert,
946                                       int32_t *__restrict__ slot,
947                                       int32_t *__restrict__ dst,
948                                       int32_t *__restrict__ count) {
949    const int lane =
950        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
951    int s = -1;
952    if (lane < k) {
953        const int e = ids[lane];
954        if (e >= 0 && e < n_expert) s = res_row[e];
955    }
956    const unsigned hit = sycl::reduce_over_group(
957        sycl::ext::oneapi::this_work_item::get_sub_group(),
958        (0xffffffffu &
959         (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
960                     .get_local_linear_id())) &&
961                s >= 0
962            ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
963                          .get_local_linear_id())
964            : 0,
965        sycl::ext::oneapi::plus<>());
966    if (s >= 0) {
967        const int at = sycl::popcount(hit & ((1u << lane) - 1u));
968        slot[at] = s;
969        dst[at] = lane;
970    }
971    if (lane == 0) *count = sycl::popcount(hit);
972}
973
974// Plan v0.3 P6: the same for up to 128 routed entries (a verify window of T tokens x k): four warps, ballots
975// compacted in entry order.
976__dpct_inline__ void hit_select_multi_kernel(
977    const int32_t *__restrict__ ids, const int32_t *__restrict__ res_row, int n,
978    int n_expert, int32_t *__restrict__ slot, int32_t *__restrict__ dst,
979    int32_t *__restrict__ count) {
980    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
981auto &warp_count = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[4]>(
982    sycl::ext::oneapi::this_work_item::get_work_group<3>());
983    const int i = item_ct1.get_local_id(2), lane = i & 31, warp = i >> 5;
984    int s = -1;
985    if (i < n) {
986        const int e = ids[i];
987        if (e >= 0 && e < n_expert) s = res_row[e];
988    }
989    const unsigned hit = sycl::reduce_over_group(
990        sycl::ext::oneapi::this_work_item::get_sub_group(),
991        (0xffffffffu &
992         (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
993                     .get_local_linear_id())) &&
994                s >= 0
995            ? (0x1 << sycl::ext::oneapi::this_work_item::get_sub_group()
996                          .get_local_linear_id())
997            : 0,
998        sycl::ext::oneapi::plus<>());
999    if (lane == 0) warp_count[warp] = sycl::popcount(hit);
1000    item_ct1.barrier(sycl::access::fence_space::local_space);
1001    int before = 0;
1002#pragma unroll
1003    for (int w = 0; w < warp; ++w) before += warp_count[w];
1004    if (s >= 0) {
1005        const int at = before + sycl::popcount(hit & ((1u << lane) - 1u));
1006        slot[at] = s;
1007        dst[at] = i;
1008    }
1009    if (i == 0) *count = warp_count[0] + warp_count[1] + warp_count[2] + warp_count[3];
1010}
1011
1012__dpct_inline__ void add_hits_kernel(float *__restrict__ parts,
1013                                     const float *__restrict__ hit_out,
1014                                     const int32_t *__restrict__ dst,
1015                                     const int32_t *__restrict__ count,
1016                                     int n_embd) {
1017    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1018    const int h = item_ct1.get_group(1);
1019    if (h >= *count) return;
1020    const size_t row = (size_t) dst[h] * (size_t) n_embd;
1021#pragma unroll
1022    for (int i = item_ct1.get_group(2) * item_ct1.get_local_range(2) +
1023                 item_ct1.get_local_id(2);
1024         i < n_embd;
1025         i += item_ct1.get_group_range(2) * item_ct1.get_local_range(2))
1026        parts[row + i] += hit_out[row + i];
1027}
1028}  // namespace
1029
1030void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst,
1031                    int32_t* count, void* stream) {
1032    if (k < 1 || k > 32) { std::fprintf(stderr, "moe_hit_select: k must be 1..32\n"); std::exit(1); }
1033    {
1034        auto exp_props = sycl::ext::oneapi::experimental::properties{
1035            sycl::ext::oneapi::experimental::use_root_sync};
1036
1037        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1038            ->template parallel_for<dpct_kernel_name<class hit_select_kernel_f87f42>>(
1039                sycl::nd_range<3>(sycl::range(1, 1, 32), sycl::range(1, 1, 32)),
1040                exp_props,
1041                [=](sycl::nd_item<3> item_ct1)
1042                    [[sycl::reqd_sub_group_size(32)]] {
1043                        hit_select_kernel(ids, res_row, k, n_expert, slot, dst,
1044                                          count);
1045                    });
1046    }
1047    check("moe_hit_select", stream);
1048}
1049
1050void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
1051                            const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0,
1052                            void* scratch, float* out, void* stream, const float* x_scales) {
1053    if (cap <= 0) return;
1054    dpct::queue_ptr cs = strata::q_of(stream);
1055    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
1056    const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
1057    const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
1058    float* gate_up = (float*) scratch;
1059    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
1060    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
1061    {
1062        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0,
1063                      cs);
1064        check("moe_hit_grouped_s2_dev/gu", stream);
1065    }
1066    {
1067        const long long pairs = cap * (long long) FF;
1068        {
1069            auto exp_props = sycl::ext::oneapi::experimental::properties{
1070                sycl::ext::oneapi::experimental::use_root_sync};
1071
1072            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class swiglu_kernel_5aa9a9>>(
1073                sycl::nd_range<3>(
1074                    sycl::range(1, 1,
1075                                (unsigned)((pairs + THREADS - 1) / THREADS)) *
1076                        sycl::range(1, 1, THREADS),
1077                    sycl::range(1, 1, THREADS)),
1078                exp_props, [=](sycl::nd_item<3> item_ct1) {
1079                    swiglu_kernel(gate_up, pairs);
1080                });
1081        }
1082        check("moe_hit_grouped_s2_dev/swiglu", stream);
1083    }
1084    if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
1085    else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
1086    {
1087        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
1088                        x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
1089        check("moe_hit_grouped_s2_dev/down", stream);
1090    }
1091}
1092
1093void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst,
1094                          int32_t* count, void* stream) {
1095    if (n < 1 || n > 128) { std::fprintf(stderr, "moe_hit_select_multi: n must be 1..128\n"); std::exit(1); }
1096    {
1097        auto exp_props = sycl::ext::oneapi::experimental::properties{
1098            sycl::ext::oneapi::experimental::use_root_sync};
1099
1100        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1101            ->template parallel_for<
1102                dpct_kernel_name<class hit_select_multi_kernel_4749ea>>(
1103                sycl::nd_range<3>(sycl::range(1, 1, 128),
1104                                  sycl::range(1, 1, 128)),
1105                exp_props,
1106                [=](sycl::nd_item<3> item_ct1)
1107                    [[sycl::reqd_sub_group_size(32)]] {
1108                        hit_select_multi_kernel(ids, res_row, n, n_expert, slot,
1109                                                dst, count);
1110                    });
1111    }
1112    check("moe_hit_select_multi", stream);
1113}
1114
1115void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
1116                              const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0,
1117                              const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) {
1118    if (cap <= 0) return;
1119    dpct::queue_ptr cs = strata::q_of(stream);
1120    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
1121    const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
1122    const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
1123    float* gate_up = (float*) scratch;
1124    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
1125    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
1126    {
1127        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index,
1128                      k_per_token, cs);
1129        check("moe_hit_grouped_s2_multi/gu", stream);
1130    }
1131    {
1132        const long long pairs = cap * (long long) FF;
1133        {
1134            auto exp_props = sycl::ext::oneapi::experimental::properties{
1135                sycl::ext::oneapi::experimental::use_root_sync};
1136
1137            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class swiglu_kernel_a0c31a>>(
1138                sycl::nd_range<3>(
1139                    sycl::range(1, 1,
1140                                (unsigned)((pairs + THREADS - 1) / THREADS)) *
1141                        sycl::range(1, 1, THREADS),
1142                    sycl::range(1, 1, THREADS)),
1143                exp_props, [=](sycl::nd_item<3> item_ct1) {
1144                    swiglu_kernel(gate_up, pairs);
1145                });
1146        }
1147        check("moe_hit_grouped_s2_multi/swiglu", stream);
1148    }
1149    if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap * (int64_t) FF, stream);
1150    else quantize_q8_0(gate_up, h_q8_0, cap * (int64_t) FF, stream);
1151    {
1152        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
1153                        x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
1154        check("moe_hit_grouped_s2_multi/down", stream);
1155    }
1156}
1157
1158namespace {
1159// Plan v0.3 P6: experts GROUPED - one blob pointer per group (a VRAM slot or a mapped host blob read over PCIe),
1160// every entry of the group (a token routed to that expert) computed from ONE read of each row.  Per entry the
1161// arithmetic is `row_dot_s2_q8`'s, chunk by chunk in the same lane order, so every entry is bitwise the per-entry
1162// hit kernel's.
1163constexpr int GU_CHUNKS = (H / 32 + 31) / 32;   // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes)
1164constexpr int GMAX = 8;                          // entries per group (tokens routed to one expert in a window)
1165// a group holds one entry per token of the window routed to its expert, and the kernels below keep at
1166// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word.
1167static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries");
1168constexpr int GU_ROWS = 32;                      // gate/up rows per block: 4 per warp
1169constexpr int D_ROWS = 64;                       // down rows per block: 8 per warp
1170
1171// One activation chunk's contribution, `row_dot_s2_q8`'s inner body with the 32 int8 of the chunk already in
1172// aligned words: same dp4a sequence, same float expression, so the result is bitwise the per-entry kernel's.
1173__dpct_inline__ float chunk_dot(sycl::uint2 cb, const int *xw, float dw,
1174                                float dx) {
1175    const uint8_t* cbytes = (const uint8_t*) &cb;
1176    int s = 0, hx = 0;
1177    const int ones = 0x01010101;
1178#pragma unroll
1179    for (int j = 0; j < 8; ++j) {
1180        const unsigned cbyte = cbytes[j];
1181        const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) |
1182                              (((cbyte >> 6) & 3u) << 24));
1183        s = strata::dp4a(cw, xw[j], s);
1184        hx = strata::dp4a(ones, xw[j], hx);
1185    }
1186    return dw * dx * (float) (s - hx);
1187}
1188
1189// Gate/up: a block = GU_ROWS rows of ONE group.  The group's activations (each entry's token row of x_q8_0 and
1190// its fp32 scales) are staged once into shared memory as aligned words; each warp then walks its rows, loading
1191// each lane's code chunks once and dotting them with every entry.
1192/*
1193DPCT1110: The total declared local variable size in device function
1194gu_grouped_kernel exceeds 128 bytes and may cause high register pressure.
1195Consult with your hardware vendor to find the total register size available and
1196adjust the code, or use smaller sub-group size to avoid high register pressure.
1197*/
1198__dpct_inline__ void gu_grouped_kernel(
1199    const unsigned long long *__restrict__ grp_ptr,
1200    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
1201    const int32_t *__restrict__ ent_tok, const uint8_t *__restrict__ x_q8_0,
1202    const float *__restrict__ x_scales, float *__restrict__ gate_up,
1203    int cap_entries) {
1204    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1205auto &xs_q =
1206    *sycl::ext::oneapi::group_local_memory_for_overwrite<int[GMAX][H / 4]>(
1207        sycl::ext::oneapi::this_work_item::get_work_group<
1208            3>()); // the entries' int8 activations as words (2560 B each)
1209    auto &xs_d = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1210        float[GMAX][H / 32]>(
1211        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1212    const int g = item_ct1.get_group(1);
1213    if (g >= *n_groups) return;
1214    const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
1215    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1216    for (int i = t; i < ne * (H / 32); i += item_ct1.get_local_range(2)) {
1217        const int k = i / (H / 32), c = i - k * (H / 32);
1218        const uint8_t* xb = x_q8_0 + (size_t) ent_tok[e0 + k] * (size_t) (H / 32) * 34 + (size_t) c * 34;
1219        xs_d[k][c] = x_scales ? x_scales[(size_t) ent_tok[e0 + k] * (H / 32) + c] : f16_at(xb);
1220        const int8_t* q = (const int8_t*) (xb + 2);
1221#pragma unroll
1222        for (int w = 0; w < 8; ++w) {
1223            int v;
1224            memcpy(&v, q + 4 * w, 4);
1225            xs_q[k][c * 8 + w] = v;
1226        }
1227    }
1228    item_ct1.barrier(sycl::access::fence_space::local_space);
1229    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1230    const int row0 = item_ct1.get_group(2) * GU_ROWS;
1231    for (int rr = warp; rr < GU_ROWS; rr += 8) {
1232        const int i = row0 + rr;
1233        const uint8_t* codes = blob + (size_t) i * ROW_GU;
1234        const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
1235        sycl::uint2 cb[GU_CHUNKS];
1236        float dw[GU_CHUNKS];
1237#pragma unroll
1238        for (int q = 0; q < GU_CHUNKS; ++q) {
1239            const int c = lane + 32 * q;
1240            if (c < H / 32) {
1241                cb[q] = *(const sycl::uint2 *)(codes + (size_t)c * 8);
1242                dw[q] = f16_at(scales + (size_t) (c >> 1) * 2);
1243            }
1244        }
1245        for (int k = 0; k < ne; ++k) {
1246            float acc = 0.0f;
1247#pragma unroll
1248            for (int q = 0; q < GU_CHUNKS; ++q) {
1249                const int c = lane + 32 * q;
1250                if (c >= H / 32) break;
1251                acc += chunk_dot(cb[q], &xs_q[k][c * 8], dw[q], xs_d[k][c]);
1252            }
1253            const float sum = warp_sum(acc);
1254            if (lane == 0) {
1255                const int e = e0 + k, r = i >> 1;
1256                const size_t base = (i & 1) ? ((size_t) cap_entries * FF + (size_t) e * FF) : ((size_t) e * FF);
1257                gate_up[base + (size_t) r] = sum;
1258            }
1259        }
1260    }
1261}
1262
1263// Down: a block = D_ROWS rows of ONE group; the entries' quantized intermediates staged once.  A down row is 20
1264// chunks, so lanes 0..19 each hold one chunk, as in the per-entry kernel.
1265__dpct_inline__ void down_grouped_kernel(
1266    const unsigned long long *__restrict__ grp_ptr,
1267    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
1268    const int32_t *__restrict__ ent_dst, const uint8_t *__restrict__ h_q8_0,
1269    const float *__restrict__ h_scales, float *__restrict__ out) {
1270    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1271auto &hs_q =
1272    *sycl::ext::oneapi::group_local_memory_for_overwrite<int[GMAX][FF / 4]>(
1273        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1274    auto &hs_d = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1275        float[GMAX][FF / 32]>(
1276        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1277    const int g = item_ct1.get_group(1);
1278    if (g >= *n_groups) return;
1279    const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
1280    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1281    for (int i = t; i < ne * (FF / 32); i += item_ct1.get_local_range(2)) {
1282        const int k = i / (FF / 32), c = i - k * (FF / 32);
1283        const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) (FF / 32) * 34 + (size_t) c * 34;
1284        hs_d[k][c] = h_scales ? h_scales[(size_t) (e0 + k) * (FF / 32) + c] : f16_at(xb);
1285        const int8_t* q = (const int8_t*) (xb + 2);
1286#pragma unroll
1287        for (int w = 0; w < 8; ++w) {
1288            int v;
1289            memcpy(&v, q + 4 * w, 4);
1290            hs_q[k][c * 8 + w] = v;
1291        }
1292    }
1293    item_ct1.barrier(sycl::access::fence_space::local_space);
1294    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1295    const int row0 = item_ct1.get_group(2) * D_ROWS;
1296    for (int rr = warp; rr < D_ROWS; rr += 8) {
1297        const int r = row0 + rr;
1298        const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
1299        const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
1300        const int c = lane;
1301        sycl::uint2 cb = sycl::uint2(0, 0);
1302        float dw = 0.0f;
1303        if (c < FF / 32) {
1304            cb = *(const sycl::uint2 *)(codes + (size_t)c * 8);
1305            dw = f16_at(scales + (size_t) (c >> 1) * 2);
1306        }
1307        for (int k = 0; k < ne; ++k) {
1308            float acc = 0.0f;
1309            if (c < FF / 32) acc += chunk_dot(cb, &hs_q[k][c * 8], dw, hs_d[k][c]);
1310            const float sum = warp_sum(acc);
1311            if (lane == 0) out[(size_t) ent_dst[e0 + k] * H + r] = sum;
1312        }
1313    }
1314}
1315
1316// ---- The grouped kernels with the staged activations laid out for the reads.
1317//
1318// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.**  `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so
1319// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes
1320// `hx`, which depends on the entry alone, for every row.  Here the staging writes, once per (entry, chunk):
1321//
1322//     xs_w[j][k * NC + c]   word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words
1323//     xs_dh[k * NC + c]     (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a`
1324//
1325// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side
1326// conflicts and no padding is needed.  Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`,
1327// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not
1328// once per entry.  Per (row, entry) the lane's chunks, their order, the float expression and the shuffle
1329// reduction are the kernels' above, so every output is bitwise theirs.
1330
1331// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`.
1332template <int STRIDE>
1333__dpct_inline__ void stage_chunk(const uint8_t *__restrict__ xb, float dx,
1334                                 int *xs_w, sycl::int2 *xs_dh, int i) {
1335    int X[8];
1336    const int hx = load_x_chunk(xb, X);
1337#pragma unroll
1338    for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j];
1339    xs_dh[i] = sycl::int2(sycl::bit_cast<int>(dx), hx);
1340}
1341
1342/*
1343DPCT1110: The total declared local variable size in device function
1344gu_grouped_t_kernel exceeds 128 bytes and may cause high register pressure.
1345Consult with your hardware vendor to find the total register size available and
1346adjust the code, or use smaller sub-group size to avoid high register pressure.
1347*/
1348__dpct_inline__ void gu_grouped_t_kernel(
1349    const unsigned long long *__restrict__ grp_ptr,
1350    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
1351    const int32_t *__restrict__ ent_tok, const uint8_t *__restrict__ x_q8_0,
1352    const float *__restrict__ x_scales, float *__restrict__ gate_up,
1353    int cap_entries) {
1354    #pragma clang fp contract(off)   // SYCL port: round as the previous kernels do (see tools/fixups.py)
1355    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1356    constexpr int NC = H / 32;
1357    auto &xs_w = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1358        int[8 * GMAX * NC]>(
1359        sycl::ext::oneapi::this_work_item::get_work_group<
1360            3>()); // 20 KB: word j of entry k's chunk c at [j][k * NC + c]
1361    auto &xs_dh = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1362        sycl::int2[GMAX * NC]>(
1363        sycl::ext::oneapi::this_work_item::get_work_group<3>()); // 5 KB: (dx as
1364                                                                 // bits, hx)
1365    const int g = item_ct1.get_group(1);
1366    if (g >= *n_groups) return;
1367    const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
1368    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1369    for (int i = t; i < ne * NC; i += item_ct1.get_local_range(2)) {
1370        const int k = i / NC, c = i - k * NC;
1371        const int tok = ent_tok[e0 + k];
1372        const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34;
1373        const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb);
1374        stage_chunk<GMAX * NC>(xb, dx, xs_w, xs_dh, i);
1375    }
1376    item_ct1.barrier(sycl::access::fence_space::local_space);
1377    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1378    const int row0 = item_ct1.get_group(2) *
1379                     GU_ROWS; // even: a pair is always (gate r, up r)
1380    for (int pp = warp; pp < GU_ROWS / 2; pp += 8) {
1381        const int i = row0 + 2 * pp;
1382        const uint8_t* codes = blob + (size_t) i * ROW_GU;
1383        const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
1384        int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8];
1385        float dw0[GU_CHUNKS], dw1[GU_CHUNKS];
1386#pragma unroll
1387        for (int q = 0; q < GU_CHUNKS; ++q) {
1388            const int c = lane + 32 * q;
1389            if (c < NC) {
1390                expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8),
1391                             m0[q]);
1392                expand_codes(
1393                    *(const sycl::uint2 *)(codes + ROW_GU + (size_t)c * 8),
1394                    m1[q]);
1395                dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2);
1396                dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
1397            }
1398        }
1399        for (int k = 0; k < ne; ++k) {
1400            float acc0 = 0.0f, acc1 = 0.0f;
1401#pragma unroll
1402            for (int q = 0; q < GU_CHUNKS; ++q) {
1403                const int c = lane + 32 * q;
1404                if (c >= NC) break;
1405                const int at = k * NC + c;
1406                int X[8];
1407#pragma unroll
1408                for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (GMAX * NC) + at];
1409                const sycl::int2 dh = xs_dh[at];
1410                const float dx = sycl::bit_cast<float>(dh.x());
1411                acc0 += dw0[q] * dx * (float)(chunk_s(m0[q], X) - dh.y());
1412                acc1 += dw1[q] * dx * (float)(chunk_s(m1[q], X) - dh.y());
1413            }
1414            const float s0 = warp_sum(acc0);
1415            const float s1 = warp_sum(acc1);
1416            if (lane == 0) {
1417                const int e = e0 + k, r = i >> 1;
1418                gate_up[(size_t) e * FF + (size_t) r] = s0;
1419                gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1;
1420            }
1421        }
1422    }
1423}
1424
1425/*
1426DPCT1110: The total declared local variable size in device function
1427down_grouped_t_kernel exceeds 128 bytes and may cause high register pressure.
1428Consult with your hardware vendor to find the total register size available and
1429adjust the code, or use smaller sub-group size to avoid high register pressure.
1430*/
1431__dpct_inline__ void down_grouped_t_kernel(
1432    const unsigned long long *__restrict__ grp_ptr,
1433    const int32_t *__restrict__ grp_start, const int32_t *__restrict__ n_groups,
1434    const int32_t *__restrict__ ent_dst, const uint8_t *__restrict__ h_q8_0,
1435    const float *__restrict__ h_scales, float *__restrict__ out) {
1436    #pragma clang fp contract(off)   // SYCL port: round as the previous kernels do (see tools/fixups.py)
1437    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1438    constexpr int NC = FF / 32;
1439    auto &hs_w = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1440        int[8 * GMAX * NC]>(
1441        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1442    auto &hs_dh = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1443        sycl::int2[GMAX * NC]>(
1444        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1445    const int g = item_ct1.get_group(1);
1446    if (g >= *n_groups) return;
1447    const int e0 = grp_start[g], ne = sycl::min(grp_start[g + 1] - e0, GMAX);
1448    const int t = item_ct1.get_local_id(2), lane = t & 31, warp = t >> 5;
1449    for (int i = t; i < ne * NC; i += item_ct1.get_local_range(2)) {
1450        const int k = i / NC, c = i - k * NC;
1451        const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34;
1452        const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb);
1453        stage_chunk<GMAX * NC>(xb, dx, hs_w, hs_dh, i);
1454    }
1455    item_ct1.barrier(sycl::access::fence_space::local_space);
1456    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1457    const int row0 = item_ct1.get_group(2) * D_ROWS;
1458    for (int pp = warp; pp < D_ROWS / 2; pp += 8) {
1459        const int r = row0 + 2 * pp;
1460        const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
1461        const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
1462        const int c = lane;                                // lanes 0..19 hold one chunk each, as above
1463        int m0[8], m1[8];
1464        float dw0 = 0.0f, dw1 = 0.0f;
1465        if (c < NC) {
1466            expand_codes(*(const sycl::uint2 *)(codes + (size_t)c * 8), m0);
1467            expand_codes(*(const sycl::uint2 *)(codes + ROW_D + (size_t)c * 8),
1468                         m1);
1469            dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
1470            dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
1471        }
1472        for (int k = 0; k < ne; ++k) {
1473            float acc0 = 0.0f, acc1 = 0.0f;
1474            if (c < NC) {
1475                const int at = k * NC + c;
1476                int X[8];
1477#pragma unroll
1478                for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (GMAX * NC) + at];
1479                const sycl::int2 dh = hs_dh[at];
1480                const float dx = sycl::bit_cast<float>(dh.x());
1481                acc0 += dw0 * dx * (float)(chunk_s(m0, X) - dh.y());
1482                acc1 += dw1 * dx * (float)(chunk_s(m1, X) - dh.y());
1483            }
1484            const float s0 = warp_sum(acc0);
1485            const float s1 = warp_sum(acc1);
1486            if (lane == 0) {
1487                const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r;
1488                out[o] = s0;
1489                out[o + 1] = s1;
1490            }
1491        }
1492    }
1493}
1494}  // namespace
1495
1496namespace {
1497// Plan v0.3 P6: groups built on the device when every expert is resident at `base + id * blob` (the MTP layer):
1498// one block of 128 threads, groups in first-appearance order, entries of a group in routing order.
1499__dpct_inline__ void group_resident_kernel(
1500    const int32_t *__restrict__ ids, int n, int k_per_tok, const uint8_t *base,
1501    long long blob, unsigned long long *__restrict__ grp_ptr,
1502    int32_t *__restrict__ grp_start, int32_t *__restrict__ counts,
1503    int32_t *__restrict__ ent_dst, int32_t *__restrict__ ent_tok) {
1504    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1505auto &e_s = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
1506    sycl::ext::oneapi::this_work_item::get_work_group<3>());
1507    auto &first_s =
1508        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
1509            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1510    auto &size_s =
1511        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
1512            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1513    auto &gidx_s =
1514        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[128]>(
1515            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1516    auto &gstart_s =
1517        *sycl::ext::oneapi::group_local_memory_for_overwrite<int[129]>(
1518            sycl::ext::oneapi::this_work_item::get_work_group<3>());
1519    const int i = item_ct1.get_local_id(2);
1520    const int e = i < n ? ids[i] : -1;
1521    e_s[i] = e;
1522    item_ct1.barrier(sycl::access::fence_space::local_space);
1523    int first = i, rank = 0, size = 0;
1524    if (i < n) {
1525#pragma unroll
1526        for (int j = 0; j < i; ++j)
1527            if (e_s[j] == e) { if (first == i) first = j; ++rank; }
1528        if (first == i)
1529#pragma unroll
1530            for (int j = i; j < n; ++j) size += e_s[j] == e;
1531    }
1532    first_s[i] = first;
1533    size_s[i] = (i < n && first == i) ? size : 0;
1534    item_ct1.barrier(sycl::access::fence_space::local_space);
1535    if (i == 0) {
1536        int gi = 0, acc = 0;
1537#pragma unroll
1538        for (int j = 0; j < n; ++j)
1539            if (first_s[j] == j) {
1540                gidx_s[j] = gi;
1541                gstart_s[gi] = acc;
1542                grp_ptr[gi] = (unsigned long long) (base + (size_t) e_s[j] * (size_t) blob);
1543                grp_start[gi] = acc;
1544                acc += size_s[j];
1545                ++gi;
1546            }
1547        grp_start[gi] = acc;
1548        counts[0] = gi;
1549        counts[1] = acc;
1550    }
1551    item_ct1.barrier(sycl::access::fence_space::local_space);
1552    if (i < n) {
1553        const int at = gstart_s[gidx_s[first]] + rank;
1554        ent_dst[at] = i;
1555        ent_tok[at] = i / k_per_tok;
1556    }
1557}
1558}  // namespace
1559
1560void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob,
1561                        unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst,
1562                        int32_t* ent_tok, void* stream) {
1563    if (n < 1 || n > 128) { std::fprintf(stderr, "moe_group_resident: n must be 1..128\n"); std::exit(1); }
1564    {
1565        auto exp_props = sycl::ext::oneapi::experimental::properties{
1566            sycl::ext::oneapi::experimental::use_root_sync};
1567
1568        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1569            ->template parallel_for<
1570                dpct_kernel_name<class group_resident_kernel_5c38b8>>(
1571                sycl::nd_range<3>(sycl::range(1, 1, 128),
1572                                  sycl::range(1, 1, 128)),
1573                exp_props, [=](sycl::nd_item<3> item_ct1) {
1574                    group_resident_kernel(ids, n, k_per_tok, base,
1575                                          (long long)blob, grp_ptr, grp_start,
1576                                          counts, ent_dst, ent_tok);
1577                });
1578    }
1579    check("moe_group_resident", stream);
1580}
1581
1582void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
1583                    const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
1584                    const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream) {
1585    if (cap_groups <= 0 || cap_entries <= 0) return;
1586    dpct::queue_ptr cs = strata::q_of(stream);
1587    const uint64_t gu_bytes = ((uint64_t) cap_entries * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
1588    const uint64_t q8_bytes = ((uint64_t) cap_entries * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
1589    float* gate_up = (float*) scratch;
1590    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
1591    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
1592    const bool fast = new_grouped(x_q8_0, scratch);
1593    {
1594        const dpct::dim3 grid((unsigned)(2 * FF / GU_ROWS),
1595                              (unsigned)cap_groups);
1596        if (fast)
1597        {
1598            auto exp_props = sycl::ext::oneapi::experimental::properties{
1599                sycl::ext::oneapi::experimental::use_root_sync};
1600
1601            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
1602                dpct_kernel_name<class gu_grouped_t_kernel_998f94>>(
1603                sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
1604                                  sycl::range(1, 1, 256)),
1605                exp_props,
1606                [=](sycl::nd_item<3> item_ct1)
1607                    [[sycl::reqd_sub_group_size(32)]] {
1608                        gu_grouped_t_kernel(grp_ptr, grp_start, n_groups,
1609                                            ent_tok, x_q8_0, x_scales, gate_up,
1610                                            (int)cap_entries);
1611                    });
1612        } else {
1613            auto exp_props = sycl::ext::oneapi::experimental::properties{
1614                sycl::ext::oneapi::experimental::use_root_sync};
1615
1616            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class gu_grouped_kernel_c9eb4d>>(
1617                sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
1618                                  sycl::range(1, 1, 256)),
1619                exp_props,
1620                [=](sycl::nd_item<3> item_ct1)
1621                    [[sycl::reqd_sub_group_size(32)]] {
1622                        gu_grouped_kernel(grp_ptr, grp_start, n_groups, ent_tok,
1623                                          x_q8_0, x_scales, gate_up,
1624                                          (int)cap_entries);
1625                    });
1626        }
1627        check("moe_grouped_s2/gu", stream);
1628    }
1629    // #783 PR-k (stuchapin909): SwiGLU and the scaled Q8_0 quantize of its result in one kernel (gate_up still gets the
1630    // activation written back, so the parity checks read the same buffer); STRATA_S2_SWIGLU_Q8=0 keeps the two launches
1631    static const bool swiglu_q8 = [] {
1632        const char* e = std::getenv("STRATA_S2_SWIGLU_Q8");
1633        return e == nullptr || e[0] != '0';
1634    }();
1635    static_assert(FF % 32 == 0, "the fused SwiGLU + Q8_0 kernel works in whole 32-value blocks");
1636    if (fast && x_scales != nullptr && swiglu_q8) {
1637        const long long pairs = cap_entries * (long long) FF;
1638        const long long n_blocks = pairs >> 5;
1639        const int warps = THREADS / 32;
1640        {
1641            auto exp_props = sycl::ext::oneapi::experimental::properties{
1642                sycl::ext::oneapi::experimental::use_root_sync};
1643
1644            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
1645                class swiglu_quantize_q8_0_scaled_kernel_1271ea>>(
1646                sycl::nd_range<3>(
1647                    sycl::range(1, 1,
1648                                (unsigned)((n_blocks + warps - 1) / warps)) *
1649                        sycl::range(1, 1, THREADS),
1650                    sycl::range(1, 1, THREADS)),
1651                exp_props,
1652                [=](sycl::nd_item<3> item_ct1)
1653                    [[sycl::reqd_sub_group_size(32)]] {
1654                        swiglu_quantize_q8_0_scaled_kernel(gate_up, pairs,
1655                                                           h_q8_0, h_scales);
1656                    });
1657        }
1658        check("moe_grouped_s2/swiglu_q8", stream);
1659    } else {
1660        const long long pairs = cap_entries * (long long) FF;
1661        {
1662            auto exp_props = sycl::ext::oneapi::experimental::properties{
1663                sycl::ext::oneapi::experimental::use_root_sync};
1664
1665            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class swiglu_kernel_90849f>>(
1666                sycl::nd_range<3>(
1667                    sycl::range(1, 1,
1668                                (unsigned)((pairs + THREADS - 1) / THREADS)) *
1669                        sycl::range(1, 1, THREADS),
1670                    sycl::range(1, 1, THREADS)),
1671                exp_props, [=](sycl::nd_item<3> item_ct1) {
1672                    swiglu_kernel(gate_up, pairs);
1673                });
1674        }
1675        check("moe_grouped_s2/swiglu", stream);
1676        if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);
1677        else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);
1678    }
1679    {
1680        const dpct::dim3 grid((unsigned)(H / D_ROWS), (unsigned)cap_groups);
1681        const float* hs = x_scales != nullptr ? h_scales : nullptr;
1682        if (fast)
1683        {
1684            auto exp_props = sycl::ext::oneapi::experimental::properties{
1685                sycl::ext::oneapi::experimental::use_root_sync};
1686
1687            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
1688                dpct_kernel_name<class down_grouped_t_kernel_12b16d>>(
1689                sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
1690                                  sycl::range(1, 1, 256)),
1691                exp_props,
1692                [=](sycl::nd_item<3> item_ct1)
1693                    [[sycl::reqd_sub_group_size(32)]] {
1694                        down_grouped_t_kernel(grp_ptr, grp_start, n_groups,
1695                                              ent_dst, h_q8_0, hs, out);
1696                    });
1697        } else {
1698            auto exp_props = sycl::ext::oneapi::experimental::properties{
1699                sycl::ext::oneapi::experimental::use_root_sync};
1700
1701            strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
1702                dpct_kernel_name<class down_grouped_kernel_ea4417>>(
1703                sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
1704                                  sycl::range(1, 1, 256)),
1705                exp_props,
1706                [=](sycl::nd_item<3> item_ct1)
1707                    [[sycl::reqd_sub_group_size(32)]] {
1708                        down_grouped_kernel(grp_ptr, grp_start, n_groups,
1709                                            ent_dst, h_q8_0, hs, out);
1710                    });
1711        }
1712        check("moe_grouped_s2/down", stream);
1713    }
1714}
1715
1716void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap,
1717                 int64_t n_embd, void* stream) {
1718    if (cap <= 0) return;
1719    const dpct::dim3 grid(
1720        (unsigned)((n_embd + 255) / 256 < 8 ? (n_embd + 255) / 256 : 8),
1721        (unsigned)cap);
1722    {
1723        auto exp_props = sycl::ext::oneapi::experimental::properties{
1724            sycl::ext::oneapi::experimental::use_root_sync};
1725
1726        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1727            ->template parallel_for<dpct_kernel_name<class add_hits_kernel_50cbcb>>(
1728                sycl::nd_range<3>(grid * sycl::range(1, 1, 256),
1729                                  sycl::range(1, 1, 256)),
1730                exp_props, [=](sycl::nd_item<3> item_ct1) {
1731                    add_hits_kernel(parts, hit_out, dst, count, (int)n_embd);
1732                });
1733    }
1734    check("moe_hit_add", stream);
1735}
1736
1737void moe_hit_grouped_s2_cpu_order(const uint8_t *blob_base,
1738                                  const int32_t *slot_index,
1739                                  const int32_t *dst_index, int64_t n_hits,
1740                                  int64_t blob_bytes, const uint8_t *x_q8_0,
1741                                  void *scratch, float *out, void *stream,
1742                                  const float *x_scales,
1743                                  float *gate_up_trace) try {
1744    if (n_hits <= 0) return;
1745    if (x_scales == nullptr) {
1746        std::fprintf(stderr, "moe_hit_grouped_s2_cpu_order requires fp32 activation scales\n");
1747        std::exit(1);
1748    }
1749    dpct::queue_ptr cs = strata::q_of(stream);
1750    const uint64_t gu_bytes = ((uint64_t) n_hits * 2 * FF * 4 + 15) & ~15ull;
1751    const uint64_t q8_bytes = ((uint64_t) n_hits * (FF / 32) * 34 + 15) & ~15ull;
1752    const uint64_t scale_bytes = ((uint64_t) n_hits * (FF / 32) * 4 + 15) & ~15ull;
1753    float* gu = (float*) scratch;
1754    uint8_t* hq = (uint8_t*) scratch + gu_bytes;
1755    float* hs = (float*) (hq + q8_bytes);
1756    float* hh = (float*) ((uint8_t*) hs + scale_bytes);
1757    float* xh = (float*) ((uint8_t*) hh + scale_bytes);
1758    {
1759        auto exp_props = sycl::ext::oneapi::experimental::properties{
1760            sycl::ext::oneapi::experimental::use_root_sync};
1761
1762        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1763            auto H_ct3 = H / 32;
1764
1765            cgh.parallel_for<
1766                dpct_kernel_name<class activation_correction_kernel_ca15a9>>(
1767                sycl::nd_range<3>(
1768                    sycl::range(1, 1, (H / 32 + THREADS - 1) / THREADS) *
1769                        sycl::range(1, 1, THREADS),
1770                    sycl::range(1, 1, THREADS)),
1771                exp_props, [=](sycl::nd_item<3> item_ct1) {
1772                    activation_correction_kernel(x_q8_0, x_scales, xh, H_ct3);
1773                });
1774        });
1775    }
1776    check("cpu_order/input_correction", stream);
1777    const int rows_per_block = THREADS / 8;
1778    {
1779        auto exp_props = sycl::ext::oneapi::experimental::properties{
1780            sycl::ext::oneapi::experimental::use_root_sync};
1781
1782        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
1783            dpct_kernel_name<class cpu_order_projection_kernel_2fbdd9,
1784                             dpct_kernel_scalar<false>>>(
1785            sycl::nd_range<3>(
1786                sycl::range(1, 1,
1787                            (unsigned)((n_hits * 2 * FF + rows_per_block - 1) /
1788                                       rows_per_block)) *
1789                    sycl::range(1, 1, THREADS),
1790                sycl::range(1, 1, THREADS)),
1791            exp_props,
1792            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1793                cpu_order_projection_kernel<false>(
1794                    blob_base, slot_index, dst_index, blob_bytes, x_q8_0,
1795                    x_scales, xh, gu, (int)n_hits);
1796            });
1797    }
1798    check("cpu_order/gate_up", stream);
1799    if (gate_up_trace != nullptr &&
1800        /*
1801        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
1802        While the origin API might be synchronous, it depends on the type of
1803        operand memory, so you may need to call wait() on event return by memcpy
1804        API to ensure synchronization behavior.
1805        */
1806        DPCT_CHECK_ERROR(cs->memcpy(
1807            gate_up_trace, gu, (size_t)n_hits * 2 * FF * sizeof(float))) != 0) {
1808        std::fprintf(stderr, "cpu_order/gate_up_trace copy failed\n");
1809        std::exit(1);
1810    }
1811    {
1812        auto exp_props = sycl::ext::oneapi::experimental::properties{
1813            sycl::ext::oneapi::experimental::use_root_sync};
1814
1815        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1816            auto int_n_hits_FF_ct1 = (int)n_hits * FF;
1817
1818            cgh.parallel_for<
1819                dpct_kernel_name<class cpu_order_swiglu_kernel_4d84ce>>(
1820                sycl::nd_range<3>(
1821                    sycl::range(
1822                        1, 1,
1823                        (unsigned)((n_hits * FF + THREADS - 1) / THREADS)) *
1824                        sycl::range(1, 1, THREADS),
1825                    sycl::range(1, 1, THREADS)),
1826                exp_props, [=](sycl::nd_item<3> item_ct1) {
1827                    cpu_order_swiglu_kernel(gu, int_n_hits_FF_ct1);
1828                });
1829        });
1830    }
1831    check("cpu_order/swiglu", stream);
1832    {
1833        auto exp_props = sycl::ext::oneapi::experimental::properties{
1834            sycl::ext::oneapi::experimental::use_root_sync};
1835
1836        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1837            auto int_n_hits_FF_ct4 = (int)n_hits * (FF / 32);
1838
1839            cgh.parallel_for<
1840                dpct_kernel_name<class cpu_order_quantize_kernel_7d1393>>(
1841                sycl::nd_range<3>(
1842                    sycl::range(1, 1,
1843                                (unsigned)((n_hits * (FF / 32) + THREADS - 1) /
1844                                           THREADS)) *
1845                        sycl::range(1, 1, THREADS),
1846                    sycl::range(1, 1, THREADS)),
1847                exp_props, [=](sycl::nd_item<3> item_ct1) {
1848                    cpu_order_quantize_kernel(gu, hq, hs, hh,
1849                                              int_n_hits_FF_ct4);
1850                });
1851        });
1852    }
1853    check("cpu_order/intermediate_quantize", stream);
1854    {
1855        auto exp_props = sycl::ext::oneapi::experimental::properties{
1856            sycl::ext::oneapi::experimental::use_root_sync};
1857
1858        strata::kprof::kp(cs, __FILE__, __func__, __LINE__)->template parallel_for<
1859            dpct_kernel_name<class cpu_order_projection_kernel_2e007a,
1860                             dpct_kernel_scalar<true>>>(
1861            sycl::nd_range<3>(
1862                sycl::range(1, 1,
1863                            (unsigned)((n_hits * H + rows_per_block - 1) /
1864                                       rows_per_block)) *
1865                    sycl::range(1, 1, THREADS),
1866                sycl::range(1, 1, THREADS)),
1867            exp_props,
1868            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
1869                cpu_order_projection_kernel<true>(blob_base, slot_index,
1870                                                  dst_index, blob_bytes, hq, hs,
1871                                                  hh, out, (int)n_hits);
1872            });
1873    }
1874    check("cpu_order/down", stream);
1875}
1876catch (sycl::exception const &exc) {
1877  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1878            << ", line:" << __LINE__ << std::endl;
1879  std::exit(1);
1880}
1881
1882}  // namespace strata::kernels