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
74.1 KiB1473 linesraw
1// src/prefill/moe_fused_iq.cu - see include/strata/prefill/moe_fused_iq.hpp (#136: the native packs' prompt experts on
2// the fused int8 kernels of moe_fused.cu).
3//
4// The arithmetic.  An activation block of 32 values is x = d_x * a, a = round(x / d_x) in -127..127, stored in natural
5// order (per 64 values: 64 codes, then {d_0, d_1} and 8 unused bytes - 80 bytes, the Q2_0 path's size).  A weight
6// block of 32 (or 16) values is w = d_w * q with q an int8: the i-quants' codebook entries with their signs applied
7// (IQ2_XXS / IQ2_XS / IQ2_S: 0..43, IQ3_XXS: 0..62, IQ3_S: 0..15, IQ4_XS / IQ4_NL: -127..113), Q2_0's code - 1.  So
8//     sum w x = d_w * d_x * sum q a,     |sum q a| <= 32 * 127 * 127 < 2^22,
9// and the int32 dot becomes a float exactly with one float add: the mma starts from C = 0x4B400000 (the bits of
10// 1.5 * 2^23), so as_float(D) - 1.5 * 2^23 is the dot.  Per output and 32 values: that add, d_w * d_x, one fma (the
11// formats with a scale per 16 values: two dots, each times its d_w, then d_x).  d_w is llama.cpp's own: IQ2_XXS
12// d (2s + 1) / 8, IQ2_XS / IQ2_S d (2s + 1) / 8 per 16, IQ3_XXS d (2s + 1) / 4, IQ3_S d (2s + 1), IQ4_XS d (s - 32),
13// IQ4_NL and Q2_0 d (dequantize_row_* in ggml-quants.c, mmq-load-tiles.cuh).
14//
15// The load stage.  Per 64 values of K (a stage), a thread decodes one 32-value sub-block of one of the work item's
16// weight rows: its block bytes are read from the blob with 16-bit loads (the GGUF blocks are 2-byte aligned: 66 / 74 /
17// 82 / 98 / 110 / 136 / 18 bytes) one stage ahead into registers (and two 256-value blocks ahead into L2), then turned
18// into 32 int8 and the sub-block's scales in shared memory, double-buffered.  The codebooks live in shared memory (up
19// to 8 KB, IQ2_S).  The activations arrive by cp.async, four stages deep, as in moe_fused.cu; the fragments come by
20// ldmatrix.  The products are mma.sync m16n8k32 (m16n8k16 for the formats with a scale per 16 values); the epilogues
21// (SwiGLU, H to int8 per 32 features; down into the per-slot rows) are moe_fused.cu's.
22#define DPCT_PROFILING_ENABLED
23#include <sycl/sycl.hpp>
24#include "strata/kprof.hpp"
25#include <dpct/dpct.hpp>
26#include "strata/sycl_queue.hpp"
27#include "strata/prefill/moe_fused_iq.hpp"
28#include "strata/core/geometry.hpp"
29
30#include "ggml.h"
31
32#define GGML_COMMON_DECL_CUDA
33#define GGML_COMMON_IMPL_CUDA
34#include "ggml-common.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <cstdlib>
39#include <cstring>
40#include <mutex>
41
42namespace strata::prefill::fused {
43namespace {
44
45void ck(dpct::err0 e, const char *what) {
46}
47
48constexpr int AB = 80;                  // activation bytes per 64 values: 64 codes, {d0, d1}, 8 unused
49constexpr int MAGIC = 0x4B400000;       // the bits of 1.5 * 2^23
50constexpr float MAGICF = 12582912.0f;
51// 16 warps, each 64 weight rows x 16 routed rows; WW of them along the weight rows and 16 / WW along the routed rows: a
52// work item is (WR = 64 WW weight rows) x (TR = 256 / WW routed rows of one expert) - 256 x 64 or 128 x 128, chosen
53// per launch by the rows per expert (pick_ww)
54constexpr int THREADS = 512;
55constexpr int WLD = 80;                 // bytes per decoded weight row of a stage: 64 int8 + 16 (no bank conflicts)
56constexpr int tile_rows(int ww) { return 256 / ww; }
57constexpr int weight_rows(int ww) { return 64 * ww; }
58constexpr int ASTAGES = 4;              // cp.async depth of the activations (64 values of K a stage)
59constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640;   // K of gate/up (n_embd) and of down (n_ff)
60
61// the formats (ggml type ids)
62constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S,
63              T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS,
64              T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0,
65              // Aurora (opt-in, HIP gfx11 only): Unsloth UD-Q4_K_XL's experts - gate/up Q4_K (one layer Q5_K), down Q5_1
66              // (five layers Q8_0).  Their weights are w = d_w q + m_w (a minimum), so a sub-block's dot is
67              //   sum w x = d_x (d_w sum q a + m_w sum a):
68              // the activation blocks carry sum a per 32 values in their eight spare bytes (quant_act_nat_kernel and
69              // the H epilogue write it for every path; no other format reads it)
70              T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K, T_Q5_1 = GGML_TYPE_Q5_1, T_Q8_0 = GGML_TYPE_Q8_0;
71static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 &&
72              sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 &&
73              sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18 && sizeof(block_q4_K) == 144 &&
74              sizeof(block_q5_K) == 176 && sizeof(block_q5_1) == 24 && sizeof(block_q8_0) == 34,
75              "the block layouts this file decodes");
76
77// block bytes, scale per 16 values, codebook bytes in shared memory
78constexpr int block_bytes(int t) {
79    return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110
80         : t == T_IQ4_XS ? 136 : t == T_Q4_K ? 144 : t == T_Q5_K ? 176 : t == T_Q5_1 ? 24 : t == T_Q8_0 ? 34 : 18;
81}
82// the formats with a minimum (w = d q + m), and the raw words a sub-block's load stage holds
83constexpr bool has_min(int t) { return t == T_Q4_K || t == T_Q5_K || t == T_Q5_1; }
84constexpr int raw_words(int t) {
85    return t == T_Q4_K ? 10 : t == T_Q5_K ? 18 : t == T_Q5_1 ? 6 : t == T_Q8_0 ? 9 : 5;
86}
87constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; }
88constexpr int grid_bytes(int t) {
89    return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4
90         : t == T_IQ3_S ? 512 * 4 : 0;
91}
92constexpr size_t smem_bytes(int t, int ww) {
93    return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) ASTAGES * tile_rows(ww) * AB +
94           (size_t) tile_rows(ww) * 4 + grid_bytes(t);
95}
96
97// moe_fused.cu's grouping tables (the same layout: fused::group writes them)
98struct Tables {
99    int32_t *cnt, *off, *fill, *ts;
100    sycl::int2 *tiles;
101};
102size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }
103Tables tables(void* scratch, int n_expert) {
104    int32_t* p = (int32_t*) scratch;
105    return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,
106            (sycl::int2 *)((uint8_t *)scratch + tiles_at(n_expert))};
107}
108
109// ---- activations in natural order: one warp per 64 values
110__dpct_inline__ void quant_act_nat_kernel(const float *__restrict__ x,
111                                          int64_t nblk,
112                                          uint8_t *__restrict__ xa) {
113    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
114    const int64_t w =
115        (int64_t)item_ct1.get_group(2) * (item_ct1.get_local_range(2) / 32) +
116        item_ct1.get_local_id(2) / 32;
117    const int lane = item_ct1.get_local_id(2) & 31;
118    if (w >= nblk) return;
119    const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];
120    float a0 = sycl::fabs(v0), a1 = sycl::fabs(v1);
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        a0 = sycl::fmax(
129            a0, dpct::experimental::permute_sub_group_by_xor(
130                    0xffffffffu,
131                    sycl::ext::oneapi::this_work_item::get_sub_group(), a0, o));
132        /*
133        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
134        feature masked sub_group function which may not be supported by all
135        compilers or runtimes. You may need to adjust the code.
136        */
137        a1 = sycl::fmax(
138            a1, dpct::experimental::permute_sub_group_by_xor(
139                    0xffffffffu,
140                    sycl::ext::oneapi::this_work_item::get_sub_group(), a1, o));
141    }
142    uint8_t* out = xa + w * AB;
143    const int c0 = a0 > 0.0f ? sycl::vec<float, 1>{(v0 * (127.0f / a0))}
144                                   .convert<int, sycl::rounding_mode::rte>()[0]
145                             : 0,
146              c1 = a1 > 0.0f ? sycl::vec<float, 1>{(v1 * (127.0f / a1))}
147                                   .convert<int, sycl::rounding_mode::rte>()[0]
148                             : 0;
149    out[lane] = (uint8_t) (int8_t) c0;
150    out[32 + lane] = (uint8_t) (int8_t) c1;
151    int s0 = c0, s1 = c1;   // the codes' sums per 32 values (the formats with a minimum read them)
152#pragma unroll
153    for (int o = 16; o > 0; o >>= 1) {
154        /*
155        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
156        feature masked sub_group function which may not be supported by all
157        compilers or runtimes. You may need to adjust the code.
158        */
159        s0 += dpct::experimental::permute_sub_group_by_xor(
160            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s0,
161            o);
162        /*
163        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
164        feature masked sub_group function which may not be supported by all
165        compilers or runtimes. You may need to adjust the code.
166        */
167        s1 += dpct::experimental::permute_sub_group_by_xor(
168            0xffffffffu, sycl::ext::oneapi::this_work_item::get_sub_group(), s1,
169            o);
170    }
171    if (lane == 0) * (sycl::float4 *)(out + 64) =
172        sycl::float4(a0 / 127.0f, a1 / 127.0f, (float)s0, (float)s1);
173}
174
175#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800
176__dpct_inline__ void cp16(void *dst, const void *src) {
177#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
178    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(
179                     (unsigned)__cvta_generic_to_shared(dst)),
180                 "l"(src));
181#else
182    *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst))) =
183        *(((uint32_t *)(uintptr_t)src));
184    if (16 > 4)
185        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
186          1) = *(((uint32_t *)(uintptr_t)src) + 1);
187    if (16 > 8)
188        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
189          2) = *(((uint32_t *)(uintptr_t)src) + 2);
190    if (16 > 12)
191        *(((uint32_t *)(uintptr_t)(unsigned)__cvta_generic_to_shared(dst)) +
192          3) = *(((uint32_t *)(uintptr_t)src) + 3);
193#endif
194}
195/*
196DPCT1026: The call to "cp.async.commit_group;
197" was removed because current "cp.async" is migrated to synchronous copy
198operation. You may need to adjust the code to tune the performance.
199*/
200#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
201__device__ __forceinline__ void cp_commit() {
202    asm volatile("cp.async.commit_group;\n" ::);
203#else
204__device__ __forceinline__ void cp_commit() {
205#endif }
206/*
207DPCT1053: Migration of device assembly code is not supported.
208*/
209__dpct_inline__ void pf_l2(const void *p) {
210    asm volatile("prefetch.global.L2 [%0];\n" ::"l"(p));
211}
212/*
213DPCT1026: The call to "cp.async.wait_group %0;
214" was removed because current "cp.async" is migrated to synchronous copy
215operation. You may need to adjust the code to tune the performance.
216*/
217#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
218    template <int N> __device__ __forceinline__ void cp_wait() {
219        asm volatile("cp.async.wait_group %0;\n" ::"n"(N));
220#else
221    template <int N> __device__ __forceinline__ void cp_wait() {
222#endif }
223// d = MAGIC + A (16 x 32 s8, row) * B (32 x 8 s8, col): the int32 dot with the magic bias already added (the C
224// operand), so as_float(d) - 1.5 * 2^23 is the dot as a float
225__dpct_inline__ void mma32(int (&d)[4], const uint32_t (&a)[4], uint32_t b0,
226                           uint32_t b1) {
227#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
228            asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 "
229                "{%0,%1,%2,%3}, "
230                "{%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"
231                : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
232                : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1),
233                  "r"(MAGIC));
234#else
235            {
236                volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};
237                sycl::vec<uint32_t, 4> a_mat_frag_ct1(a[0], a[1], a[2], a[3]);
238                sycl::vec<uint32_t, 2> b_mat_frag_ct1(b0, b1);
239                sycl::vec<int32_t, 4> c_mat_frag_ct1(MAGIC, MAGIC, MAGIC,
240                                                     MAGIC);
241                dpct::experimental::matrix::mma<16, 8, 32, int8_t, int32_t>(
242                    reinterpret_cast<volatile void **>(d_mat_frag_ct1),
243                    &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);
244            }
245#endif
246}
247// the same at m16n8k16 (A 16 x 16, B 16 x 8)
248__dpct_inline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uint32_t b0) {
249#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
250            asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 "
251                "{%0,%1,%2,%3}, "
252                "{%4,%5}, {%6}, {%7,%7,%7,%7};\n"
253                : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
254                : "r"(a0), "r"(a1), "r"(b0), "r"(MAGIC));
255#else
256            {
257                volatile void *d_mat_frag_ct1[4] = {&d[0], &d[1], &d[2], &d[3]};
258                sycl::vec<uint32_t, 2> a_mat_frag_ct1(a0, a1);
259                sycl::vec<uint32_t, 1> b_mat_frag_ct1(b0);
260                sycl::vec<int32_t, 4> c_mat_frag_ct1(MAGIC, MAGIC, MAGIC,
261                                                     MAGIC);
262                dpct::experimental::matrix::mma<16, 8, 16, int8_t, int32_t>(
263                    reinterpret_cast<volatile void **>(d_mat_frag_ct1),
264                    &a_mat_frag_ct1, &b_mat_frag_ct1, &c_mat_frag_ct1);
265            }
266#endif
267}
268__dpct_inline__ float dotf(int d) {
269    return sycl::bit_cast<float>(d) - MAGICF;
270}
271// four 8 x 16-byte matrices, row addresses from lanes 0-7, 8-15, 16-23, 24-31: lane (g, t) gets bytes 4t..4t+3 of row g
272// of each - an mma fragment
273__dpct_inline__ void ldsm4(uint32_t (&r)[4], const void *p) {
274#if defined(__SYCL_DEVICE_ONLY__) && defined(__NVPTX__)
275            asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 "
276                         "{%0,%1,%2,%3}, [%4];\n"
277                         : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3])
278                         : "r"((unsigned)__cvta_generic_to_shared(p))
279                         : "memory");
280#else
281            dpct::experimental::matrix::ldmatrix(
282                (uintptr_t)(unsigned)__cvta_generic_to_shared(p), &r[0], &r[1],
283                &r[2], &r[3]);
284#endif
285}
286
287#endif
288#if (defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800) ||    \
289    defined(__HIPCC__)
290#if defined(__HIPCC__)
291__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; }
292#endif
293// ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales
294__dpct_inline__ uint32_t ld16(const uint8_t *p) {
295    return *(const uint16_t *)p;
296}
297__dpct_inline__ uint32_t ld32(const uint8_t *p) {
298    return ld16(p) | (ld16(p + 2) << 16);
299}
300__dpct_inline__ float half_at(uint32_t w) {
301    return sycl::vec<sycl::half, 1>(
302               sycl::bit_cast<sycl::half, unsigned short>((unsigned short)w))
303        .convert<float, sycl::rounding_mode::automatic>()[0];
304}
305// llama.cpp's sign unpacking: 7 bits of signs, the 8th their parity (bit 7 of v may be anything)
306__dpct_inline__ uint32_t unpack_ksigns(uint32_t v) {
307    v &= 0xFF;
308    const uint32_t p = sycl::popcount(v) & 1;
309    return (v ^ p << 7) * 0x01010101u;
310}
311// 8 bytes of a codebook entry with the sign byte `s` (broadcast) applied: bits 0-3 to .x, 4-7 to .y
312__dpct_inline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, uint32_t &qx,
313                             uint32_t &qy) {
314    const uint32_t m0 = dpct::vectorized_binary<sycl::uchar4>(
315                       s & 0x08040201u, 0, std::not_equal_to<>()),
316                   m1 = dpct::vectorized_binary<sycl::uchar4>(
317                       s & 0x80402010u, 0, std::not_equal_to<>());
318    qx = dpct::vectorized_binary<sycl::uchar4>(gx ^ m0, m0, std::minus<>());
319    qy = dpct::vectorized_binary<sycl::uchar4>(gy ^ m1, m1, std::minus<>());
320}
321#if defined(__HIPCC__)
322// gfx11 (Aurora): the signs from a shared-memory table instead of the compare / subtract emulation.  An entry (one per
323// sign byte b; for the 7-bit sign formats per 7 bits, the parity bit folded in) is {m0, c0, m1, c1}: m = 0xFF in the
324// bytes whose sign bit is set (bits 0-3 for .x, 4-7 for .y), c = m & 0x01010101.  q = (g ^ m) + c is -g where the sign
325// is set - the two's complement, byte-wise - and g elsewhere; no byte carries into the next, because no codebook entry
326// has a zero byte (256 - g with g in 1..127; the grids' bytes are 1..62), so it is the bytes signed8 gives.
327__device__ __forceinline__ void signed8t(uint32_t gx, uint32_t gy, const uint4 sg, uint32_t& qx, uint32_t& qy) {
328    qx = (gx ^ sg.x) + sg.y;
329    qy = (gy ^ sg.z) + sg.w;
330}
331__host__ __device__ constexpr int sign_entries(int t) { return t == T_IQ2_S || t == T_IQ3_S ? 256 : 128; }
332__device__ __forceinline__ uint4 sign_entry(int i, bool parity) {
333    uint32_t b = (uint32_t) i;
334    if (parity) b ^= (__popc(b) & 1) << 7;
335    const uint32_t m0 = __vcmpne4(((b & 15) * 0x01010101u) & 0x08040201u, 0),
336                   m1 = __vcmpne4(((b >> 4) * 0x01010101u) & 0x08040201u, 0);
337    return make_uint4(m0, m0 & 0x01010101u, m1, m1 & 0x01010101u);
338}
339#endif
340// 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y
341// W (X5): direct-selector form on gfx: p = low 3 bits of each nibble picks within the table half, bit 3 picks the half;
342// exhaustively bit-exact over all 2^32 inputs (X5). Disable with -DSTRATA_W_NO_T16.
343#if defined(__HIPCC__) && !defined(STRATA_W_NO_T16)
344__device__ __forceinline__ uint32_t table16_one(uint32_t x, const uint32_t (&t)[4]) {
345    const uint32_t p = x & 0x07070707u;
346    const uint32_t a = __builtin_amdgcn_perm(t[1], t[0], p), b = __builtin_amdgcn_perm(t[3], t[2], p);
347    return __builtin_amdgcn_perm(b, a, ((x >> 1) & 0x04040404u) | 0x03020100u);
348}
349__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) {
350    lo = table16_one(q4, t);
351    hi = table16_one(q4 >> 4, t);
352}
353#else
354__dpct_inline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t &lo,
355                             uint32_t &hi) {
356    uint32_t tmp[2];
357    const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1);
358#pragma unroll
359    for (int i = 0; i < 2; ++i) {
360        const uint32_t sh = 16 * i;
361        const uint32_t l = dpct::byte_level_permute(t[0], t[1], q4 >> sh),
362                       h = dpct::byte_level_permute(t[2], t[3], q4 >> sh);
363        tmp[i] = dpct::byte_level_permute(l, h, sel >> sh);
364    }
365    lo = dpct::byte_level_permute(tmp[0], tmp[1], 0x6420);
366    hi = dpct::byte_level_permute(tmp[0], tmp[1], 0x7531);
367}
368#endif
369
370// Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block,
371// ib 0..1; IQ4_NL: the 32-value block).
372// 32 bits at a 2-byte aligned address (one load when it is 4-byte aligned)
373__dpct_inline__ uint32_t ld32a(const uint8_t *p) {
374    return ((uintptr_t) p & 3) == 0 ? *(const uint32_t*) p : ld32(p);
375}
376template <int T, int NW>
377__dpct_inline__ void load_unit(const uint8_t *bp, int ib, uint32_t (&w)[NW]) {
378    static_assert(NW >= raw_words(T), "raw words");
379    if constexpr (T == T_IQ2_XXS) {
380        w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp);
381    } else if constexpr (T == T_IQ2_XS) {
382        w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16);
383    } else if constexpr (T == T_IQ2_S) {
384        w[0] = ld32(bp + 2 + 4 * ib); w[1] = ld32(bp + 34 + 4 * ib);
385        w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) bp[74 + ib] << 24);
386    } else if constexpr (T == T_IQ3_XXS) {
387        w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 66 + 4 * ib); w[3] = ld16(bp);
388    } else if constexpr (T == T_IQ3_S) {
389        w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 74 + 4 * ib);
390        w[3] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) ((bp[106 + ib / 2] >> (4 * (ib & 1))) & 15) << 24);
391    } else if constexpr (T == T_IQ4_XS) {
392#pragma unroll
393        for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 8 + 16 * ib + 4 * k);
394        const uint32_t ls = ((bp[4 + ib / 2] >> (4 * (ib & 1))) & 15) | (((ld16(bp + 2) >> (2 * ib)) & 3) << 4);
395        w[4] = ld16(bp) | (ls << 16);
396    } else if constexpr (T == T_IQ4_NL) {
397#pragma unroll
398        for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k);
399        w[4] = ld16(bp);
400    } else if constexpr (T == T_Q4_K || T == T_Q5_K) {
401        // qs: 32 bytes of the sub-block pair (ib / 2), the nibble chosen in convert; w[8] = d | dmin << 16; w[9]: the
402        // scale/min bytes (get_scale_min_k4's: ib < 4: sc[ib], sc[ib + 4]; else sc[ib + 4], sc[ib - 4], sc[ib]), ib << 24
403        constexpr int QS = T == T_Q4_K ? 16 : 48;
404        const uint8_t* q = bp + QS + 32 * (ib >> 1);
405#pragma unroll
406        for (int k = 0; k < 8; ++k) w[k] = ld32a(q + 4 * k);
407        w[8] = ld32a(bp);
408        const uint8_t* sc = bp + 4;
409        w[9] = ib < 4 ? (uint32_t) sc[ib] | ((uint32_t) sc[ib + 4] << 8)
410                      : (uint32_t) sc[ib + 4] | ((uint32_t) sc[ib - 4] << 8) | ((uint32_t) sc[ib] << 16);
411        w[9] |= (uint32_t) ib << 24;
412        if constexpr (T == T_Q5_K) {
413#pragma unroll
414            for (int k = 0; k < 8; ++k) w[10 + k] = ld32a(bp + 16 + 4 * k);   // qh
415        }
416    } else if constexpr (T == T_Q5_1) {   // d, m, qh, qs[16]
417#pragma unroll
418        for (int k = 0; k < 4; ++k) w[k] = ld32a(bp + 8 + 4 * k);
419        w[4] = ld32a(bp + 4);
420        w[5] = ld32a(bp);
421    } else if constexpr (T == T_Q8_0) {   // d, qs[32]
422#pragma unroll
423        for (int k = 0; k < 8; ++k) w[k] = ld32(bp + 2 + 4 * k);
424        w[8] = ld16(bp);
425    } else {   // Q2_0
426        w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp);
427    }
428}
429
430// The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31).
431template <int T, int NW>
432/*
433DPCT1110: The total declared local variable size in device function convert
434exceeds 128 bytes and may cause high register pressure. Consult with your
435hardware vendor to find the total register size available and adjust the code,
436or use smaller sub-group size to avoid high register pressure.
437*/
438__dpct_inline__ void convert(
439    const uint32_t (&w)[NW], const uint8_t *grid, const uint32_t (&kv)[4],
440    uint32_t (&q)[8], float &s0, float &s1, const sycl::uint4 *sgn = nullptr) {
441    if constexpr (T == T_Q4_K || T == T_Q5_K) {
442        const int ib = (int) (w[9] >> 24), sh = 4 * (ib & 1);
443        uint32_t sc, mn;
444        if (ib < 4) { sc = w[9] & 63; mn = (w[9] >> 8) & 63; }
445        else {
446            sc = ((w[9] & 0xF) | (((w[9] >> 8) & 0xC0) >> 2));   // sc[ib + 4] & 15 | (sc[ib - 4] >> 6) << 4
447            mn = (((w[9]) >> 4) & 0xF) | (((w[9] >> 16) & 0xC0) >> 2);   // sc[ib + 4] >> 4 | (sc[ib] >> 6) << 4
448        }
449#pragma unroll
450        for (int k = 0; k < 8; ++k) {
451            q[k] = (w[k] >> sh) & 0x0F0F0F0Fu;
452            if constexpr (T == T_Q5_K) q[k] |= ((w[10 + k] >> ib) & 0x01010101u) << 4;
453        }
454        s0 = half_at(w[8]) * (float) sc;
455        s1 = -(half_at(w[8] >> 16) * (float) mn);
456    } else if constexpr (T == T_Q5_1) {
457#pragma unroll
458        for (int k = 0; k < 4; ++k) {
459            const uint32_t lo = ((w[4] >> (4 * k)) & 0xF) * 0x00204081u, hi = ((w[4] >> (16 + 4 * k)) & 0xF) * 0x00204081u;
460            q[k] = (w[k] & 0x0F0F0F0Fu) | ((lo & 0x01010101u) << 4);
461            q[4 + k] = ((w[k] >> 4) & 0x0F0F0F0Fu) | ((hi & 0x01010101u) << 4);
462        }
463        s0 = half_at(w[5]);
464        s1 = half_at(w[5] >> 16);
465    } else if constexpr (T == T_Q8_0) {
466#pragma unroll
467        for (int k = 0; k < 8; ++k) q[k] = w[k];
468        s0 = s1 = half_at(w[8]);
469    } else if constexpr (T == T_IQ2_XXS) {
470        const sycl::uint2 *g = (const sycl::uint2 *)grid;
471#pragma unroll
472        for (int l = 0; l < 4; ++l) {
473            const sycl::uint2 e = g[(w[0] >> (8 * l)) & 255];
474#if defined(__HIPCC__)
475            signed8t(e.x, e.y, sgn[(w[1] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);
476#else
477            signed8(e.x(), e.y(), unpack_ksigns(w[1] >> (7 * l)), q[2 * l],
478                    q[2 * l + 1]);
479#endif
480        }
481        s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f;
482    } else if constexpr (T == T_IQ2_XS) {
483        const sycl::uint2 *g = (const sycl::uint2 *)grid;
484#pragma unroll
485        for (int l = 0; l < 4; ++l) {
486            const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF;
487            const sycl::uint2 e = g[c & 511];
488#if defined(__HIPCC__)
489            signed8t(e.x, e.y, sgn[(c >> 9) & 127], q[2 * l], q[2 * l + 1]);
490#else
491            signed8(e.x(), e.y(), unpack_ksigns(c >> 9), q[2 * l],
492                    q[2 * l + 1]);
493#endif
494        }
495        const float d = half_at(w[2]);
496        const uint32_t sc = w[2] >> 16;
497        s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f;
498        s1 = d * (float) (2 * ((sc >> 4) & 15) + 1) * 0.125f;
499    } else if constexpr (T == T_IQ2_S) {
500        const sycl::uint2 *g = (const sycl::uint2 *)grid;
501        const uint32_t qh = (w[2] >> 16) & 255;
502#pragma unroll
503        for (int l = 0; l < 4; ++l) {
504            const sycl::uint2 e =
505                g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)];
506#if defined(__HIPCC__)
507            signed8t(e.x, e.y, sgn[(w[1] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]);
508#else
509            signed8(e.x(), e.y(), ((w[1] >> (8 * l)) & 255) * 0x01010101u,
510                    q[2 * l], q[2 * l + 1]);
511#endif
512        }
513        const float d = half_at(w[2]);
514        const uint32_t sc = w[2] >> 24;
515        s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f;
516        s1 = d * (float) (2 * (sc >> 4) + 1) * 0.125f;
517    } else if constexpr (T == T_IQ3_XXS) {
518        const uint32_t* g = (const uint32_t*) grid;
519#pragma unroll
520        for (int l = 0; l < 4; ++l) {
521            const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;
522#if defined(__HIPCC__)
523            signed8t(g[i0], g[i1], sgn[(w[2] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);
524#else
525            signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]);
526#endif
527        }
528        s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f;
529    } else if constexpr (T == T_IQ3_S) {
530        const uint32_t* g = (const uint32_t*) grid;
531        const uint32_t qh = (w[3] >> 16) & 255;
532#pragma unroll
533        for (int l = 0; l < 4; ++l) {
534            const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;
535#if defined(__HIPCC__)
536            signed8t(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)],
537                     sgn[(w[2] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]);
538#else
539            signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)],
540                    ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]);
541#endif
542        }
543        s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24));
544    } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) {
545#pragma unroll
546        for (int k = 0; k < 4; ++k) table16(w[k], kv, q[k], q[4 + k]);
547        s0 = s1 = T == T_IQ4_XS ? half_at(w[4]) * (float) ((int) (w[4] >> 16) - 32) : half_at(w[4]);
548    } else {   // Q2_0: code - 1 via a byte table {-1, 0, 1, 2}
549#pragma unroll
550        for (int h = 0; h < 4; ++h) {
551            const uint32_t c = (w[h >> 1] >> (16 * (h & 1))) & 0xFFFF;
552            const uint32_t qe =
553                dpct::byte_level_permute(0x020100FFu, 0x020100FFu, c & 0x7777);
554            const uint32_t qo = dpct::byte_level_permute(
555                0x020100FFu, 0x020100FFu, (c >> 2) & 0x7777);
556            q[2 * h] = dpct::byte_level_permute(qe, qo, 0x5140);
557            q[2 * h + 1] = dpct::byte_level_permute(qe, qo, 0x7362);
558        }
559        s0 = s1 = half_at(w[2]);
560    }
561}
562
563template <int T>
564__dpct_inline__ const void *grid_src(
565    const uint64_t *iq2xxs_grid, const uint64_t *iq2xs_grid,
566    const uint64_t *iq2s_grid, const uint32_t *iq3xxs_grid,
567    const uint32_t *iq3s_grid) {
568    if constexpr (T == T_IQ2_XXS) return iq2xxs_grid;
569    else if constexpr (T == T_IQ2_XS) return iq2xs_grid;
570    else if constexpr (T == T_IQ2_S) return iq2s_grid;
571    else if constexpr (T == T_IQ3_XXS) return iq3xxs_grid;
572    else if constexpr (T == T_IQ3_S) return iq3s_grid;
573    else return nullptr;
574}
575#endif
576
577// One work item = (TR routed rows of expert e - one or two of group()'s 64-row tiles -, a block of WR weight rows);
578// a persistent grid walks the batch's items.  GU: gate/up rows of WR / 2 features (format WT) against the rows'
579// tokens' activations, SwiGLU, H to int8 per 32 features into `out`.  !GU: down rows (format WT) against H, FP32 into
580// `dm`.  Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, gate rows as mma rows 0-7 and
581// up rows as 8-15, so a lane holds gate and up of one feature), routed rows 16 wt.. as two n8.
582template <int WT, bool GU, int WW>
583/*
584DPCT1110: The total declared local variable size in device function
585native_kernel exceeds 128 bytes and may cause high register pressure. Consult
586with your hardware vendor to find the total register size available and adjust
587the code, or use smaller sub-group size to avoid high register pressure.
588*/
589__dpct_inline__ void native_kernel(
590    const Batch b, const NativeGeom geo, const Tables tb,
591    const uint8_t *__restrict__ act, const int32_t *__restrict__ src,
592    uint8_t *__restrict__ out, float *__restrict__ dm, uint8_t *dpct_local,
593    uint64_t *iq2xxs_grid, uint64_t *iq2xs_grid, uint64_t *iq2s_grid,
594    uint32_t *iq3xxs_grid, uint32_t *iq3s_grid, const int8_t *kvalues_iq4nl) {
595#if defined(DPCT_COMPATIBILITY_TEMP) && DPCT_COMPATIBILITY_TEMP >= 800
596    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
597    constexpr int TR = tile_rows(WW), WR = weight_rows(WW);
598    constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB;
599    constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64;   // 64-value stages along K
600    constexpr int NFB = (GU ? 1280 : 2560) / WR;          // weight-row blocks per tile
601    constexpr int ACT_LD = NS * AB;                       // bytes per activation row: 3200 (a token), 800 (a row's H)
602    constexpr int BS = block_bytes(WT);
603    constexpr bool K16 = per16(WT);
604    auto smem = (uint8_t *)dpct_local;
605    uint8_t* wt = smem;                                               // [2][WR][WLD] decoded int8 weights
606    float* ws = (float*) (smem + 2 * WT_BYTES);                       // [2][WR][4] their scales per 16 values
607    uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS);                // [ASTAGES][TR][AB] activations
608    int* srow = (int*) (stages + ASTAGES * ACT_STAGE);                // [TR] the activation row of each tile row
609    uint8_t* sgrid = (uint8_t*) (srow + TR);                          // the codebook
610
611    const int tid = item_ct1.get_local_id(2), lane = tid & 31, warp = tid >> 5,
612              g = lane >> 2, tig = lane & 3;
613    const int wf = warp % WW, nb0 = 16 * (warp / WW);
614    if constexpr (grid_bytes(WT) > 0) {
615        const uint32_t *gs = (const uint32_t *)grid_src<WT>(
616            iq2xxs_grid, iq2xs_grid, iq2s_grid, iq3xxs_grid, iq3s_grid);
617#pragma unroll
618        for (int i = tid; i < grid_bytes(WT) / 4;
619             i += THREADS)((uint32_t *)sgrid)[i] = gs[i];
620    }
621    uint32_t kv[4] = {0, 0, 0, 0};
622    if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) {
623#pragma unroll
624        for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3));
625    }
626    // Local weight rows: m tile i of warp wf is rows 64 wf + 16 i.. (mma rows g and g + 8: rows +g and +8+g).  For
627    // gate/up a tile is 8 features, its gate rows then its up rows, so a lane holds gate and up of one feature.  The
628    // fragments come by ldmatrix: lane l gives the address of row (l & 7) of matrix l >> 3 - A: {rows 0-7, rows 8-15}
629    // x {bytes 0-15, 16-31} of a 32-value chunk; B: {tokens nb0 + 0-7, + 8-15} x {bytes 0-15, 16-31}.
630    const int lm = lane >> 3, l8 = lane & 7;
631    const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLD + 16 * (lm >> 1);
632    const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1);
633    // this thread's decode unit (the first 2 WR threads): local weight row ur, sub-block uj of each stage
634    const bool dec = tid < 2 * WR;
635    const int ur = dec ? tid >> 1 : 0, uj = tid & 1;
636    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
637    for (int w = item_ct1.get_group(2); w < nwork;
638         w += item_ct1.get_group_range(2)) {
639        const sycl::int2 tl = tb.tiles[t0 + w / NFB];
640        const int fb = w % NFB, e = tl.x(), row0 = tl.y();
641        if ((row0 - tb.off[e]) % TR != 0) continue;              // a 64-row tile inside an earlier item's TR rows
642        const int nrows = sycl::min(TR, tb.off[e + 1] - row0);
643        const uint8_t* blob = b.blob[e - b.e0];
644        const int rbase = fb * WR;
645        // local row ur: gate/up - feature (WR / 2) fb + 8 (ur >> 4) + (ur & 7), its up row when bit 3 is set
646        const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) +
647                                       (size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row
648                                 : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row;
649        auto unit = [&](int s) -> const uint8_t* {                  // the block of stage s's sub-block
650            if (GU) return wrow + (s >> 2) * BS;
651            return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS;
652        };
653        auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; };
654        // the weight bytes into L2 ahead of the register loads (one stage ahead only - less than a DRAM round trip):
655        // gate/up PF super-blocks ahead (the row's two threads take a block's first and last line), down the whole row
656        // slice at once (180 or 360 bytes a row)
657        constexpr int PF = 2;
658        auto prefetch_sb = [&](int sb) {
659            if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0));
660        };
661        if (GU) {
662#pragma unroll
663            for (int sb = 0; sb < PF; ++sb) prefetch_sb(sb);
664        } else if (dec) {
665#pragma unroll
666            for (size_t o = 128 * (size_t)uj; o < geo.d_row + 127; o += 256)
667                pf_l2(wrow + dpct::min(o, geo.d_row - 1));
668        }
669        /*
670        DPCT1118: SYCL group functions and algorithms must be encountered in
671        converged control flow. You may need to adjust the code.
672        */
673        /*
674        DPCT1065: Consider replacing sycl::nd_item::barrier() with
675        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
676        better performance if there is no access to global memory.
677        */
678        item_ct1.barrier(); // the previous item is done with the buffers
679        if (tid < TR) srow[tid] = tid < nrows ? (GU ? src[row0 + tid] : row0 + tid) : -1;
680        /*
681        DPCT1118: SYCL group functions and algorithms must be encountered in
682        converged control flow. You may need to adjust the code.
683        */
684        /*
685        DPCT1065: Consider replacing sycl::nd_item::barrier() with
686        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
687        better performance if there is no access to global memory.
688        */
689        item_ct1.barrier(); // srow
690        // the rows past the item's end are not loaded: a warp entirely past it skips the products, and the columns
691        // of a partial one are never written (no reduction mixes columns)
692        auto load_act = [&](int s) {
693            uint8_t* st = stages + (s % ASTAGES) * ACT_STAGE;
694            for (int c = tid; c < TR * 5; c += THREADS) {
695                const int r = c / 5, q = c % 5;
696                if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16);
697            }
698        };
699        auto put = [&](const uint32_t (&raw)[5], int buf) {
700            if (!dec) return;
701            uint32_t q[8];
702            float s0, s1;
703            convert<WT>(raw, sgrid, kv, q, s0, s1);
704            sycl::uint4 *d =
705                (sycl::uint4 *)(wt + buf * WT_BYTES + ur * WLD + 32 * uj);
706            d[0] = sycl::uint4(q[0], q[1], q[2], q[3]);
707            d[1] = sycl::uint4(q[4], q[5], q[6], q[7]);
708            *(sycl::float2 *)(ws + buf * WS_FLOATS + ur * 4 + 2 * uj) =
709                sycl::float2(s0, s1);
710        };
711#pragma unroll
712        for (int s = 0; s < ASTAGES - 1; ++s) {
713            if (s < NS) load_act(s);
714            cp_commit();
715        }
716        uint32_t raw[5] = {0, 0, 0, 0, 0};
717        if (dec) load_unit<WT>(unit(0), sub(0), raw);
718        put(raw, 0);
719        if (dec) load_unit<WT>(unit(1), sub(1), raw);
720        // a warp whose rows are all past the tile's end only takes part in the loads
721        const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
722        float acc[4][2][4];
723#pragma unroll
724        for (int i = 0; i < 4; ++i)
725#pragma unroll
726            for (int n = 0; n < 2; ++n)
727#pragma unroll
728                for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
729        for (int s = 0; s < NS; ++s) {
730            cp_wait<ASTAGES - 2>();
731            /*
732            DPCT1118: SYCL group functions and algorithms must be
733            encountered in converged control flow. You may need to adjust the
734            code.
735            */
736            /*
737            DPCT1065: Consider replacing sycl::nd_item::barrier() with
738            sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
739            better performance if there is no access to global memory.
740            */
741            item_ct1.barrier();
742            if (s + ASTAGES - 1 < NS) load_act(s + ASTAGES - 1);
743            cp_commit();
744            if (GU && (s & 3) == 0) prefetch_sb((s >> 2) + PF);
745            if (on0) {
746                const uint8_t* W = wt + (s & 1) * WT_BYTES;
747                const float* S = ws + (s & 1) * WS_FLOATS;
748                const uint8_t* sa = stages + (s % ASTAGES) * ACT_STAGE;
749                // the stage's scales: per weight row 4 (per 16 values), per routed row 2 (per 32)
750                sycl::float2 dx[2][2]; // [n8 tile][column 2 tig + cc]
751#pragma unroll
752                for (int n = 0; n < 2; ++n)
753#pragma unroll
754                    for (int cc = 0; cc < 2; ++cc) dx[n][cc] =
755                        *(const sycl::float2 *)(sa +
756                                                (nb0 + 8 * n + 2 * tig + cc) *
757                                                    AB +
758                                                64);
759#pragma unroll
760                for (int h = 0; h < 2; ++h) {                     // the stage's two 32-value halves
761                    uint32_t bq[4];                               // {n0 bytes 0-15, n0 16-31, n1 0-15, n1 16-31}
762                    ldsm4(bq, sa + b_off + 32 * h);
763#pragma unroll
764                    for (int i = 0; i < 4; ++i) {
765                        uint32_t a[4];                            // {rows g, g + 8} x {bytes 0-15, 16-31}
766                        ldsm4(a, W + a_off + 16 * i * WLD + 32 * h);
767                        const sycl::float2 swa =
768                            *(const sycl::float2 *)(S +
769                                                    (64 * wf + 16 * i + g) * 4 +
770                                                    2 * h);
771                        const sycl::float2 swb =
772                            *(const sycl::float2 *)(S +
773                                                    (64 * wf + 16 * i + 8 + g) *
774                                                        4 +
775                                                    2 * h);
776                        const float wa0 = swa.x(), wa1 = swa.y(), wb0 = swb.x(),
777                                    wb1 = swb.y();
778#pragma unroll
779                        for (int n = 0; n < 2; ++n) {
780                            if (n == 1 && !on1) break;
781                            if constexpr (K16) {
782                                // a scale per 16 weights: the two halves' dots, each times its scale, then d_x
783                                int d0[4], d1[4];
784                                mma16(d0, a[0], a[1], bq[2 * n]);
785                                mma16(d1, a[2], a[3], bq[2 * n + 1]);
786#pragma unroll
787                                for (int q = 0; q < 4; ++q) {
788                                    const float v = sycl::fma(
789                                        (float)(q < 2 ? wa1 : wb1), dotf(d1[q]),
790                                        (q < 2 ? wa0 : wb0) * dotf(d0[q]));
791                                    acc[i][n][q] = sycl::fma(
792                                        h ? dx[n][q & 1].y() : dx[n][q & 1].x(),
793                                        (float)v, acc[i][n][q]);
794                                }
795                            } else {
796                                int d[4];
797                                mma32(d, a, bq[2 * n], bq[2 * n + 1]);
798#pragma unroll
799                                for (int q = 0; q < 4; ++q) {
800                                    const float p = (q < 2 ? wa0 : wb0) *
801                                                    (h ? dx[n][q & 1].y()
802                                                       : dx[n][q & 1].x());
803                                    acc[i][n][q] = sycl::fma(
804                                        (float)p, dotf(d[q]), acc[i][n][q]);
805                                }
806                            }
807                        }
808                    }
809                }
810            }
811            // the next stage's weights (into the other buffer, read after the next barrier).  (Decoding them before
812            // this stage's products instead was slower on the RTX 5070: a layer of 2048 / 3584 / 8192 tokens, IQ2_S
813            // 5.2 / 9.5 / 17.5 ms -> 6.0 / 10.2 / 18.3.)
814            if (s + 1 < NS) {
815                put(raw, (s + 1) & 1);
816                if (dec && s + 2 < NS) load_unit<WT>(unit(s + 2), sub(s + 2), raw);
817            }
818        }
819        if (!on0) continue;
820        if (GU) {
821            // SwiGLU of feature (WR / 2) fb + 32 wf + 8 i + g (lane g of m tile i: rows 64 wf + 16 i + g and + 8), tile
822            // rows nb0 + 8 n + 2 tig + c; H to int8 per row over the warp's 32 features (one 32-value half-block of the
823            // down product's K)
824            const int blk = WW * fb + wf;
825#pragma unroll
826            for (int n = 0; n < 2; ++n) {
827                if (n == 1 && !on1) break;
828#pragma unroll
829                for (int c = 0; c < 2; ++c) {
830                    float h[4], am = 0.0f;
831#pragma unroll
832                    for (int i = 0; i < 4; ++i) {
833                        const float gt = acc[i][n][c], up = acc[i][n][2 + c];
834                        h[i] = gt / (1.0f + sycl::native::exp(-gt)) * up;
835                        am = sycl::fmax(am, sycl::fabs(h[i]));
836                    }
837#pragma unroll
838                    /*
839                    DPCT1108: '__shfl_xor_sync' was migrated with the
840                    experimental feature masked sub_group function which may not
841                    be supported by all compilers or runtimes. You may need to
842                    adjust the code.
843                    */
844                    for (int o = 4; o < 32; o <<= 1) am = sycl::fmax(
845                        am,
846                        dpct::experimental::permute_sub_group_by_xor(
847                            0xffffffffu,
848                            sycl::ext::oneapi::this_work_item::get_sub_group(),
849                            am, o));
850                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
851                    const int r = nb0 + 8 * n + 2 * tig + c;
852                    if (r < nrows) {
853                        uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;
854                        const int hh = blk & 1;
855#pragma unroll
856                        for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] =
857                            (uint8_t)(int8_t)sycl::vec<float, 1>{(h[i] * inv)}
858                                .convert<int, sycl::rounding_mode::rte>()[0];
859                        if (g == 0) *(float*) (o + 64 + 4 * hh) = am / 127.0f;
860                    }
861                }
862            }
863        } else {
864#pragma unroll
865            for (int i = 0; i < 4; ++i)
866#pragma unroll
867                for (int n = 0; n < 2; ++n) {
868                    if (n == 1 && !on1) break;
869#pragma unroll
870                    for (int q = 0; q < 4; ++q) {
871                        const int r = nb0 + 8 * n + 2 * tig + (q & 1);
872                        if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q];
873                    }
874                }
875        }
876    }
877#endif
878}
879
880#if defined(__HIPCC__)
881// ---- Aurora (S23): the native packs' fused experts on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8
882// (wave32).  The CUDA kernel's arithmetic: a 32-value sub-block decoded to int8 (load_unit / convert above) and its
883// scales; per 32 values the int32 dot starts from MAGIC (the C operand), so as_float(d) - 1.5 * 2^23 is the dot; the
884// formats with a scale per 16 values take each 16-value k-step's dot alone.  Fragments (gfx11): A lane l holds the 16
885// k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of column l % 16, C/D lane l holds
886// D[2i + l / 16][l % 16].  Both operands are in natural order: the decoded weights (LDS, double-buffered) and the
887// activations (quant_act_nat_kernel; read by each lane from global/L2, a stage ahead).
888// A work item = NW_ROWS weight rows x a 64-row tile; 8 waves: 4 along the weight rows (32 each) x 2 along the tile
889// (32 each), each 2 x 2 WMMA tiles.  Gate/up: local row r is feature r / 2, its gate (r even) or up (r odd) row, so a
890// lane pair l, l + 16 holds gate and up of one feature.
891#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1150__) || defined(__gfx1151__)
892#define STRATA_NAT_W11 1
893#else
894#define STRATA_NAT_W11 0
895#endif
896typedef int nw_i4 __attribute__((ext_vector_type(4)));
897typedef int nw_i8 __attribute__((ext_vector_type(8)));
898constexpr int NW_ROWS = 128;
899constexpr int NW_THREADS = 256;
900
901__device__ __forceinline__ nw_i8 nw_wmma(nw_i4 a, nw_i4 b, nw_i8 c) {
902#if STRATA_NAT_W11
903    return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false);
904#else
905    __builtin_trap();
906    return c;
907#endif
908}
909__device__ __forceinline__ nw_i4 nw_u4(uint4 v) { return nw_i4{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; }
910
911// W (X1): ALIAS = the H tile lives on the weight buffers (one extra barrier); LB > 0 = amdgpu_waves_per_eu(LB) (VGPR cap).
912// Disable both with -DSTRATA_W_NO_OCC (the launch sites then use <WT, GU, false, 0> and grid factor wgp_blocks).
913template <int WT, bool GU, bool ALIAS = false, int LB = 0>
914__global__ void __launch_bounds__(NW_THREADS) __attribute__((amdgpu_waves_per_eu(LB > 0 ? LB : 1)))
915native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act,
916                  const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) {
917#if STRATA_NAT_W11
918    constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64;  // 64-value stages along K
919    constexpr int NFB = (GU ? 1280 : 2560) / NW_ROWS;     // work items per tile
920    constexpr int ACT_LD = NS * AB;
921    constexpr int BS = block_bytes(WT);
922    constexpr bool K16 = per16(WT);
923    constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16;
924    __shared__ __align__(16) uint8_t wtbuf[2 * NW_ROWS * WLD];
925    uint8_t(*wt)[NW_ROWS][WLD] = reinterpret_cast<uint8_t(*)[NW_ROWS][WLD]>(wtbuf);
926    __shared__ __align__(16) float ws[2][NW_ROWS][4];           // their scales per 16 values
927    __shared__ __align__(16) uint8_t sgrid[GB];
928    constexpr int SGN = (WT == T_IQ2_XXS || WT == T_IQ2_XS || WT == T_IQ2_S || WT == T_IQ3_XXS || WT == T_IQ3_S)
929                            ? sign_entries(WT) : 1;
930    __shared__ __align__(16) uint4 ssign[SGN];                   // the signs of a sign byte, as byte masks
931    __shared__ int srow[kTileRows];
932    __shared__ float hs_sep[(GU && !ALIAS) ? kTileRows : 1][65];
933    static_assert(!ALIAS || (size_t) kTileRows * 65 * 4 <= (size_t) 2 * NW_ROWS * WLD, "H tile must fit the weight buffers");
934    float(*hs)[65] = ALIAS ? reinterpret_cast<float(*)[65]>(wtbuf) : hs_sep;
935    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
936    const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4;
937    if constexpr (grid_bytes(WT) > 0) {
938        const uint32_t* gs = (const uint32_t*) grid_src<WT>();
939        for (int i = tid; i < grid_bytes(WT) / 4; i += NW_THREADS) ((uint32_t*) sgrid)[i] = gs[i];
940    }
941    if constexpr (SGN > 1) {
942        for (int i = tid; i < SGN; i += NW_THREADS) ssign[i] = sign_entry(i, SGN == 128);
943    }
944    uint32_t kv[4] = {0, 0, 0, 0};
945    if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) {
946#pragma unroll
947        for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3));
948    }
949    const int ur = tid >> 1, uj = tid & 1;                       // this thread's decode unit: row ur, sub-block uj
950    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
951    for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
952        const int2 tl = tb.tiles[t0 + w / NFB];
953        const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);
954        const uint8_t* blob = b.blob[e - b.e0];
955        const int rbase = fb * NW_ROWS;
956        const uint8_t* wrow = GU ? blob + ((ur & 1) ? geo.up_off : 0) + (size_t) (fb * (NW_ROWS / 2) + (ur >> 1)) * geo.gu_row
957                                 : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row;
958        auto unit = [&](int s) -> const uint8_t* {
959            if (GU) return wrow + (s >> 2) * BS;
960            return (WT == T_IQ4_NL || WT == T_Q5_1 || WT == T_Q8_0) ? wrow + (2 * s + uj) * BS : wrow + s * BS;
961        };
962        auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; };
963        auto put = [&](const uint32_t (&raw)[raw_words(WT)], int buf) {
964            uint32_t q[8];
965            float s0, s1;
966            convert<WT>(raw, sgrid, kv, q, s0, s1, ssign);
967            uint4* d = (uint4*) &wt[buf][ur][32 * uj];
968            d[0] = make_uint4(q[0], q[1], q[2], q[3]);
969            d[1] = make_uint4(q[4], q[5], q[6], q[7]);
970            *(float2*) &ws[buf][ur][2 * uj] = make_float2(s0, s1);
971        };
972        __syncthreads();                                          // the previous item is done with the buffers
973        if (tid < kTileRows) {
974            const int r = row0 + min(tid, nrows - 1);             // rows past the tile's end repeat its last one
975            srow[tid] = GU ? src[r] : r;
976        }
977        uint32_t raw[raw_words(WT)] = {};
978        load_unit<WT>(unit(0), sub(0), raw);
979        put(raw, 0);
980        if (NS > 1) load_unit<WT>(unit(1), sub(1), raw);
981        __syncthreads();                                          // srow
982        const bool on = 32 * wn < nrows;
983        const uint8_t* brow[2];
984#pragma unroll
985        for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD;
986        float acc[2][2][8];
987#pragma unroll
988        for (int mt = 0; mt < 2; ++mt)
989#pragma unroll
990            for (int nt = 0; nt < 2; ++nt)
991#pragma unroll
992                for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f;
993        uint4 bq[2][4];
994        float2 bx[2], bsum[2];   // the activation scales, and (the formats with a minimum) the codes' sums per 32 values
995        auto fetch_b = [&](int s, uint4 (&q)[2][4], float2 (&x)[2], float2 (&sm)[2]) {
996#pragma unroll
997            for (int nt = 0; nt < 2; ++nt) {
998                const uint4* p = reinterpret_cast<const uint4*>(brow[nt] + s * AB);
999                q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3];
1000                x[nt] = *reinterpret_cast<const float2*>(brow[nt] + s * AB + 64);
1001                if constexpr (has_min(WT)) sm[nt] = *reinterpret_cast<const float2*>(brow[nt] + s * AB + 72);
1002                else sm[nt] = make_float2(0.0f, 0.0f);
1003            }
1004        };
1005        if (on) fetch_b(0, bq, bx, bsum);
1006        for (int s = 0; s < NS; ++s) {
1007            __syncthreads();                                      // stage s's weights are in buffer s & 1
1008            uint4 nbq[2][4];
1009            float2 nbx[2], nbsum[2];
1010            if (on && s + 1 < NS) fetch_b(s + 1, nbq, nbx, nbsum);
1011            if (on) {
1012                const int bf = s & 1;
1013#pragma unroll
1014                for (int h = 0; h < 2; ++h) {
1015#pragma unroll
1016                    for (int mt = 0; mt < 2; ++mt) {
1017                        const int rb = 32 * wm + 16 * mt;
1018                        const uint4* ap = reinterpret_cast<const uint4*>(&wt[bf][rb + l16][32 * h]);
1019                        const nw_i4 A0 = nw_u4(ap[0]), A1 = nw_u4(ap[1]);
1020                        float w0[8], w1[8];
1021#pragma unroll
1022                        for (int i = 0; i < 8; ++i) {
1023                            const float2 sw = *reinterpret_cast<const float2*>(&ws[bf][rb + 2 * i + hi][2 * h]);
1024                            w0[i] = sw.x; w1[i] = sw.y;
1025                        }
1026#pragma unroll
1027                        for (int nt = 0; nt < 2; ++nt) {
1028                            const float dx = h ? bx[nt].y : bx[nt].x;
1029                            const nw_i4 B0 = nw_u4(bq[nt][2 * h]), B1 = nw_u4(bq[nt][2 * h + 1]);
1030                            const nw_i8 m = nw_i8{MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC, MAGIC};
1031                            if constexpr (K16) {
1032                                const nw_i8 d0 = nw_wmma(A0, B0, m), d1 = nw_wmma(A1, B1, m);
1033#pragma unroll
1034                                for (int i = 0; i < 8; ++i) {
1035                                    const float v = fmaf(w1[i], dotf(d1[i]), w0[i] * dotf(d0[i]));
1036                                    acc[mt][nt][i] = fmaf(dx, v, acc[mt][nt][i]);
1037                                }
1038                            } else {
1039                                const nw_i8 d = nw_wmma(A1, B1, nw_wmma(A0, B0, m));
1040#pragma unroll
1041                                for (int i = 0; i < 8; ++i) {
1042                                    acc[mt][nt][i] = fmaf(w0[i] * dx, dotf(d[i]), acc[mt][nt][i]);
1043                                    if constexpr (has_min(WT)) acc[mt][nt][i] = fmaf(w1[i] * dx, h ? bsum[nt].y : bsum[nt].x, acc[mt][nt][i]);
1044                                }
1045                            }
1046                        }
1047                    }
1048                }
1049            }
1050            if (s + 1 < NS) {
1051                put(raw, (s + 1) & 1);                            // the other buffer: its readers passed this barrier
1052                if (s + 2 < NS) load_unit<WT>(unit(s + 2), sub(s + 2), raw);
1053                if (on) {
1054#pragma unroll
1055                    for (int nt = 0; nt < 2; ++nt) {
1056                        bx[nt] = nbx[nt];
1057                        bsum[nt] = nbsum[nt];
1058#pragma unroll
1059                        for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j];
1060                    }
1061                }
1062            }
1063        }
1064        if constexpr (GU) {
1065            if constexpr (ALIAS) __syncthreads();                 // every wave is done reading the weight buffers
1066            if (on) {
1067#pragma unroll
1068                for (int mt = 0; mt < 2; ++mt)
1069#pragma unroll
1070                    for (int nt = 0; nt < 2; ++nt)
1071#pragma unroll
1072                        for (int i = 0; i < 8; ++i) {
1073                            const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16);
1074                            const float gt = acc[mt][nt][i];
1075                            if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up;
1076                        }
1077            }
1078            __syncthreads();
1079            // H block fb (features 64 fb ..) to int8 per 32, natural order: a thread per (tile row, half)
1080            if (tid < 2 * kTileRows) {
1081                const int r = tid >> 1, hh = tid & 1;
1082                if (r < nrows) {
1083                    float am = 0.0f;
1084#pragma unroll 8
1085                    for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j]));
1086                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
1087                    uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB;
1088                    uint32_t wd[8] = {};
1089                    int csum = 0;
1090#pragma unroll
1091                    for (int j = 0; j < 32; ++j) {
1092                        const int c = __float2int_rn(hs[r][32 * hh + j] * inv);
1093                        csum += c;
1094                        wd[j >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (j & 3));
1095                    }
1096                    uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh);
1097                    o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]);
1098                    o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]);
1099                    *reinterpret_cast<float*>(o + 64 + 4 * hh) = am / 127.0f;
1100                    *reinterpret_cast<float*>(o + 72 + 4 * hh) = (float) csum;   // (the formats with a minimum)
1101                }
1102            }
1103        } else {
1104            if (on) {
1105#pragma unroll
1106                for (int mt = 0; mt < 2; ++mt)
1107#pragma unroll
1108                    for (int nt = 0; nt < 2; ++nt) {
1109                        const int r = 32 * wn + 16 * nt + l16;
1110                        if (r < nrows) {
1111                            float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi;
1112#pragma unroll
1113                            for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i];
1114                        }
1115                    }
1116            }
1117        }
1118    }
1119#else
1120    __builtin_trap();
1121#endif
1122}
1123#endif  // __HIPCC__
1124
1125unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }
1126
1127// per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy
1128struct DevInfo {
1129    bool done = false, ok = false;
1130    int sms = 0, occ = 1;
1131};
1132std::mutex g_mu;
1133DevInfo g_dev[32];
1134
1135#if !defined(__HIPCC__)
1136template <int T, bool GU, int WW> bool setup_ww(int& occ) {
1137    dpct::kernel_function_info fa{};
1138    if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != 0 ||
1139        fa.ptxVersion < 80) return false;
1140    if (cudaFuncSetAttribute(native_kernel<T, GU, WW>,
1141                             cudaFuncAttributeMaxDynamicSharedMemorySize,
1142                             (int)smem_bytes(T, WW)) != 0)
1143        return false;
1144    int o = 0;
1145    if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(
1146            &o, native_kernel<T, GU, WW>, THREADS, smem_bytes(T, WW)) != 0 ||
1147        o < 1)
1148        return false;
1149    occ = std::min(occ, o);
1150    return true;
1151}
1152template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); }
1153#endif
1154
1155#if defined(__HIPCC__)
1156// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids.  HIP counts a gfx11
1157// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query
1158// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room.  gfx1151 (20
1159// 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
1160// work items and arithmetic: the results do not change).  STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob).
1161static int wgp_blocks(int occ) {
1162    static const int env = [] {
1163        const char* v = std::getenv("STRATA_PF_OCC");
1164        return v != nullptr ? std::atoi(v) : 0;
1165    }();
1166    return env > 0 ? env : 2 * std::max(occ, 1);
1167}
1168#endif
1169const DevInfo& dev_info() {
1170    int dev = 0;
1171    dev = dpct::get_current_device_id();
1172    std::lock_guard<std::mutex> lk(g_mu);
1173    DevInfo& d = g_dev[dev & 31];
1174    if (d.done) return d;
1175    d.done = true;
1176#if defined(STRATA_HIP_GFX906)
1177    // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
1178    // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
1179    return d;
1180#elif defined(__HIPCC__)
1181    {   // gfx11 with this build's code: the WMMA kernels (one occupancy for all: the same shape and LDS budget)
1182        cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
1183        cudaDeviceProp prop;
1184        hipFuncAttributes fa{};
1185        if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || std::strncmp(prop.gcnArchName, "gfx11", 5) != 0 ||
1186            hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(native_w11_kernel<T_IQ3_XXS, true>)) != hipSuccess) {
1187            cudaGetLastError();
1188            return d;
1189        }
1190        int o = 0;
1191        if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_w11_kernel<T_IQ2_S, true>, NW_THREADS, 0) != hipSuccess)
1192            o = 0;
1193        d.ok = o >= 1;
1194        d.occ = d.ok ? o : 1;
1195        cudaGetLastError();
1196        return d;
1197    }
1198#else
1199    int major = 0;
1200    major = dpct::get_device(dev).get_major_version();
1201    d.sms = dpct::get_device(dev).get_max_compute_units();
1202    if (major < 8) return d;
1203    int occ = 1 << 20;
1204    d.ok = setup_one<T_IQ2_XXS, true>(occ) && setup_one<T_IQ2_XS, true>(occ) && setup_one<T_IQ2_S, true>(occ) &&
1205           setup_one<T_IQ3_XXS, true>(occ) && setup_one<T_IQ3_S, true>(occ) && setup_one<T_IQ4_XS, true>(occ) &&
1206           setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);
1207    d.occ = d.ok ? occ : 1;
1208    /*
1209    DPCT1026: The call to cudaGetLastError was removed because this
1210    functionality is redundant in SYCL.
1211    */
1212#endif
1213    return d;
1214}
1215
1216// opt-in on top of STRATA_PF_FUSED=1: STRATA_PF_FUSED_KQ=1 takes UD-Q4_K_XL's formats (the output differs from the FP16
1217// expert path's at rounding level; KL-gated, see aurora_s23.md)
1218bool kq_on() {
1219    static const bool on = [] {
1220        const char* v = std::getenv("STRATA_PF_FUSED_KQ");
1221        return v != nullptr && v[0] == '1';
1222    }();
1223    return on;
1224}
1225bool gu_covered(int t) {
1226    return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS
1227#if defined(__HIPCC__)
1228           || ((t == T_Q4_K || t == T_Q5_K) && kq_on())   // the gfx11 kernels only
1229#endif
1230        ;
1231}
1232bool d_covered(int t) {
1233    return t == T_Q2_0 || t == T_IQ4_NL
1234#if defined(__HIPCC__)
1235           || ((t == T_Q5_1 || t == T_Q8_0) && kq_on())
1236#endif
1237        ;
1238}
1239
1240template <int T, bool GU>
1241void launch(int ww, unsigned grid, const Batch &b, const NativeGeom &g,
1242            const Tables &tb, const void *act, const int32_t *src, void *out,
1243            float *dm, dpct::queue_ptr s) {
1244    const uint8_t* a = (const uint8_t*) act;
1245    uint8_t* o = (uint8_t*) out;
1246    /*
1247    DPCT1049: The work-group size passed to the SYCL kernel may exceed the
1248    limit. To get the device limit, query info::device::max_work_group_size.
1249    Adjust the work-group size if needed.
1250    */
1251            if (ww == 4) {
1252                iq2xxs_grid.init(*s);
1253                iq2xs_grid.init(*s);
1254                iq2s_grid.init(*s);
1255                iq3xxs_grid.init(*s);
1256                iq3s_grid.init(*s);
1257                kvalues_iq4nl.init(*s);
1258
1259                auto exp_props = sycl::ext::oneapi::experimental::properties{
1260                    sycl::ext::oneapi::experimental::use_root_sync};
1261
1262                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1263                    auto iq2xxs_grid_ptr_ct1 = iq2xxs_grid.get_ptr();
1264                    auto iq2xs_grid_ptr_ct1 = iq2xs_grid.get_ptr();
1265                    auto iq2s_grid_ptr_ct1 = iq2s_grid.get_ptr();
1266                    auto iq3xxs_grid_ptr_ct1 = iq3xxs_grid.get_ptr();
1267                    auto iq3s_grid_ptr_ct1 = iq3s_grid.get_ptr();
1268                    auto kvalues_iq4nl_ptr_ct1 = kvalues_iq4nl.get_ptr();
1269
1270                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1271                        sycl::range(smem_bytes(T, 4)), cgh);
1272
1273                    cgh.parallel_for<dpct_kernel_name<
1274                        class native_kernel_6643fb, dpct_kernel_scalar<T>,
1275                        dpct_kernel_scalar<GU>, dpct_kernel_scalar<4>>>(
1276                        sycl::nd_range<3>(sycl::range(1, 1, grid) *
1277                                              sycl::range(1, 1, THREADS),
1278                                          sycl::range(1, 1, THREADS)),
1279                        exp_props,
1280                        [=](sycl::nd_item<3> item_ct1)
1281                            [[sycl::reqd_sub_group_size(32)]] {
1282                                native_kernel<T, GU, 4>(
1283                                    b, g, tb, a, src, o, dm,
1284                                    dpct_local_acc_ct1
1285                                        .get_multi_ptr<
1286                                            sycl::access::decorated::no>()
1287                                        .get(),
1288                                    iq2xxs_grid_ptr_ct1, iq2xs_grid_ptr_ct1,
1289                                    iq2s_grid_ptr_ct1, iq3xxs_grid_ptr_ct1,
1290                                    iq3s_grid_ptr_ct1, kvalues_iq4nl_ptr_ct1);
1291                            });
1292                });
1293            }
1294            /*
1295            DPCT1049: The work-group size passed to the SYCL kernel may
1296            exceed the limit. To get the device limit, query
1297            info::device::max_work_group_size. Adjust the work-group size if
1298            needed.
1299            */
1300            else {
1301                iq2xxs_grid.init(*s);
1302                iq2xs_grid.init(*s);
1303                iq2s_grid.init(*s);
1304                iq3xxs_grid.init(*s);
1305                iq3s_grid.init(*s);
1306                kvalues_iq4nl.init(*s);
1307
1308                auto exp_props = sycl::ext::oneapi::experimental::properties{
1309                    sycl::ext::oneapi::experimental::use_root_sync};
1310
1311                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
1312                    auto iq2xxs_grid_ptr_ct1 = iq2xxs_grid.get_ptr();
1313                    auto iq2xs_grid_ptr_ct1 = iq2xs_grid.get_ptr();
1314                    auto iq2s_grid_ptr_ct1 = iq2s_grid.get_ptr();
1315                    auto iq3xxs_grid_ptr_ct1 = iq3xxs_grid.get_ptr();
1316                    auto iq3s_grid_ptr_ct1 = iq3s_grid.get_ptr();
1317                    auto kvalues_iq4nl_ptr_ct1 = kvalues_iq4nl.get_ptr();
1318
1319                    sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
1320                        sycl::range(smem_bytes(T, 2)), cgh);
1321
1322                    cgh.parallel_for<dpct_kernel_name<
1323                        class native_kernel_e6c346, dpct_kernel_scalar<T>,
1324                        dpct_kernel_scalar<GU>, dpct_kernel_scalar<2>>>(
1325                        sycl::nd_range<3>(sycl::range(1, 1, grid) *
1326                                              sycl::range(1, 1, THREADS),
1327                                          sycl::range(1, 1, THREADS)),
1328                        exp_props,
1329                        [=](sycl::nd_item<3> item_ct1)
1330                            [[sycl::reqd_sub_group_size(32)]] {
1331                                native_kernel<T, GU, 2>(
1332                                    b, g, tb, a, src, o, dm,
1333                                    dpct_local_acc_ct1
1334                                        .get_multi_ptr<
1335                                            sycl::access::decorated::no>()
1336                                        .get(),
1337                                    iq2xxs_grid_ptr_ct1, iq2xs_grid_ptr_ct1,
1338                                    iq2s_grid_ptr_ct1, iq3xxs_grid_ptr_ct1,
1339                                    iq3s_grid_ptr_ct1, kvalues_iq4nl_ptr_ct1);
1340                            });
1341                });
1342            }
1343}
1344
1345// The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has
1346// about one such tile (56 to 112 rows on average), else 64.  Measured on the RTX 5070 (tests/cuda/prefill_fused_iq_test,
1347// a layer of 2048 / 3584 / 8192 tokens, ms, 64 -> 128): IQ2_S 5.2 -> 6.7, 9.5 -> 9.3, 17.5 -> 19.5; IQ2_XXS 4.2 ->
1348// 5.8, 7.4 -> 7.6, 13.6 -> 16.5; IQ3_S 5.6 -> 6.6, 10.2 -> 8.8, 18.4 -> 19.0; IQ3_XXS 5.1 -> 6.3, 9.1 -> 8.3, 16.5 ->
1349// 17.5 (256 rows was slower still).  STRATA_PF_FUSED_TILE=64|128 forces one.
1350int pick_ww(int64_t n, int n_expert) {
1351    static const int forced = [] {
1352        const char* v = std::getenv("STRATA_PF_FUSED_TILE");
1353        const int t = v ? std::atoi(v) : 0;
1354        return t == 64 ? 4 : t == 128 ? 2 : 0;
1355    }();
1356    if (forced) return forced;
1357    const double avg = (double) n / std::max(n_expert, 1);
1358    return avg > 56.0 && avg <= 112.0 ? 2 : 4;
1359}
1360
1361}  // namespace
1362
1363bool native_supported(int gu_type, int d_type) {
1364    static const bool off = [] {   // STRATA_PF_FUSED_NATIVE=0: the native packs keep MMQ under STRATA_PF_FUSED=1 (A/B)
1365        const char* v = std::getenv("STRATA_PF_FUSED_NATIVE");
1366        return v != nullptr && v[0] == '0';
1367    }();
1368    // GU_ROWS_K / D_ROWS_K, the 1280 / 2560 weight-row counts and the 2560-wide output rows are Flash-Next's: another compiled shape keeps MMQ
1369    if (strata::core::kCompiledGeometry.n_embd != GU_ROWS_K || strata::core::kCompiledGeometry.n_ff != D_ROWS_K) return false;
1370    return !off && requested() && gu_covered(gu_type) && d_covered(d_type) && dev_info().ok;   // opt-in (=1)
1371}
1372
1373void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {
1374    if (rows <= 0) return;
1375    const int64_t nblk = rows * (cols / 64);
1376        {
1377            auto exp_props = sycl::ext::oneapi::experimental::properties{
1378                sycl::ext::oneapi::experimental::use_root_sync};
1379
1380            strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
1381                ->template parallel_for<
1382                    dpct_kernel_name<class quant_act_nat_kernel_7d58c5>>(
1383                    sycl::nd_range<3>(sycl::range(1, 1, blocks(nblk, 8)) *
1384                                          sycl::range(1, 1, 256),
1385                                      sycl::range(1, 1, 256)),
1386                    exp_props,
1387                    [=](sycl::nd_item<3> item_ct1)
1388                        [[sycl::reqd_sub_group_size(32)]] {
1389                            quant_act_nat_kernel(x, nblk, (uint8_t *)xa);
1390                        });
1391        }
1392    /*
1393    DPCT1010: SYCL uses exceptions to report errors and does not use the
1394    error codes. The cudaGetLastError function call was replaced with 0. You
1395    need to rewrite this code.
1396    */
1397    ck(0, "quantize_act_native");
1398}
1399
1400void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa,
1401                    const int32_t* src, void* ha, float* dm, void* stream) {
1402    if (b.e1 <= b.e0 || n <= 0) return;
1403    const DevInfo& d = dev_info();
1404    if (!d.ok || !gu_covered(g.gu_type) || !d_covered(g.d_type)) {
1405        std::fprintf(stderr, "prefill fused experts (native): types %d / %d are not covered here\n", g.gu_type, g.d_type);
1406        std::exit(1);
1407    }
1408    const dpct::queue_ptr s = strata::q_of(stream);
1409    const Tables tb = tables(const_cast<void*>(scratch), n_expert);
1410#if defined(__HIPCC__)
1411    {
1412        const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
1413        // W (X1): LDS alias of the H tile + waves_per_eu(8) (192 VGPRs) + 4 blocks per WGP, only for the types whose
1414        // kernels do not spill under the cap (measured: gate/up IQ2_*, IQ3_*, IQ4_XS 0-5 regs; down IQ4_NL 11, Q8_0 / Q2_0 0;
1415        // Q4_K / Q5_K gate/up and Q5_1 down spill 100+ and keep the old launch).
1416#ifdef STRATA_W_NO_OCC
1417        const bool occ_gu = false, occ_d = false;
1418#else
1419        const bool occ_gu = g.gu_type == T_IQ2_XXS || g.gu_type == T_IQ2_XS || g.gu_type == T_IQ2_S ||
1420                            g.gu_type == T_IQ3_XXS || g.gu_type == T_IQ3_S || g.gu_type == T_IQ4_XS;
1421        const bool occ_d = g.d_type == T_Q2_0 || g.d_type == T_Q8_0 || g.d_type == T_IQ4_NL;
1422#endif
1423        const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / NW_ROWS), (int64_t) d.sms * (occ_gu ? 4 : wgp_blocks(d.occ)));
1424        const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / NW_ROWS), (int64_t) d.sms * (occ_d ? 4 : wgp_blocks(d.occ)));
1425        const uint8_t* xa8 = (const uint8_t*) xa;
1426        uint8_t* ha8 = (uint8_t*) ha;
1427#define STRATA_NW_GU(T) do { if (occ_gu) native_w11_kernel<T, true, true, 8><<<g_gu, NW_THREADS, 0, s>>>(b, g, tb, xa8, src, ha8, nullptr); else native_w11_kernel<T, true><<<g_gu, NW_THREADS, 0, s>>>(b, g, tb, xa8, src, ha8, nullptr); } while (0)
1428        switch (g.gu_type) {
1429            case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break;
1430            case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break;
1431            case T_IQ2_S: STRATA_NW_GU(T_IQ2_S); break;
1432            case T_IQ3_XXS: STRATA_NW_GU(T_IQ3_XXS); break;
1433            case T_IQ3_S: STRATA_NW_GU(T_IQ3_S); break;
1434            case T_Q4_K: STRATA_NW_GU(T_Q4_K); break;
1435            case T_Q5_K: STRATA_NW_GU(T_Q5_K); break;
1436            default: STRATA_NW_GU(T_IQ4_XS); break;
1437        }
1438#undef STRATA_NW_GU
1439#define STRATA_NW_D(T) do { if (occ_d) native_w11_kernel<T, false, true, 8><<<g_d, NW_THREADS, 0, s>>>(b, g, tb, ha8, src, nullptr, dm); else native_w11_kernel<T, false><<<g_d, NW_THREADS, 0, s>>>(b, g, tb, ha8, src, nullptr, dm); } while (0)
1440        if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0);
1441        else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1);
1442        else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0);
1443        else STRATA_NW_D(T_IQ4_NL);
1444#undef STRATA_NW_D
1445        ck(cudaGetLastError(), "experts_native");
1446        return;
1447    }
1448#endif
1449    const int ww = pick_ww(n, n_expert);
1450    // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the
1451    // ones inside a larger item end at once
1452    const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
1453    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / weight_rows(ww)), (int64_t) d.sms * d.occ);
1454    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / weight_rows(ww)), (int64_t) d.sms * d.occ);
1455    switch (g.gu_type) {
1456        case T_IQ2_XXS: launch<T_IQ2_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1457        case T_IQ2_XS: launch<T_IQ2_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1458        case T_IQ2_S: launch<T_IQ2_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1459        case T_IQ3_XXS: launch<T_IQ3_XXS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1460        case T_IQ3_S: launch<T_IQ3_S, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1461        default: launch<T_IQ4_XS, true>(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break;
1462    }
1463    if (g.d_type == T_Q2_0) launch<T_Q2_0, false>(ww, g_d, b, g, tb, ha, src, nullptr, dm, s);
1464    else launch<T_IQ4_NL, false>(ww, g_d, b, g, tb, ha, src, nullptr, dm, s);
1465    /*
1466    DPCT1010: SYCL uses exceptions to report errors and does not use the
1467    error codes. The cudaGetLastError function call was replaced with 0. You
1468    need to rewrite this code.
1469    */
1470    ck(0, "experts_native");
1471}
1472
1473}  // namespace strata::prefill::fused