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
54.0 KiB1165 linesraw
1// src/prefill/moe_fused.cu - see include/strata/prefill/moe_fused.hpp (#136: the Q2_0 pack's prompt experts on
2// Strata's own int8 tensor-core kernels, with the grouping on the GPU).
3//
4// The arithmetic.  A Q2_0 block is 64 weights w = d_w * (q - 1), q in 0..3, four codes per byte, weight j of a block
5// in byte j / 4 at bits 2 * (j % 4).  An activation block of 32 values is x = d_x * a with a = round(x / d_x) in
6// -127..127.  Over one 32-value half-block
7//     sum w x = d_w * d_x * (sum q a - sum a),
8// so the int8 product takes the codes as they are (0..3 is a valid s8) and the offset is the activations' own sum,
9// stored with the block.  The dot product (|sum q a| <= 32 * 3 * 127 < 2^22) becomes a float exactly with one
10// integer add: as_float(0x4B400000 + dot) = 1.5 * 2^23 + dot, and the block stores c = -(1.5 * 2^23 + sum a), so
11// as_float(0x4B400000 + dot) + c = dot - sum a with no rounding.  Per output and 64-block that is
12//     acc += d_w * (d_x0 * t0 + d_x1 * t1)        (t = dot - sum a of each half)
13// - two integer adds, two float adds and three multiply-adds.
14//
15// The K order.  mma.sync m16n8k32 takes four consecutive k of a row (A) or column (B) per register.  Four consecutive
16// weights are one code byte; four codes of one register instead come from the same 2-bit field of four consecutive
17// bytes - (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, t+12 of a 16-weight word.  So the kernels use that order
18// for the k of a half-block: mma k index 16h + 4t + j stands for weight (and activation) 16h + t + 4j.  The
19// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load.
20#define DPCT_PROFILING_ENABLED
21#include <sycl/sycl.hpp>
22#include "strata/kprof.hpp"
23#include <dpct/dpct.hpp>
24#include "strata/sycl_queue.hpp"
25#include "strata/prefill/moe_fused.hpp"
26#include "strata/core/geometry.hpp"
27
28#include <algorithm>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <mutex>
33#include <cmath>
34
35namespace strata::prefill::fused {
36namespace {
37
38void ck(dpct::err0 e, const char *what) {
39}
40
41constexpr int AB = 80;                  // activation bytes per 64 values: 64 codes, then {d0, c0, d1, c1}
42constexpr int MAGIC = 0x4B400000;       // the bits of 1.5 * 2^23
43constexpr float MAGICF = 12582912.0f;
44// The Strata Q2_0 blob (moe_mmq.cu strata_q2_kernel, kernels.cu blob_dequant_kernel): gate/up codes [1280][640 B]
45// (rows interleaved: gate of feature f at row 2f, its up at 2f + 1), down codes [2560][160 B], gate/up scales
46// [1280][40] fp16, down scales [2560][10] fp16.
47constexpr size_t O_GU_CODES = 0, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160,
48                 O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2;
49constexpr int THREADS = 512;            // 16 warps: 4 along the weight rows (64 each) x 4 along the tile rows (16 each)
50constexpr int WROWS = 256;              // weight rows per work item: 128 features of gate/up, or 256 outputs of down
51constexpr int STAGES = 4;               // cp.async pipeline depth, one 64-weight block of K per stage
52constexpr int STAGE_BYTES = WROWS * 16 + kTileRows * AB;
53constexpr size_t smem_bytes(bool gu) {
54    return (size_t) WROWS * (gu ? 40 : 10) * 2 + STAGES * STAGE_BYTES + kTileRows * 4;
55}
56
57// the stored position of value k of a 32-value half-block (see "The K order")
58__dpct_inline__ int perm32(int k) {
59    return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2);
60}
61// where value k of a 32-value half-block is stored: perm32 for the CUDA kernel; on HIP the gfx11 WMMA kernel's order
62// (value 4b + t of a 16-value word at 4t + b: see expert_w11_kernel)
63__dpct_inline__ int act_pos(int k) {
64#if defined(__HIPCC__)
65    return (k & 16) | ((k & 3) << 2) | ((k >> 2) & 3);
66#else
67    return perm32(k);
68#endif
69}
70
71struct Tables {
72    int32_t *cnt, *off, *fill, *ts;      // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1)
73    sycl::int2 *tiles;                   // {expert, first row}, in expert order
74};
75size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }
76Tables tables(void* scratch, int n_expert) {
77    int32_t* p = (int32_t*) scratch;
78    return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,
79            (sycl::int2 *)((uint8_t *)scratch + tiles_at(n_expert))};
80}
81
82// ---- activations: one warp per 64 values
83__dpct_inline__ void quant_act_kernel(const float *__restrict__ x, int64_t nblk,
84                                      uint8_t *__restrict__ xa) {
85    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
86    const int64_t w =
87        (int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) / 32) +
88        item_ct1.get_local_id(2) / 32;
89    const int lane = item_ct1.get_local_id(2) & 31;
90    if (w >= nblk) return;
91    const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];
92    float a0 = sycl::fabs(v0), a1 = sycl::fabs(v1);
93#pragma unroll
94    for (int o = 16; o > 0; o >>= 1) {
95        /*
96        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
97        feature masked sub_group function which may not be supported by all
98        compilers or runtimes. You may need to adjust the code.
99        */
100        a0 = sycl::fmax(
101            a0, dpct::experimental::permute_sub_group_by_xor(
102                    0xffffffffu,
103                    sycl::ext::oneapi::this_work_item::get_sub_group(), a0, o));
104        /*
105        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
106        feature masked sub_group function which may not be supported by all
107        compilers or runtimes. You may need to adjust the code.
108        */
109        a1 = sycl::fmax(
110            a1, dpct::experimental::permute_sub_group_by_xor(
111                    0xffffffffu,
112                    sycl::ext::oneapi::this_work_item::get_sub_group(), a1, o));
113    }
114    const int q0 = a0 > 0.0f ? sycl::vec<float, 1>{(v0 * (127.0f / a0))}
115                                   .convert<int, sycl::rounding_mode::rte>()[0]
116                             : 0;
117    const int q1 = a1 > 0.0f ? sycl::vec<float, 1>{(v1 * (127.0f / a1))}
118                                   .convert<int, sycl::rounding_mode::rte>()[0]
119                             : 0;
120    int s0 = q0, s1 = q1;
121#pragma unroll
122    for (int o = 16; o > 0; o >>= 1) {
123        /*
124        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
125        feature masked sub_group function which may not be supported by all
126        compilers or runtimes. You may need to adjust the code.
127        */
128        s0 += dpct::experimental::permute_sub_group_by_xor(
129            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s0,
130            o);
131        /*
132        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
133        feature masked sub_group function which may not be supported by all
134        compilers or runtimes. You may need to adjust the code.
135        */
136        s1 += dpct::experimental::permute_sub_group_by_xor(
137            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s1,
138            o);
139    }
140    uint8_t* out = xa + w * AB;
141    out[act_pos(lane)] = (uint8_t) (int8_t) q0;
142    out[32 + act_pos(lane)] = (uint8_t) (int8_t) q1;
143    if (lane == 0)
144        *(sycl::float4 *)(out + 64) =
145            sycl::float4(a0 / 127.0f, -(MAGICF + (float)s0), a1 / 127.0f,
146                         -(MAGICF + (float)s1));
147}
148
149// ---- grouping: counts, offsets and tiles, placement
150__dpct_inline__ void count_kernel(const int32_t *__restrict__ ids, int64_t n,
151                                  int E, int32_t *__restrict__ cnt,
152                                  uint8_t *dpct_local) {
153    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
154    auto hist = (int32_t *)dpct_local;
155#pragma unroll
156    for (int e = item_ct1.get_local_id(2); e < E;
157         e += item_ct1.get_local_range(2)) hist[e] = 0;
158    /*
159    DPCT1065: Consider replacing sycl::nd_item::barrier() with
160    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
161    performance if there is no access to global memory.
162    */
163    item_ct1.barrier();
164    for (int64_t i =
165             (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
166             item_ct1.get_local_id(2);
167         i < n; i += (int64_t)item_ct1.get_group_range(2) *
168                     item_ct1.get_local_range(2)) {
169        const int e = ids[i];
170        if ((unsigned)e < (unsigned)E)
171            dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(
172                &hist[e], 1);
173    }
174    /*
175    DPCT1065: Consider replacing sycl::nd_item::barrier() with
176    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
177    performance if there is no access to global memory.
178    */
179    item_ct1.barrier();
180#pragma unroll
181    for (int e = item_ct1.get_local_id(2); e < E;
182         e += item_ct1.get_local_range(2))
183        if (hist[e])
184            dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(
185                &cnt[e], hist[e]);
186}
187
188// exclusive prefix sum over the block (blockDim a multiple of 32); *total = the block's sum
189inline int block_excl_sum(int v, int *total, int *sh) {
190    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
191    const int lane = item_ct1.get_local_id(2) & 31,
192              w = item_ct1.get_local_id(2) >> 5,
193              nw = item_ct1.get_local_range(2) >> 5;
194    int x = v;
195#pragma unroll
196    for (int o = 1; o < 32; o <<= 1) {
197        /*
198        DPCT1108: '__shfl_up_sync' was migrated with the experimental
199        feature masked sub_group function which may not be supported by all
200        compilers or runtimes. You may need to adjust the code.
201        */
202        const int y = dpct::experimental::shift_sub_group_right(
203            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
204            o);
205        if (lane >= o) x += y;
206    }
207    if (lane == 31) sh[w] = x;
208    /*
209    DPCT1065: Consider replacing sycl::nd_item::barrier() with
210    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
211    performance if there is no access to global memory.
212    */
213    item_ct1.barrier();
214    if (w == 0) {
215        int s = lane < nw ? sh[lane] : 0;
216#pragma unroll
217        for (int o = 1; o < 32; o <<= 1) {
218            /*
219            DPCT1108: '__shfl_up_sync' was migrated with the experimental
220            feature masked sub_group function which may not be supported by all
221            compilers or runtimes. You may need to adjust the code.
222            */
223            const int y = dpct::experimental::shift_sub_group_right(
224                0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(),
225                s, o);
226            if (lane >= o) s += y;
227        }
228        sh[lane] = s;
229    }
230    /*
231    DPCT1065: Consider replacing sycl::nd_item::barrier() with
232    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
233    performance if there is no access to global memory.
234    */
235    item_ct1.barrier();
236    const int r = x - v + (w > 0 ? sh[w - 1] : 0);
237    *total = sh[nw - 1];
238    /*
239    DPCT1065: Consider replacing sycl::nd_item::barrier() with
240    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
241    performance if there is no access to global memory.
242    */
243    item_ct1.barrier(); // sh is reused by the next call
244    return r;
245}
246
247// one block, a thread per expert (E <= 1024)
248__dpct_inline__ void scan_kernel(Tables tb, int E) {
249    auto &sh = *sycl::ext::oneapi::group_local_memory_for_overwrite<int[32]>(
250        sycl::ext::oneapi::this_work_item::get_work_group<3>());
251    const int e =
252        sycl::ext::oneapi::this_work_item::get_nd_item<3>().get_local_id(2);
253    const int c = e < E ? tb.cnt[e] : 0, nt = (c + kTileRows - 1) / kTileRows;
254    int rows = 0, tiles = 0;
255    const int o = block_excl_sum(c, &rows, sh), to = block_excl_sum(nt, &tiles, sh);
256    if (e < E) {
257        tb.off[e] = o;
258        tb.fill[e] = o;
259        tb.ts[e] = to;
260#pragma unroll
261        for (int i = 0; i < nt; ++i)
262            tb.tiles[to + i] = sycl::int2(e, o + i * kTileRows);
263    }
264    if (e == 0) {
265        tb.off[E] = rows;
266        tb.ts[E] = tiles;
267    }
268}
269
270__dpct_inline__ void place_kernel(const int32_t *__restrict__ ids, int64_t n,
271                                  int k, int E, Tables tb,
272                                  int32_t *__restrict__ slot,
273                                  int32_t *__restrict__ src) {
274    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
275    const int64_t i =
276        (int64_t)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
277        item_ct1.get_local_id(2);
278    if (i >= n) return;
279    const int e = ids[i];
280    if ((unsigned) e >= (unsigned) E) { slot[i] = 0; return; }   // (the router never writes one)
281    const int p =
282        dpct::atomic_fetch_add<sycl::access::address_space::generic_space>(
283            &tb.fill[e], 1);
284    slot[i] = p;
285    src[p] = (int32_t) (i / k);
286}
287
288// ---- the expert products
289#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800
290__dpct_inline__ void cp16(void *dst, const void *src) {
291#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
292    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(
293                     (unsigned)__cvta_generic_to_shared(dst)),
294                 "l"(src));
295#else
296    *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst))) =
297        *(((uint32_t *)(uintptr_t)src));
298    if (16 > 4)
299        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
300          1) = *(((uint32_t *)(uintptr_t)src) + 1);
301    if (16 > 8)
302        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
303          2) = *(((uint32_t *)(uintptr_t)src) + 2);
304    if (16 > 12)
305        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
306          3) = *(((uint32_t *)(uintptr_t)src) + 3);
307#endif
308}
309__dpct_inline__ void cp4(void *dst, const void *src) {
310    /*
311    DPCT1053: Migration of device assembly code is not supported.
312    */
313    asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(
314                     (unsigned)__cvta_generic_to_shared(dst)),
315                 "l"(src));
316}
317/*
318DPCT1026: The call to "cp.async.commit_group;
319" was removed because current "cp.async" is migrated to synchronous copy
320operation. You may need to adjust the code to tune the performance.
321*/
322#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
323__device__ __forceinline__ void cp_commit() {
324    asm volatile("cp.async.commit_group;\n" ::);
325#else
326__device__ __forceinline__ void cp_commit() {
327#endif }
328/*
329DPCT1026: The call to "cp.async.wait_group %0;
330" was removed because current "cp.async" is migrated to synchronous copy
331operation. You may need to adjust the code to tune the performance.
332*/
333#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
334    template <int N> __device__ __forceinline__ void cp_wait() {
335        asm volatile("cp.async.wait_group %0;\n" ::"n"(N));
336#else
337    template <int N> __device__ __forceinline__ void cp_wait() {
338#endif }
339// d = A (16 x 32 s8, row) * B (32 x 8 s8, col), int32, from zero
340__dpct_inline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0,
341                            uint32_t b1) {
342#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
343            asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 "
344                "{%0,%1,%2,%3}, "
345                "{%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"
346                : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
347                : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1),
348                  "r"(0));
349#else
350            {
351                volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};
352                sycl::vec<uint32_t, 4> a_mat_frag_ct1(a[0], a[1], a[2], a[3]);
353                sycl::vec<uint32_t, 2> b_mat_frag_ct1(b0, b1);
354                sycl::vec<int32_t, 4> c_mat_frag_ct1(0, 0, 0, 0);
355                dpct::experimental::matrix::mma<16, 8, 32, int8_t, int32_t>(
356                    reinterpret_cast<volatile void **>(d_mat_frag_ct1),
357                    &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);
358            }
359#endif
360}
361#endif
362
363// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks
364// the batch's items (their count is on the device).  GU: gate/up rows of 128 features against the rows' tokens'
365// activations (`act` per token, 2560 values), SwiGLU, H to int8 per 32 features into `out` (per row, 640 values).
366// !GU: down rows (256 outputs) against H (`act` per row), FP32 into `dm` per row.
367// Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, its gate rows as mma rows 0-7 and
368// its up rows as 8-15, so a lane holds gate and up of one feature: SwiGLU in registers), tile rows 16 wt.. as two n8.
369template <bool GU>
370/*
371DPCT1110: The total declared local variable size in device function
372expert_kernel exceeds 128 bytes and may cause high register pressure. Consult
373with your hardware vendor to find the total register size available and adjust
374the code, or use smaller sub-group size to avoid high register pressure.
375*/
376__dpct_inline__ void expert_kernel(
377    const Batch b, const Tables tb, const uint8_t *__restrict__ act,
378    const int32_t *__restrict__ src, uint8_t *__restrict__ out,
379    float *__restrict__ dm, uint8_t *dpct_local) {
380#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800
381    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
382    constexpr int NKB = GU ? 40 : 10; // 64-weight blocks along K
383    constexpr int NFB = GU ? 5 : 10;                  // weight-row blocks per tile
384    constexpr int CODE_LD = GU ? 640 : 160;           // code bytes per weight row
385    constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;
386    constexpr int ACT_LD = NKB * AB;                  // bytes per activation row: 3200 (a token), 800 (a row's H)
387    constexpr unsigned M2 = 0x03030303u;
388    auto smem = (uint8_t *)dpct_local;
389    const sycl::half *wsc =
390        (const sycl::half *)smem; // [256][NKB] the work item's weight scales
391    uint8_t* stages = smem + WROWS * NKB * 2;                     // [STAGES] x {codes [256][16], act [64][AB]}
392    int* srow = (int*) (stages + STAGES * STAGE_BYTES);           // [64] the activation row of each tile row
393
394    const int tid = item_ct1.get_local_id(2), lane = tid & 31, warp = tid >> 5,
395              g = lane >> 2, tig = lane & 3;
396    const int wf = warp & 3, nb0 = 16 * (warp >> 2);
397    int ra[4], rb[4];                                             // the local weight rows of mma rows g and g + 8
398#pragma unroll
399    for (int i = 0; i < 4; ++i) {
400        if (GU) { ra[i] = 2 * (32 * wf + 8 * i + g); rb[i] = ra[i] + 1; }
401        else { ra[i] = 64 * wf + 16 * i + g; rb[i] = ra[i] + 8; }
402    }
403    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
404    for (int w = item_ct1.get_group(2); w < nwork;
405         w += item_ct1.get_group_range(2)) {
406        const sycl::int2 tl = tb.tiles[t0 + w / NFB];
407        const int fb = w % NFB, e = tl.x(), row0 = tl.y(),
408                  nrows = sycl::min(kTileRows, tb.off[e + 1] - row0);
409        const uint8_t* blob = b.blob[e - b.e0];
410        const int rbase = fb * WROWS;
411        /*
412        DPCT1118: SYCL group functions and algorithms must be encountered in
413        converged control flow. You may need to adjust the code.
414        */
415        /*
416        DPCT1065: Consider replacing sycl::nd_item::barrier() with
417        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
418        better performance if there is no access to global memory.
419        */
420        item_ct1.barrier(); // the previous item is done with the buffers
421        if (tid < kTileRows) {
422            const int r =
423                row0 +
424                sycl::min(
425                    tid,
426                    nrows - 1); // rows past the tile's end repeat its last one
427            srow[tid] = GU ? src[r] : r;
428        }
429        for (int c = tid; c < WROWS * 5; c += THREADS) {          // the scales: 5 x 16 B (GU) or 5 x 4 B a row
430            const int r = c / 5, q = c % 5;
431            if (GU) cp16(smem + r * 80 + q * 16, blob + O_SC + (size_t) (rbase + r) * 80 + q * 16);
432            else cp4(smem + r * 20 + q * 4, blob + O_SC + (size_t) (rbase + r) * 20 + q * 4);
433        }
434        /*
435        DPCT1118: SYCL group functions and algorithms must be encountered in
436        converged control flow. You may need to adjust the code.
437        */
438        /*
439        DPCT1065: Consider replacing sycl::nd_item::barrier() with
440        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
441        better performance if there is no access to global memory.
442        */
443        item_ct1.barrier(); // srow
444        auto load = [&](int kb) {
445            uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
446            if (tid < WROWS) cp16(st + tid * 16, blob + O_CODES + (size_t) (rbase + tid) * CODE_LD + kb * 16);
447            const int a = tid - (THREADS - kTileRows * 5);        // the last 320 threads: 64 rows x 5 x 16 B
448            if (a >= 0) {
449                const int r = a / 5, q = a % 5;
450                cp16(st + WROWS * 16 + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + kb * AB + q * 16);
451            }
452        };
453#pragma unroll
454        for (int s = 0; s < STAGES - 1; ++s) {
455            if (s < NKB) load(s);
456            cp_commit();
457        }
458        // a warp whose rows are all past the tile's end only takes part in the loads
459        const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
460        float acc[4][2][4];
461#pragma unroll
462        for (int i = 0; i < 4; ++i)
463#pragma unroll
464            for (int n = 0; n < 2; ++n)
465#pragma unroll
466                for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
467        for (int kb = 0; kb < NKB; ++kb) {
468            cp_wait<STAGES - 2>();
469            /*
470            DPCT1118: SYCL group functions and algorithms must be
471            encountered in converged control flow. You may need to adjust the
472            code.
473            */
474            /*
475            DPCT1065: Consider replacing sycl::nd_item::barrier() with
476            sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
477            better performance if there is no access to global memory.
478            */
479            item_ct1.barrier();
480            if (kb + STAGES - 1 < NKB) load(kb + STAGES - 1);
481            cp_commit();
482            if (!on0) continue;
483            const uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
484            const uint8_t* sa = st + WROWS * 16;
485            sycl::uint2 bq[2][2]; // [n8 tile][half]: the B registers
486            sycl::float4 sc[2]
487                           [2]; // [n8 tile][column 2 tig + c]: {d0, c0, d1, c1}
488#pragma unroll
489            for (int n = 0; n < 2; ++n) {
490                if (n == 1 && !on1) break;
491                const uint8_t* r = sa + (nb0 + 8 * n + g) * AB + 8 * tig;
492                bq[n][0] = *(const sycl::uint2 *)r;
493                bq[n][1] = *(const sycl::uint2 *)(r + 32);
494                sc[n][0] =
495                    *(const sycl::float4 *)(sa + (nb0 + 8 * n + 2 * tig) * AB +
496                                            64);
497                sc[n][1] =
498                    *(const sycl::float4 *)(sa +
499                                            (nb0 + 8 * n + 2 * tig + 1) * AB +
500                                            64);
501            }
502#pragma unroll
503            for (int i = 0; i < 4; ++i) {
504                const sycl::uint4 ca = *(const sycl::uint4 *)(st + ra[i] * 16),
505                                  cb = *(const sycl::uint4 *)(st + rb[i] * 16);
506                const float
507                    da = sycl::vec<sycl::half, 1>(wsc[ra[i] * NKB + kb])
508                             .convert<float,
509                                      sycl::rounding_mode::automatic>()[0],
510                    db = sycl::vec<sycl::half, 1>(wsc[rb[i] * NKB + kb])
511                             .convert<float,
512                                      sycl::rounding_mode::automatic>()[0];
513                const int s = 2 * tig;
514                const uint32_t a0[4] = {(ca.x() >> s) & M2, (cb.x() >> s) & M2,
515                                        (ca.y() >> s) & M2, (cb.y() >> s) & M2};
516                const uint32_t a1[4] = {(ca.z() >> s) & M2, (cb.z() >> s) & M2,
517                                        (ca.w() >> s) & M2, (cb.w() >> s) & M2};
518#pragma unroll
519                for (int n = 0; n < 2; ++n) {
520                    if (n == 1 && !on1) break;
521                    int d0[4], d1[4];
522                    mma_s8(d0, a0, bq[n][0].x(), bq[n][0].y());
523                    mma_s8(d1, a1, bq[n][1].x(), bq[n][1].y());
524#pragma unroll
525                    for (int q = 0; q < 4; ++q) {
526                        const sycl::float4 z = sc[n][q & 1];
527                        const float u0 = sycl::bit_cast<float>(MAGIC + d0[q]) +
528                                         z.y(),
529                                    u1 = sycl::bit_cast<float>(MAGIC + d1[q]) +
530                                         z.w();
531                        acc[i][n][q] = sycl::fma(
532                            (float)(q < 2 ? da : db),
533                            sycl::fma((float)(z.z()), (float)u1, z.x() * u0),
534                            acc[i][n][q]);
535                    }
536                }
537            }
538        }
539        if (!on0) continue;
540        if (GU) {
541            // SwiGLU of feature 32 wf + 8 i + g (lane g of m tile i), tile rows nb0 + 8 n + 2 tig + c; H to int8 per
542            // row over the warp's 32 features (= one 32-value half-block of the down product's K)
543            const int blk = 4 * fb + wf;
544#pragma unroll
545            for (int n = 0; n < 2; ++n) {
546                if (n == 1 && !on1) break;
547#pragma unroll
548                for (int c = 0; c < 2; ++c) {
549                    float h[4], am = 0.0f;
550#pragma unroll
551                    for (int i = 0; i < 4; ++i) {
552                        const float gt = acc[i][n][c], up = acc[i][n][2 + c];
553                        h[i] = gt / (1.0f + sycl::native::exp(-gt)) * up;
554                        am = sycl::fmax(am, sycl::fabs(h[i]));
555                    }
556#pragma unroll
557                    /*
558                    DPCT1108: '__shfl_xor_sync' was migrated with the
559                    experimental feature masked sub_group function which may not
560                    be supported by all compilers or runtimes. You may need to
561                    adjust the code.
562                    */
563                    for (int o = 4; o < 32; o <<= 1) am = sycl::fmax(
564                        am,
565                        dpct::experimental::permute_sub_group_by_xor(
566                            0xffffffffu,
567                            sycl::ext::oneapi::this_work_item::get_sub_group(),
568                            am, o));
569                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
570                    int qv[4], sum = 0;
571#pragma unroll
572                    for (int i = 0; i < 4; ++i) {
573                        qv[i] =
574                            sycl::vec<float, 1>{(h[i] * inv)}
575                                .convert<int, sycl::rounding_mode::rte>()[0];
576                        sum += qv[i];
577                    }
578#pragma unroll
579                    /*
580                    DPCT1108: '__shfl_xor_sync' was migrated with the
581                    experimental feature masked sub_group function which may not
582                    be supported by all compilers or runtimes. You may need to
583                    adjust the code.
584                    */
585                    for (int o = 4; o < 32; o <<= 1) sum +=
586                        dpct::experimental::permute_sub_group_by_xor(
587                            0xffffffffu,
588                            sycl::ext::oneapi::this_work_item::get_sub_group(),
589                            sum, o);
590                    const int r = nb0 + 8 * n + 2 * tig + c;
591                    if (r < nrows) {
592                        uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;
593                        const int hh = blk & 1;
594#pragma unroll
595                        for (int i = 0; i < 4; ++i) o[32 * hh + perm32(8 * i + g)] = (uint8_t) (int8_t) qv[i];
596                        if (g == 0) * (sycl::float2 *)(o + 64 + 8 * hh) =
597                            sycl::float2(am / 127.0f, -(MAGICF + (float)sum));
598                    }
599                }
600            }
601        } else {
602#pragma unroll
603            for (int i = 0; i < 4; ++i)
604#pragma unroll
605                for (int n = 0; n < 2; ++n) {
606                    if (n == 1 && !on1) break;
607#pragma unroll
608                    for (int q = 0; q < 4; ++q) {
609                        const int r = nb0 + 8 * n + 2 * tig + (q & 1);
610                        if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + (q < 2 ? ra[i] : rb[i])] = acc[i][n][q];
611                    }
612                }
613        }
614    }
615#endif
616}
617
618#if defined(__HIPCC__)
619// ---- Aurora (S23): the same products on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 (wave32).
620// Fragments (gfx11): A lane l holds the 16 k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of
621// column l % 16, C/D lane l holds D[2i + l / 16][l % 16], i = 0..7.  A = 16 weight rows, B = 16 tile rows (tokens):
622// a lane's eight results are eight weight rows of ONE tile row, whose activation scales it already holds.
623// The K order of a 16-weight word (one k-step): A register t = (word >> 2t) & 0x03030303 holds weights t, t+4, t+8,
624// t+12, so k index p = 4t + b stands for weight 4b + t; the activations are stored in that order (act_pos).  The
625// integer dot of each 32-value half (two k-steps) is exact and the epilogue is the CUDA kernel's, so the numbers are
626// those of expert_kernel (another K order inside exact integer sums).
627// No LDS staging: a wave reads its weight rows (16 B per row and 64-weight block) and its tile rows' activation
628// blocks (80 B) straight from global memory (L2: an expert's rows are read by every tile, a token's by every weight
629// block), one block ahead in registers; the work item's weight scales go to LDS once.
630#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)
631#define STRATA_FUSED_W11 1
632#else
633#define STRATA_FUSED_W11 0
634#endif
635typedef int w11_i4 __attribute__((ext_vector_type(4)));
636typedef int w11_i8 __attribute__((ext_vector_type(8)));
637constexpr int W_ROWS = 128;                       // weight rows per work item (GU: 64 features = one H block)
638constexpr int W_THREADS = 256;                    // 8 waves: 4 along the weight rows (32 each) x 2 along the tile (32)
639
640__device__ __forceinline__ w11_i8 wmma_iu8(w11_i4 a, w11_i4 b, w11_i8 c) {
641#if STRATA_FUSED_W11
642    return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(false, a, true, b, c, false);
643#else
644    __builtin_trap();
645    return c;
646#endif
647}
648
649template <bool GU>
650__global__ void __launch_bounds__(W_THREADS)
651expert_w11_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,
652                  uint8_t* __restrict__ out, float* __restrict__ dm) {
653#if STRATA_FUSED_W11
654    constexpr int NKB = GU ? 40 : 10;                 // 64-weight blocks along K
655    constexpr int NFB = (GU ? 1280 : 2560) / W_ROWS;  // work items per tile
656    constexpr int CODE_LD = GU ? 640 : 160;           // code bytes per weight row
657    constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;
658    constexpr int ACT_LD = NKB * AB;                  // bytes per activation row
659    constexpr unsigned M2 = 0x03030303u;
660    __shared__ __align__(16) uint16_t wsc[W_ROWS * NKB];        // the item's weight scales (fp16), [row][kb]
661    __shared__ int srow[kTileRows];
662    __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1];      // GU: H of the item's 64 features, [tile row][feature]
663    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
664    const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4;
665    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
666    for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
667        const int2 tl = tb.tiles[t0 + w / NFB];
668        const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);
669        const uint8_t* blob = b.blob[e - b.e0];
670        const int rbase = fb * W_ROWS;
671        __syncthreads();                                          // the previous item is done with srow / wsc / hs
672        if (tid < kTileRows) {
673            const int r = row0 + min(tid, nrows - 1);             // rows past the tile's end repeat its last one
674            srow[tid] = GU ? src[r] : r;
675        }
676        {
677            const uint4* s4 = reinterpret_cast<const uint4*>(blob + O_SC + (size_t) rbase * NKB * 2);
678            for (int i = tid; i < W_ROWS * NKB / 8; i += W_THREADS) reinterpret_cast<uint4*>(wsc)[i] = s4[i];
679        }
680        __syncthreads();
681        const bool on = 32 * wn < nrows;                          // a wave past the tile's rows only stages
682        float acc[2][2][8];
683#pragma unroll
684        for (int mt = 0; mt < 2; ++mt)
685#pragma unroll
686            for (int nt = 0; nt < 2; ++nt)
687#pragma unroll
688                for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f;
689        if (on) {
690            const uint8_t* arow[2];
691            const uint8_t* brow[2];
692#pragma unroll
693            for (int mt = 0; mt < 2; ++mt) arow[mt] = blob + O_CODES + (size_t) (rbase + 32 * wm + 16 * mt + l16) * CODE_LD;
694#pragma unroll
695            for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD;
696            uint4 ac[2], bq[2][4];
697            float4 bs[2];
698            auto fetch = [&](int kb, uint4 (&a)[2], uint4 (&q)[2][4], float4 (&s)[2]) {
699#pragma unroll
700                for (int mt = 0; mt < 2; ++mt) a[mt] = *reinterpret_cast<const uint4*>(arow[mt] + kb * 16);
701#pragma unroll
702                for (int nt = 0; nt < 2; ++nt) {
703                    const uint4* p = reinterpret_cast<const uint4*>(brow[nt] + kb * AB);
704                    q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3];
705                    s[nt] = *reinterpret_cast<const float4*>(brow[nt] + kb * AB + 64);
706                }
707            };
708            fetch(0, ac, bq, bs);
709            for (int kb = 0; kb < NKB; ++kb) {
710                uint4 nac[2], nbq[2][4];
711                float4 nbs[2];
712                if (kb + 1 < NKB) fetch(kb + 1, nac, nbq, nbs);
713                w11_i8 c[2][2][2];                                // [half][mt][nt]
714#pragma unroll
715                for (int h = 0; h < 2; ++h)
716#pragma unroll
717                    for (int mt = 0; mt < 2; ++mt)
718#pragma unroll
719                        for (int nt = 0; nt < 2; ++nt) c[h][mt][nt] = w11_i8{0, 0, 0, 0, 0, 0, 0, 0};
720#pragma unroll
721                for (int ks = 0; ks < 4; ++ks) {                  // k-step = 16-weight word ks of the block
722                    w11_i4 A[2];
723#pragma unroll
724                    for (int mt = 0; mt < 2; ++mt) {
725                        const unsigned wd = ks == 0 ? ac[mt].x : ks == 1 ? ac[mt].y : ks == 2 ? ac[mt].z : ac[mt].w;
726                        A[mt] = w11_i4{(int) (wd & M2), (int) ((wd >> 2) & M2), (int) ((wd >> 4) & M2),
727                                       (int) ((wd >> 6) & M2)};
728                    }
729#pragma unroll
730                    for (int nt = 0; nt < 2; ++nt) {
731                        const uint4 q = bq[nt][ks];
732                        const w11_i4 B = w11_i4{(int) q.x, (int) q.y, (int) q.z, (int) q.w};
733#pragma unroll
734                        for (int mt = 0; mt < 2; ++mt) c[ks >> 1][mt][nt] = wmma_iu8(A[mt], B, c[ks >> 1][mt][nt]);
735                    }
736                }
737                // the epilogue: per 64-weight block acc += d_w * (d_x0 * (dot0 - sum0) + d_x1 * (dot1 - sum1))
738#pragma unroll
739                for (int mt = 0; mt < 2; ++mt) {
740                    float dw[8];
741#pragma unroll
742                    for (int i = 0; i < 8; ++i) {
743                        const int m = 32 * wm + 16 * mt + 2 * i + hi;
744                        dw[i] = __half2float(__ushort_as_half(wsc[m * NKB + kb]));
745                    }
746#pragma unroll
747                    for (int nt = 0; nt < 2; ++nt) {
748                        const float4 z = bs[nt];
749#pragma unroll
750                        for (int i = 0; i < 8; ++i) {
751                            const float u0 = __int_as_float(MAGIC + c[0][mt][nt][i]) + z.y;
752                            const float u1 = __int_as_float(MAGIC + c[1][mt][nt][i]) + z.w;
753                            acc[mt][nt][i] = fmaf(dw[i], fmaf(z.z, u1, z.x * u0), acc[mt][nt][i]);
754                        }
755                    }
756                }
757                if (kb + 1 < NKB) {
758#pragma unroll
759                    for (int mt = 0; mt < 2; ++mt) ac[mt] = nac[mt];
760#pragma unroll
761                    for (int nt = 0; nt < 2; ++nt) {
762                        bs[nt] = nbs[nt];
763#pragma unroll
764                        for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j];
765                    }
766                }
767            }
768        }
769        if constexpr (GU) {
770            // SwiGLU: row 2f is feature f's gate (lanes 0..15), 2f + 1 its up (lanes 16..31) - the same (mt, i)
771            if (on) {
772#pragma unroll
773                for (int mt = 0; mt < 2; ++mt)
774#pragma unroll
775                    for (int nt = 0; nt < 2; ++nt)
776#pragma unroll
777                        for (int i = 0; i < 8; ++i) {
778                            const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16);
779                            const float gt = acc[mt][nt][i];
780                            if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up;
781                        }
782            }
783            __syncthreads();
784            // H block fb (features 64 fb .. 64 fb + 63) to int8: a thread per (tile row, half)
785            if (tid < 2 * kTileRows) {
786                const int r = tid >> 1, hh = tid & 1;
787                if (r < nrows) {
788                    float am = 0.0f;
789#pragma unroll 8
790                    for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j]));
791                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
792                    uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB;
793                    int sum = 0;
794                    uint32_t wd[8] = {};
795#pragma unroll
796                    for (int j = 0; j < 32; ++j) {
797                        const int qv = __float2int_rn(hs[r][32 * hh + j] * inv);
798                        sum += qv;
799                        const int p = act_pos(j);
800                        wd[p >> 2] |= (uint32_t) (uint8_t) (int8_t) qv << (8 * (p & 3));
801                    }
802                    uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh);
803                    o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]);
804                    o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]);
805                    *reinterpret_cast<float2*>(o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum));
806                }
807            }
808        } else if (on) {
809#pragma unroll
810            for (int mt = 0; mt < 2; ++mt)
811#pragma unroll
812                for (int nt = 0; nt < 2; ++nt) {
813                    const int r = 32 * wn + 16 * nt + l16;
814                    if (r < nrows) {
815                        float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi;
816#pragma unroll
817                        for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i];
818                    }
819                }
820        }
821    }
822#else
823    __builtin_trap();
824#endif
825}
826#endif  // __HIPCC__
827
828unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }
829
830struct DevInfo {
831    bool done = false;
832    int cc = 0, sms = 0, occ_gu = 0, occ_d = 0;
833};
834std::mutex g_mu;
835DevInfo g_dev[32];
836
837#if defined(__HIPCC__)
838// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids.  HIP counts a gfx11
839// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query
840// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room.  gfx1151 (20
841// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same
842// work items and arithmetic: the results do not change).  STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob).
843static int wgp_blocks(int occ) {
844    static const int env = [] {
845        const char* v = std::getenv("STRATA_PF_OCC");
846        return v != nullptr ? std::atoi(v) : 0;
847    }();
848    return env > 0 ? env : 2 * std::max(occ, 1);
849}
850#endif
851const DevInfo &dev_info() try {
852    int dev = 0;
853    dev = dpct::get_current_device_id();
854    std::lock_guard<std::mutex> lk(g_mu);
855    DevInfo& d = g_dev[dev & 31];
856    if (d.done) return d;
857    d.done = true;
858#if defined(STRATA_HIP_GFX906)
859    // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
860    // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
861    return d;
862#elif defined(__HIPCC__)
863    {   // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels
864        cudaDeviceProp prop;
865        cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
866        hipFuncAttributes fa{};
867        if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||
868            hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(expert_w11_kernel<true>)) != hipSuccess) {
869            cudaGetLastError();
870            return d;
871        }
872        if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel<true>, W_THREADS, 0) != hipSuccess ||
873            hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel<false>, W_THREADS, 0) != hipSuccess)
874            d.occ_gu = d.occ_d = 0;
875        d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0;
876        cudaGetLastError();
877        return d;
878    }
879#else
880    int major = 0, minor = 0;
881    major = dpct::get_device(dev).get_major_version();
882    minor = dpct::get_device(dev).get_minor_version();
883    d.sms = dpct::get_device(dev).get_max_compute_units();
884    d.cc = 10 * major + minor;
885    if (d.cc < 80) return d;
886    // the device code of this card's arch must have the kernels (a build without an sm_80+ target has an empty body)
887    dpct::kernel_function_info fa{};
888    if (DPCT_CHECK_ERROR(dpct::get_kernel_function_info(
889            &fa, (const void *)expert_kernel<true>)) != 0 ||
890        fa.ptxVersion < 80) {
891        /*
892        DPCT1026: The call to cudaGetLastError was removed because this
893        functionality is redundant in SYCL.
894        */
895        d.cc = 0;
896        return d;
897    }
898    /*
899    DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 because
900    SYCL currently does not support corresponding setting.
901    */
902    ck(0, "smem gu");
903    /*
904    DPCT1027: The call to cudaFuncSetAttribute was replaced with 0 because
905    SYCL currently does not support corresponding setting.
906    */
907    ck(0, "smem down");
908    /*
909    DPCT1111: Please verify the input arguments of
910    "dpct::experimental::calculate_max_active_wg_per_xecore" base on the target
911    function "expert_kernel<true>".
912    */
913    dpct::experimental::calculate_max_active_wg_per_xecore(
914        &d.occ_gu, THREADS,
915        smem_bytes(true) +
916            dpct_placeholder /* total share local memory size */);
917    /*
918    DPCT1111: Please verify the input arguments of
919    "dpct::experimental::calculate_max_active_wg_per_xecore" base on the target
920    function "expert_kernel<false>".
921    */
922    dpct::experimental::calculate_max_active_wg_per_xecore(
923        &d.occ_d, THREADS,
924        smem_bytes(false) +
925            dpct_placeholder /* total share local memory size */);
926    if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0;                   // does not fit this card: the MMQ path
927    /*
928    DPCT1026: The call to cudaGetLastError was removed because this
929    functionality is redundant in SYCL.
930    */
931#endif
932    return d;
933}
934catch (sycl::exception const &exc) {
935  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
936            << ", line:" << __LINE__ << std::endl;
937  std::exit(1);
938}
939
940}  // namespace
941
942bool built() { return true; }
943// the blob layout and the tile loops below are Flash-Next's 2560 x 640 (O_D_CODES = 1280 * 640 ...): another compiled shape never takes this path
944bool available() { return strata::core::kCompiledGeometry.n_embd == 2560 && strata::core::kCompiledGeometry.n_ff == 640 && dev_info().cc >= 80; }
945// 0.1.36: on by default for the Q2_0 pack (+13-23% prompts on an RTX 5070; teacher-forced against the FP16 path as
946// close as MMQ at 8K and closer at 32K: phaseA-tests s18-tf); STRATA_PF_FUSED=0 keeps MMQ.  The native packs' kernels
947// (moe_fused_iq) stay opt-in: STRATA_PF_FUSED=1 (requested()).
948bool enabled() {
949    static const bool env = [] {
950        const char* v = std::getenv("STRATA_PF_FUSED");
951#if defined(__HIPCC__)
952        return v != nullptr && v[0] == '1';   // Aurora: the gfx11 WMMA kernels are opt-in (STRATA_PF_FUSED=1)
953#else
954        return v == nullptr || v[0] != '0';
955#endif
956    }();
957    return env && available();
958}
959bool requested() {
960    static const bool env = [] {
961        const char* v = std::getenv("STRATA_PF_FUSED");
962        return v != nullptr && v[0] == '1';
963    }();
964    return env && available();
965}
966
967size_t act_bytes(int64_t rows, int64_t cols) { return (size_t) rows * (size_t) (cols / 64) * AB; }
968size_t group_bytes(int64_t n, int n_expert) {
969    return tiles_at(n_expert) +
970           ((size_t)(n + kTileRows - 1) / kTileRows + (size_t)n_expert) *
971               sizeof(sycl::int2);
972}
973
974void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {
975    if (rows <= 0) return;
976    const int64_t nblk = rows * (cols / 64);
977        {
978            auto exp_props = sycl::ext::oneapi::experimental::properties{
979                sycl::ext::oneapi::experimental::use_root_sync};
980
981            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
982                ->template parallel_for<dpct_kernel_name<class quant_act_kernel_da6c97>>(
983                    sycl::nd_range<3>(sycl::range(1, 1, blocks(nblk, 8)) *
984                                          sycl::range(1, 1, 256),
985                                      sycl::range(1, 1, 256)),
986                    exp_props,
987                    [=](sycl::nd_item<3> item_ct1)
988                        [[sycl::reqd_sub_group_size(32)]] {
989                            quant_act_kernel(x, nblk, (uint8_t *)xa);
990                        });
991        }
992    /*
993    DPCT1010: SYCL uses exceptions to report errors and does not use the
994    error codes. The cudaGetLastError function call was replaced with 0. You
995    need to rewrite this code.
996    */
997    ck(0, "quantize_act");
998}
999
1000void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src,
1001           void* stream) {
1002    if (n_expert < 1 || n_expert > 1024) {
1003        std::fprintf(stderr, "prefill fused experts: %d experts (the grouping takes 1 to 1024)\n", n_expert);
1004        std::exit(1);
1005    }
1006    const dpct::queue_ptr s = strata::q_of(stream);
1007    const Tables tb = tables(scratch, n_expert);
1008    ck(DPCT_CHECK_ERROR(s->memset(tb.cnt, 0, (size_t)n_expert * 4)),
1009       "group memset");
1010    if (n > 0) {
1011        const unsigned nb = std::min<unsigned>(blocks(n, 1024), 4u * (unsigned) std::max(dev_info().sms, 1));
1012        /*
1013        DPCT1049: The work-group size passed to the SYCL kernel may exceed
1014        the limit. To get the device limit, query
1015        info::device::max_work_group_size. Adjust the work-group size if needed.
1016        */
1017            {
1018                auto exp_props = sycl::ext::oneapi::experimental::properties{
1019                    sycl::ext::oneapi::experimental::use_root_sync};
1020
1021                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1022                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1023                        sycl::range((size_t)n_expert * 4), cgh);
1024
1025                    cgh.parallel_for<
1026                        dpct_kernel_name<class count_kernel_9919e0>>(
1027                        sycl::nd_range<3>(sycl::range(1, 1, nb) *
1028                                              sycl::range(1, 1, 1024),
1029                                          sycl::range(1, 1, 1024)),
1030                        exp_props, [=](sycl::nd_item<3> item_ct1) {
1031                            count_kernel(ids, n, n_expert, tb.cnt,
1032                                         dpct_local_acc_ct1
1033                                             .get_multi_ptr<
1034                                                 sycl::access::decorated::no>()
1035                                             .get());
1036                        });
1037                });
1038            }
1039    }
1040    /*
1041    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1042    limit. To get the device limit, query info::device::max_work_group_size.
1043    Adjust the work-group size if needed.
1044    */
1045        {
1046            auto exp_props = sycl::ext::oneapi::experimental::properties{
1047                sycl::ext::oneapi::experimental::use_root_sync};
1048
1049            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class scan_kernel_7ed98e>>(
1050                sycl::nd_range<3>(
1051                    sycl::range(1, 1, (unsigned)((n_expert + 31) / 32 * 32)),
1052                    sycl::range(1, 1, (unsigned)((n_expert + 31) / 32 * 32))),
1053                exp_props,
1054                [=](sycl::nd_item<3> item_ct1)
1055                    [[sycl::reqd_sub_group_size(32)]] {
1056                        scan_kernel(tb, n_expert);
1057                    });
1058        }
1059        if (n > 0) {
1060            auto exp_props = sycl::ext::oneapi::experimental::properties{
1061                sycl::ext::oneapi::experimental::use_root_sync};
1062
1063            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class place_kernel_cf784d>>(
1064                sycl::nd_range<3>(sycl::range(1, 1, blocks(n, 256)) *
1065                                      sycl::range(1, 1, 256),
1066                                  sycl::range(1, 1, 256)),
1067                exp_props, [=](sycl::nd_item<3> item_ct1) {
1068                    place_kernel(ids, n, k, n_expert, tb, slot, src);
1069                });
1070        }
1071    /*
1072    DPCT1010: SYCL uses exceptions to report errors and does not use the
1073    error codes. The cudaGetLastError function call was replaced with 0. You
1074    need to rewrite this code.
1075    */
1076    ck(0, "group");
1077}
1078
1079void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src,
1080             void* ha, float* dm, void* stream) {
1081    if (b.e1 <= b.e0 || n <= 0) return;
1082    const DevInfo& d = dev_info();
1083    const dpct::queue_ptr s = strata::q_of(stream);
1084    const Tables tb = tables(const_cast<void*>(scratch), n_expert);
1085    // the most tiles the batch can have: every row in it, plus a partial tile per expert
1086    const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
1087#if defined(__HIPCC__)
1088    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_gu));
1089    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_d));
1090    expert_w11_kernel<true><<<g_gu, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr);
1091    expert_w11_kernel<false><<<g_d, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) ha, src, nullptr, dm);
1092#else
1093    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * 5, (int64_t) d.sms * d.occ_gu);
1094    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * 10, (int64_t) d.sms * d.occ_d);
1095    /*
1096    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1097    limit. To get the device limit, query info::device::max_work_group_size.
1098    Adjust the work-group size if needed.
1099    */
1100    {
1101        auto exp_props = sycl::ext::oneapi::experimental::properties{
1102            sycl::ext::oneapi::experimental::use_root_sync};
1103        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
1104
1105        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1106            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1107                sycl::range(smem_bytes(true)), cgh);
1108
1109            cgh.parallel_for<dpct_kernel_name<class expert_kernel_f38977,
1110                                              dpct_kernel_scalar<true>>>(
1111                sycl::nd_range<3>(sycl::range(1, 1, g_gu) *
1112                                      sycl::range(1, 1, THREADS),
1113                                  sycl::range(1, 1, THREADS)),
1114                exp_props,
1115                [=](sycl::nd_item<3> item_ct1)
1116                    [[sycl::reqd_sub_group_size(32)]] {
1117                        expert_kernel<true>(
1118                            b, tb, (const uint8_t *)xa, src, (uint8_t *)ha,
1119                            nullptr,
1120                            dpct_local_acc_ct1
1121                                .get_multi_ptr<sycl::access::decorated::no>()
1122                                .get());
1123                    });
1124        });
1125    }
1126    /*
1127    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1128    limit. To get the device limit, query info::device::max_work_group_size.
1129    Adjust the work-group size if needed.
1130    */
1131    {
1132        auto exp_props = sycl::ext::oneapi::experimental::properties{
1133            sycl::ext::oneapi::experimental::use_root_sync};
1134        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
1135
1136        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1137            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1138                sycl::range(smem_bytes(false)), cgh);
1139
1140            cgh.parallel_for<dpct_kernel_name<class expert_kernel_e2d106,
1141                                              dpct_kernel_scalar<false>>>(
1142                sycl::nd_range<3>(sycl::range(1, 1, g_d) *
1143                                      sycl::range(1, 1, THREADS),
1144                                  sycl::range(1, 1, THREADS)),
1145                exp_props,
1146                [=](sycl::nd_item<3> item_ct1)
1147                    [[sycl::reqd_sub_group_size(32)]] {
1148                        expert_kernel<false>(
1149                            b, tb, (const uint8_t *)ha, src, nullptr, dm,
1150                            dpct_local_acc_ct1
1151                                .get_multi_ptr<sycl::access::decorated::no>()
1152                                .get());
1153                    });
1154        });
1155    }
1156#endif
1157    /*
1158    DPCT1010: SYCL uses exceptions to report errors and does not use the
1159    error codes. The cudaGetLastError function call was replaced with 0. You
1160    need to rewrite this code.
1161    */
1162    ck(0, "experts");
1163}
1164
1165}  // namespace strata::prefill::fused