okami.mom/strata

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

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

main
57.1 KiB1052 linesraw
1// 151-b70: fused int8 DPAS expert products (ESIMD, Battlemage) - see include/strata/prefill/esimd_moe.hpp and
2// docs/INTEL_INT8_EXPERTS.md (the behaviour note).
3//
4//  * Tile.  One hardware thread owns 16 output rows (a DPAS N tile; for gate/up the 16 virtual rows alternate gate/up) and up to
5//    MT x 8 activation rows (MT = 2, 4 or 8, picked per group from the experts' mean row count).  It walks K in steps of 32:
6//    decode the 16 weight rows' 32 values into the B operand (registers only), then for each of its row tiles one s8 DPAS 8x16x32
7//    into a zeroed int32 tile, converted to float and scaled by (weight scale of the row and 32-block) x (activation scale of the
8//    row and 32-block) into a float accumulator.  There is no shared memory and no barrier.
9//  * Decode once per tile: the B operand is decoded once per thread and applied to all its MT row tiles.  An expert with more rows
10//    than 8 x MT is split over row-block threads, each decoding again.  A thread's accumulators are MT tiles of 512 bytes in an
11//    8 KB register file (256 GRF of 32 bytes): MT 12, or two output tiles per thread, spilled (3-15 KB) and ran 2-5x slower.
12//  * Scales.  Activations: q8_1 as llama.cpp (d = amax / 127, q = round half away from zero), one float per row and 32 of K.
13//    Weights: IQ3_S d (1 + 2 s), IQ3_XXS d (2 s + 1) / 4, IQ2_S d (2 s + 1) / 8 per 16 (two DPAS per 32 with the other half
14//    zeroed), IQ4_NL d per 32, Q2_0 d per 64; the int8 values are the codebook entries with their signs, never rounded.  The int32
15//    dot product of a 32-block is exact and exactly convertible to float.  The float accumulation order is fixed (K ascending).
16//  * Edge cases.  Rows are padded to tiles of 8 with zeros (stores are masked to the real rows); a group of up to 16 experts per
17//    launch; K a multiple of 256 (IQ3_S / IQ3_XXS / IQ2_S) / 64 (Q2_0) / 32 (IQ4_NL); output rows a multiple of 16.  Blob reads
18//    never go past a matrix end.
19//  * Fallback.  available() is false without the s8 8x16x32 DPAS (a non-Battlemage device) and the caller keeps the dequantize +
20//    oneMKL path; gate_up()/down() return false for a type / shape they do not handle.
21//  * ESIMD on this compiler (oneAPI 2026.1, bmg-g31): a dynamic index into the kernel-argument arrays, and `/` or `%` by a run-time
22//    value, gave wrong values / garbage pointers (the first weight read faulted the GPU); the kernels use constant-index reads
23//    (pick_expert) and 2-D grids.  gather<T, N, VS> with VS > 1 is not available on Battlemage.
24#include <sycl/sycl.hpp>
25#include "strata/kprof.hpp"
26#include <sycl/ext/intel/esimd.hpp>
27#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
28#include <sycl/ext/oneapi/matrix/matrix.hpp>
29#include <algorithm>
30#include <cstdio>
31#include <cstdlib>
32#include <cstring>
33#include <mutex>
34#include <type_traits>
35#include <string>
36#include <vector>
37#include <unordered_map>
38#include "strata/sycl_queue.hpp"
39#include "strata/prefill/esimd_moe.hpp"
40
41#ifdef STRATA_I8_NO_ESIMD
42// an AOT build for a device without the s8 8x16x32 DPAS (Alchemist, Xe-HPC): no ESIMD kernels, available() is false
43namespace strata::prefill::i8 {
44void make_layout(Layout& lo, const int32_t* cnt, int n) {
45    lo.n = n;
46    int r = 0, t = 0;
47    for (int i = 0; i < n; ++i) { lo.cnt[i] = cnt[i]; lo.row0[i] = r; lo.tile0[i] = t; r += cnt[i]; t += (cnt[i] + 7) / 8; }
48    lo.row0[n] = r;
49    lo.tile0[n] = t;
50}
51bool available(void*) { return false; }
52bool battlemage(void*) { return false; }
53bool any_battlemage() { return false; }
54size_t xq_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * 8 * K; }
55size_t dx_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * (K / 32) * 8 * sizeof(float); }
56bool workspace(const Layout&, int, int, Workspace&, void*) { return false; }
57void quantize_rows(const uint16_t*, const Layout&, int, int8_t*, float*, void*) {}
58bool gate_up(int, const uint8_t* const*, size_t, int, const Layout&, int, const int8_t*, const float*, float*, void*) { return false; }
59void swiglu_quantize(const float*, const Layout&, int, int8_t*, float*, void*) {}
60bool down(int, const uint8_t* const*, size_t, int, const Layout&, int, const int8_t*, const float*, float*, void*) { return false; }
61}  // namespace strata::prefill::i8
62#else
63namespace strata::prefill::i8 {
64namespace {
65#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = {
66#define GGML_TABLE_END() };
67#include "iq_tables.inc"
68#undef GGML_TABLE_BEGIN
69#undef GGML_TABLE_END
70
71using namespace sycl::ext::intel::esimd;
72namespace xmx = sycl::ext::intel::esimd::xmx;
73using half = sycl::half;
74
75// ggml types handled
76constexpr int T_IQ3XXS = 18, T_IQ4NL = 20, T_IQ3S = 21, T_IQ2S = 22, T_Q2_0 = 42;
77template <int F> constexpr int blk_bytes() { return F == T_IQ3S ? 110 : F == T_IQ3XXS ? 98 : F == T_IQ2S ? 82 : F == T_IQ4NL ? 18 : 18; }
78constexpr int block_bytes_of(int f) { return f == T_IQ3S ? 110 : f == T_IQ3XXS ? 98 : f == T_IQ2S ? 82 : 18; }
79constexpr int block_vals_of(int f) { return (f == T_IQ3S || f == T_IQ3XXS || f == T_IQ2S) ? 256 : f == T_Q2_0 ? 64 : 32; }
80
81// One device table buffer (uint32 units): the codebooks the decoders gather from.
82constexpr int O_IQ3S = 0;        // iq3s_grid[512]
83constexpr int O_IQ3XXS = 512;    // iq3xxs_grid[256]
84constexpr int O_IQ2S = 768;      // iq2s_grid[1024] as 2048 dwords (low dword of an entry first)
85constexpr int O_KSIGNS = 2816;   // ksigns_iq2xs[128], one byte in the low byte of each dword
86constexpr int O_IQ4 = 2944;      // [256]: byte b -> kvalues_iq4nl[b & 15] in byte 0, kvalues_iq4nl[b >> 4] in byte 1
87constexpr int O_Q2 = 3200;       // [256]: byte b -> its four 2-bit codes minus 1, as four int8 (Q2_0 values)
88constexpr int N_TABLE = 3456;
89
90uint32_t* tables(sycl::queue& q) {
91    static std::mutex mu;
92    static std::unordered_map<sycl::device, uint32_t*> per_dev;   // a layer split has one prompt path per card
93    std::lock_guard<std::mutex> lk(mu);
94    uint32_t*& t = per_dev[q.get_device()];
95    if (!t) {
96        std::vector<uint32_t> h(N_TABLE, 0);
97        for (int i = 0; i < 512; ++i) h[O_IQ3S + i] = iq3s_grid[i];
98        for (int i = 0; i < 256; ++i) h[O_IQ3XXS + i] = iq3xxs_grid[i];
99        for (int i = 0; i < 1024; ++i) { h[O_IQ2S + 2 * i] = (uint32_t) iq2s_grid[i]; h[O_IQ2S + 2 * i + 1] = (uint32_t) (iq2s_grid[i] >> 32); }
100        for (int i = 0; i < 128; ++i) h[O_KSIGNS + i] = ksigns_iq2xs[i];
101        for (int b = 0; b < 256; ++b) {
102            h[O_IQ4 + b] = (uint32_t) (uint8_t) kvalues_iq4nl[b & 15] | ((uint32_t) (uint8_t) kvalues_iq4nl[b >> 4] << 8);
103            uint32_t q2 = 0;
104            for (int k = 0; k < 4; ++k) q2 |= (uint32_t) (uint8_t) (int8_t) (((b >> (2 * k)) & 3) - 1) << (8 * k);
105            h[O_Q2 + b] = q2;
106        }
107        uint32_t* d = sycl::malloc_device<uint32_t>(N_TABLE, q);
108        q.memcpy(d, h.data(), N_TABLE * 4);
109        q.wait();
110        t = d;
111    }
112    return t;
113}
114
115// unaligned 32-bit read at a 2-byte aligned byte offset (per lane) through two dword gathers
116SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld32(const uint8_t* base, simd<uint32_t, 16> off) {
117    simd<uint32_t, 16> a = off & ~3u;
118    simd<uint32_t, 16> lo = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a);
119    simd<uint32_t, 16> hi = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a + 4u);
120    simd<uint32_t, 16> sh = (off & 2u) << 3;   // 0 or 16
121    return (lo >> sh) | ((hi << 16) << (16u - sh));
122}
123// the same with the second dword clamped to byte offset `lim` (the last dword of the matrix): the down matrix ends the expert blob, and a block
124// whose last field is not dword aligned would otherwise read up to 3 bytes past it
125SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld32c(const uint8_t* base, simd<uint32_t, 16> off, uint32_t lim) {
126    simd<uint32_t, 16> a = off & ~3u;
127    simd<uint32_t, 16> a2 = a + 4u;
128    a2.merge(simd<uint32_t, 16>(lim), a2 > lim);
129    simd<uint32_t, 16> lo = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a);
130    simd<uint32_t, 16> hi = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a2);
131    simd<uint32_t, 16> sh = (off & 2u) << 3;
132    return (lo >> sh) | ((hi << 16) << (16u - sh));
133}
134SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> ld16(const uint8_t* base, simd<uint32_t, 16> off) {
135    simd<uint32_t, 16> a = off & ~3u;
136    simd<uint32_t, 16> lo = gather<uint32_t, 16>(reinterpret_cast<const uint32_t*>(base), a);
137    return (lo >> ((off & 2u) << 3)) & 0xffffu;
138}
139SYCL_ESIMD_FUNCTION inline simd<float, 16> half_of(simd<uint32_t, 16> h16) {
140    simd<uint16_t, 16> lo = h16.template bit_cast_view<uint16_t>().template select<16, 2>(0);
141    simd<half, 16> hh = lo.template bit_cast_view<half>();
142    simd<float, 16> f = hh;
143    return f;
144}
145SYCL_ESIMD_FUNCTION inline simd<int, 128> dpas_s8(simd<uint32_t, 128> b, simd<int, 64> a) {
146    simd<int, 128> bi = b.template bit_cast_view<int>();
147    return xmx::dpas<8, 8, int, int, int, int, xmx::dpas_argument_type::s8, xmx::dpas_argument_type::s8>(simd<int, 128>(0), bi, a);
148}
149// sign nibble -> four negation bytes: (g ^ mask) + m negates the bytes whose sign bit is set (g is never 0xFF per byte)
150SYCL_ESIMD_FUNCTION inline simd<uint32_t, 16> apply_signs(simd<uint32_t, 16> g, simd<uint32_t, 16> nib) {
151    simd<uint32_t, 16> m = ((nib * 0x00204081u) & 0x01010101u);
152    simd<uint32_t, 16> mask = m * 255u;
153    return (g ^ mask) + m;
154}
155
156struct GArgs {
157    const uint8_t* blob[kMaxGroup];
158    uint32_t sec_off;                 // gate/up: byte offset of the up rows; down: byte offset of the down rows
159    int n;
160    int row0[kMaxGroup + 1];
161    int tile0[kMaxGroup + 1];
162    int rb0[kMaxGroup + 1];           // first row block of expert i
163    const int8_t* Xq;
164    const float* dx;
165    float* Y;
166    const uint32_t* tab;
167    int ntiles;                       // output tiles of 16
168    int nkb;                          // K / 32
169    int rowb;                         // bytes per weight row
170    int ldy;
171    uint32_t lim;                     // byte offset of the last dword of the matrix the clamped reads (ld32c) stay inside
172    int dbg;                          // bring-up switches (STRATA_I8_DBG): 1 skip the decode, 2 skip the activation loads, 4 skip the stores, 8 skip the K loop
173};
174
175// The expert a work item belongs to, with constant-index reads of the kernel argument arrays.
176struct Pick { int e, row0, cnt, tile0, rb0; const uint8_t* blob; };
177SYCL_ESIMD_FUNCTION inline Pick pick_expert(const GArgs& a, int rbg) {
178    Pick p{0, a.row0[0], a.row0[1] - a.row0[0], a.tile0[0], a.rb0[0], a.blob[0]};
179#pragma unroll
180    for (int i = 1; i < kMaxGroup; ++i)
181        if (i < a.n && rbg >= a.rb0[i]) p = Pick{i, a.row0[i], a.row0[i + 1] - a.row0[i], a.tile0[i], a.rb0[i], a.blob[i]};
182    return p;
183}
184
185int fill_args_mt(GArgs& a, const Layout& lo, int MT) {
186    int rb = 0;
187    for (int i = 0; i < lo.n; ++i) {
188        a.row0[i] = lo.row0[i];
189        a.tile0[i] = lo.tile0[i];
190        a.rb0[i] = rb;
191        const int ntl = (lo.cnt[i] + 7) / 8;
192        rb += (ntl + MT - 1) / MT;
193    }
194    a.row0[lo.n] = lo.row0[lo.n];
195    a.tile0[lo.n] = lo.tile0[lo.n];
196    a.rb0[lo.n] = rb;
197    a.n = lo.n;
198    return rb;
199}
200
201template <int F, int MT, int G> struct TagGu;
202template <int F, int MT, int G> struct TagDn;
203
204// ------------------------------------------------------------------------------------------------ gate/up
205template <int F, int MT, int G>
206void launch_gu(sycl::queue& q, const GArgs a, int nrowblocks) {
207    auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};
208    constexpr int NS = (F == T_IQ2S) ? 2 : 1;   // IQ2_S: two scales per 32 values -> two DPAS with the other half zeroed
209    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
210        h.parallel_for<TagGu<F, MT, G>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {
211            const int rbg = (int) id[0], nt = (int) id[1];
212            const Pick pk = pick_expert(a, rbg);
213            const int cnt = pk.cnt;
214            const int ntl = (cnt + 7) >> 3;
215            const int tl0 = (rbg - pk.rb0) * MT;
216            const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;
217            const int tbase = pk.tile0 + tl0;
218            const uint8_t* We = pk.blob;
219            const uint32_t* T = a.tab;
220            simd<uint32_t, 16> lane(0, 1);
221            simd<uint32_t, 16> ro = (lane & 1u) * a.sec_off + ((lane >> 1) + (uint32_t) (8 * nt)) * (uint32_t) a.rowb;
222            simd<float, 128 * MT> acc = 0.f;
223            const int* Xi = reinterpret_cast<const int*>(a.Xq);
224            for (int sb = 0; sb < ((a.dbg & 8) ? 0 : (a.nkb >> 3)); ++sb) {
225                const uint32_t P = (uint32_t) sb * blk_bytes<F>();
226                const simd<float, 16> d = half_of(ld16(We, ro + P));
227                simd<uint32_t, 16> w0 = 0, w1 = 0, w2 = 0, w3 = 0;   // sb-level fields
228                if constexpr (F == T_IQ3S) {
229                    w0 = ld32(We, ro + (P + 106));   // scales
230                    w1 = ld32(We, ro + (P + 66));    // qh 0..3
231                    w2 = ld32(We, ro + (P + 70));    // qh 4..7
232                } else if constexpr (F == T_IQ2S) {
233                    w0 = ld32(We, ro + (P + 74));    // scales 0..3
234                    w1 = ld32(We, ro + (P + 78));    // scales 4..7
235                    w2 = ld32(We, ro + (P + 66));    // qh 0..3
236                    w3 = ld32(We, ro + (P + 70));    // qh 4..7
237                }
238#pragma unroll 1
239                for (int ib = 0; ib < 8; ++ib) {
240                    const int kb = sb * 8 + ib;
241                    simd<uint32_t, 128> fr0 = 0x01010101u, fr1 = 0u;
242                    simd<float, 16> sw0 = 1.f, sw1 = 1.f;
243                    if (!(a.dbg & 1)) {
244                        if constexpr (F == T_IQ3S) {
245                            simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));
246                            simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));
247                            simd<uint32_t, 16> sg = ld32(We, ro + (P + 74 + 4 * ib));
248                            simd<uint32_t, 16> qhv = (((ib < 4) ? w1 : w2) >> (8 * (ib & 3))) & 0xffu;
249                            simd<uint32_t, 16> scn = ((w0 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu;
250                            sw0 = d * simd<float, 16>(simd<int, 16>(scn * 2u + 1u));
251#pragma unroll
252                            for (int r = 0; r < 8; ++r) {
253                                simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;
254                                simd<uint32_t, 16> idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8);
255                                simd<uint32_t, 16> g = gather<uint32_t, 16>(T + O_IQ3S, idx << 2);
256                                simd<uint32_t, 16> nib = ((sg >> (8 * (r >> 1))) >> (4 * (r & 1))) & 0xfu;
257                                fr0.template select<16, 1>(16 * r) = apply_signs(g, nib);
258                            }
259                        } else if constexpr (F == T_IQ3XXS) {
260                            simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));
261                            simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));
262                            simd<uint32_t, 16> aux = ld32(We, ro + (P + 66 + 4 * ib));
263                            sw0 = d * simd<float, 16>(simd<int, 16>((aux >> 28) * 2u + 1u)) * 0.25f;
264#pragma unroll
265                            for (int il = 0; il < 4; ++il) {
266                                simd<uint32_t, 16> sbyte = gather<uint32_t, 16>(T + O_KSIGNS, ((aux >> (7 * il)) & 127u) << 2);
267#pragma unroll
268                                for (int hh = 0; hh < 2; ++hh) {
269                                    const int r = 2 * il + hh;
270                                    simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;
271                                    simd<uint32_t, 16> idx = (qsw >> (8 * (r & 3))) & 0xffu;
272                                    simd<uint32_t, 16> g = gather<uint32_t, 16>(T + O_IQ3XXS, idx << 2);
273                                    fr0.template select<16, 1>(16 * r) = apply_signs(g, (sbyte >> (4 * hh)) & 0xfu);
274                                }
275                            }
276                        } else if constexpr (F == T_IQ2S) {
277                            simd<uint32_t, 16> idw = ld32(We, ro + (P + 2 + 4 * ib));
278                            simd<uint32_t, 16> sgw = ld32(We, ro + (P + 34 + 4 * ib));
279                            simd<uint32_t, 16> qhb = (((ib < 4) ? w2 : w3) >> (8 * (ib & 3))) & 0xffu;
280                            simd<uint32_t, 16> scb = (((ib < 4) ? w0 : w1) >> (8 * (ib & 3))) & 0xffu;
281                            sw0 = d * simd<float, 16>(simd<int, 16>((scb & 0xfu) * 2u + 1u)) * 0.125f;
282                            sw1 = d * simd<float, 16>(simd<int, 16>((scb >> 4) * 2u + 1u)) * 0.125f;
283#pragma unroll
284                            for (int il = 0; il < 4; ++il) {
285                                simd<uint32_t, 16> idx = ((idw >> (8 * il)) & 0xffu) | ((qhb << (8 - 2 * il)) & 0x300u);
286                                simd<uint32_t, 16> gl = gather<uint32_t, 16>(T + O_IQ2S, (idx << 3));
287                                simd<uint32_t, 16> gh = gather<uint32_t, 16>(T + O_IQ2S, (idx << 3) + 4u);
288                                simd<uint32_t, 16> sbyte = (sgw >> (8 * il)) & 0xffu;
289                                simd<uint32_t, 16> vl = apply_signs(gl, sbyte & 0xfu);
290                                simd<uint32_t, 16> vh = apply_signs(gh, sbyte >> 4);
291                                if (il < 2) {
292                                    fr0.template select<16, 1>(16 * (2 * il)) = vl;
293                                    fr0.template select<16, 1>(16 * (2 * il + 1)) = vh;
294                                } else {
295                                    fr1.template select<16, 1>(16 * (2 * il)) = vl;
296                                    fr1.template select<16, 1>(16 * (2 * il + 1)) = vh;
297                                }
298                            }
299                            // fr0 holds values 0..15 (dwords 0..3, the rest zero), fr1 values 16..31 (dwords 4..7)
300                            fr0.template select<64, 1>(64) = 0u;
301                            fr1.template select<64, 1>(0) = 0u;
302                        }
303                    }
304#pragma unroll
305                    for (int i = 0; i < MT; ++i) {
306                        if (i < nvalid) {
307                            simd<int, 64> av = 0x01010101;
308                            simd<float, 8> dxv = 1.f;
309                            if (!(a.dbg & 2)) {
310                                av = block_load<int, 64>(Xi + ((size_t) (tbase + i) * a.nkb + kb) * 64);
311                                dxv = block_load<float, 8>(a.dx + ((size_t) (tbase + i) * a.nkb + kb) * 8);
312                            }
313                            simd<float, 128> tf = dpas_s8(fr0, av);
314#pragma unroll
315                            for (int r = 0; r < 8; ++r) {
316                                const float dxr = dxv[r];
317                                acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);
318                            }
319                            if constexpr (NS == 2) {
320                                simd<float, 128> tg = dpas_s8(fr1, av);
321#pragma unroll
322                                for (int r = 0; r < 8; ++r) {
323                                    const float dxr = dxv[r];
324                                    acc.template select<16, 1>(128 * i + 16 * r) += tg.template select<16, 1>(16 * r) * (sw1 * dxr);
325                                }
326                            }
327                        }
328                    }
329                }
330            }
331#pragma unroll
332            for (int i = 0; i < MT; ++i) {
333                if (i < nvalid) {
334#pragma unroll
335                    for (int r = 0; r < 8; ++r) {
336                        const int rl = (tl0 + i) * 8 + r;
337                        if (rl < cnt && !(a.dbg & 4))
338                            block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));
339                    }
340                }
341            }
342        });
343    });
344}
345
346// ------------------------------------------------------------------------------------------------ down
347template <int F, int MT, int G>
348void launch_dn(sycl::queue& q, const GArgs a, int nrowblocks) {
349    auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};
350    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
351        h.parallel_for<TagDn<F, MT, G>>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), props, [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {
352            const int rbg = (int) id[0], nt = (int) id[1];
353            const Pick pk = pick_expert(a, rbg);
354            const int cnt = pk.cnt;
355            const int ntl = (cnt + 7) >> 3;
356            const int tl0 = (rbg - pk.rb0) * MT;
357            const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;
358            const int tbase = pk.tile0 + tl0;
359            const uint8_t* We = pk.blob;
360            const uint32_t* T = a.tab;
361            simd<uint32_t, 16> lane(0, 1);
362            simd<uint32_t, 16> ro = (lane + (uint32_t) (16 * nt)) * (uint32_t) a.rowb + a.sec_off;
363            simd<float, 128 * MT> acc = 0.f;
364            const int* Xi = reinterpret_cast<const int*>(a.Xq);
365            for (int kb = 0; kb < ((a.dbg & 8) ? 0 : a.nkb); ++kb) {
366                simd<float, 16> sw0 = 1.f;
367                simd<uint32_t, 128> fr0 = 0x01010101u;
368                if (!(a.dbg & 1)) {
369                    if constexpr (F == T_IQ4NL) {
370                        const uint32_t P = (uint32_t) kb * 18;
371                        sw0 = half_of(ld16(We, ro + P));
372#pragma unroll
373                        for (int j = 0; j < 4; ++j) {
374                            simd<uint32_t, 16> qd = ld32c(We, ro + (P + 2 + 4 * j), a.lim);
375                            // four byte-pair lookups (lo value in byte 0, hi value in byte 1), repacked into the two dwords
376                            simd<uint32_t, 16> t0 = gather<uint32_t, 16>(T + O_IQ4, (qd & 0xffu) << 2);
377                            simd<uint32_t, 16> t1 = gather<uint32_t, 16>(T + O_IQ4, ((qd >> 8) & 0xffu) << 2);
378                            simd<uint32_t, 16> t2 = gather<uint32_t, 16>(T + O_IQ4, ((qd >> 16) & 0xffu) << 2);
379                            simd<uint32_t, 16> t3 = gather<uint32_t, 16>(T + O_IQ4, (qd >> 24) << 2);
380                            fr0.template select<16, 1>(16 * j) = (t0 & 0xffu) | ((t1 & 0xffu) << 8) | ((t2 & 0xffu) << 16) | (t3 << 24);
381                            fr0.template select<16, 1>(16 * (j + 4)) =
382                                ((t0 >> 8) & 0xffu) | (t1 & 0xff00u) | ((t2 & 0xff00u) << 8) | ((t3 & 0xff00u) << 16);
383                        }
384                    } else {   // T_Q2_0: 64 values per block (2 + 16 bytes), two 32-blocks per block, one table lookup per byte
385                        const uint32_t P = (uint32_t) (kb >> 1) * 18;
386                        const int hb = kb & 1;
387                        sw0 = half_of(ld16(We, ro + P));
388                        simd<uint32_t, 16> q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim);
389                        simd<uint32_t, 16> q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim);
390#pragma unroll
391                        for (int r = 0; r < 8; ++r) {
392                            simd<uint32_t, 16> qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu;
393                            fr0.template select<16, 1>(16 * r) = gather<uint32_t, 16>(T + O_Q2, qb << 2);
394                        }
395                    }
396                }
397#pragma unroll
398                for (int i = 0; i < MT; ++i) {
399                    if (i < nvalid) {
400                        simd<int, 64> av = 0x01010101;
401                        simd<float, 8> dxv = 1.f;
402                        if (!(a.dbg & 2)) {
403                            av = block_load<int, 64>(Xi + ((size_t) (tbase + i) * a.nkb + kb) * 64);
404                            dxv = block_load<float, 8>(a.dx + ((size_t) (tbase + i) * a.nkb + kb) * 8);
405                        }
406                        simd<float, 128> tf = dpas_s8(fr0, av);
407#pragma unroll
408                        for (int r = 0; r < 8; ++r) {
409                            const float dxr = dxv[r];
410                            acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);
411                        }
412                    }
413                }
414            }
415#pragma unroll
416            for (int i = 0; i < MT; ++i) {
417                if (i < nvalid) {
418#pragma unroll
419                    for (int r = 0; r < 8; ++r) {
420                        const int rl = (tl0 + i) * 8 + r;
421                        if (rl < cnt && !(a.dbg & 4))
422                            block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));
423                    }
424                }
425            }
426        });
427    });
428}
429
430// ------------------------------------------------------------------------------------------------ work-group versions
431// A work group is WGT = 8 threads side by side on 8 consecutive output tiles (128 outputs) of the same row block.  The
432// activation tiles of the row block are read from global memory ONCE per group, in chunks of 4 steps of 32 (128 of K), into local
433// memory (double buffered, one barrier per chunk) and every thread reads them from there, instead of every thread reading all of
434// them from L2 (80 threads per expert re-read the same ~200 KB: the activation loads were 8 of 19 us of gate/up).  The codebook
435// the decoders gather from is copied into local memory by the group once (its gathers then cost ~nothing).
436constexpr int WGT = 8;
437constexpr auto kAl16 = sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::alignment<16>};
438
439// bytes of the tables a format gathers from (local memory), and the segments copied from the global table buffer
440template <int F> constexpr int tab_bytes() {
441    return F == T_IQ3S ? 2048 : F == T_IQ3XXS ? 1536 : F == T_IQ2S ? 8192 : 1024;   // IQ3XXS: grid 1024 + ksigns 512
442}
443
444template <int F, int MT>
445struct WgLayout {
446    static constexpr int TB = tab_bytes<F>();
447    static constexpr int ASZ = MT * 1024;   // activation tiles of one stage: MT tiles x 4 steps x 256 bytes
448    static constexpr int DSZ = MT * 128;    // their scales: MT tiles x 4 steps x 32 bytes
449    static constexpr int STAGE = ASZ + DSZ;
450    static constexpr int TOTAL = TB + 2 * STAGE;
451    static constexpr int SPLIT = 8 / MT;    // threads per tile in the staging load
452    static constexpr int PART = 1024 / SPLIT;   // bytes of one tile's activations a thread stages
453};
454
455// Staging of one chunk's activation tiles: global -> registers (LOAD_CHUNK) -> local memory stage SS (STORE_CHUNK).  Macros, not
456// lambdas: a lambda capturing the staging registers by reference put them in private memory.
457#define LOAD_CHUNK(CC)                                                                                                         \
458    if (s_tile < nvalid) {                                                                                                     \
459        const int* src_ = Xi + ((size_t) (tbase + s_tile) * a.nkb + (CC) * 4) * 64 + s_part * (L::PART / 4);                  \
460        _Pragma("unroll")                                                                                                      \
461        for (int k = 0; k < L::PART / 256; ++k) stg.template select<64, 1>(64 * k) = block_load<int, 64>(src_ + 64 * k, kAl16); \
462        if (s_part == 0) stg_dx = block_load<float, 32>(a.dx + ((size_t) (tbase + s_tile) * a.nkb + (CC) * 4) * 8, kAl16);    \
463    }
464#define STORE_CHUNK(SS)                                                                                                        \
465    if (s_tile < nvalid) {                                                                                                     \
466        const uint32_t base_ = L::TB + (SS) * L::STAGE;                                                                        \
467        _Pragma("unroll")                                                                                                      \
468        for (int k = 0; k < L::PART / 256; ++k)                                                                                \
469            slm_block_store<int, 64>(base_ + s_tile * 1024 + s_part * L::PART + 256 * k, stg.template select<64, 1>(64 * k), kAl16); \
470        if (s_part == 0) slm_block_store<float, 32>(base_ + L::ASZ + s_tile * 128, stg_dx, kAl16);                             \
471    }
472
473template <int F, int MT, int G> struct TagGuW;
474template <int F, int MT, int G> struct TagDnW;
475
476template <int F, int MT, int G>
477void launch_gu_wg(sycl::queue& q, const GArgs a, int nrowblocks) {
478    using L = WgLayout<F, MT>;
479    auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};
480    constexpr int NS = (F == T_IQ2S) ? 2 : 1;
481    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
482        h.parallel_for<TagGuW<F, MT, G>>(sycl::nd_range<2>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), sycl::range<2>(1, WGT)), props,
483                                         [=](sycl::nd_item<2> it) SYCL_ESIMD_KERNEL {
484            slm_init<L::TOTAL>();
485            const int rbg = (int) it.get_group(0), lt = (int) it.get_local_id(1), nt = (int) it.get_global_id(1);
486            const Pick pk = pick_expert(a, rbg);
487            const int cnt = pk.cnt;
488            const int ntl = (cnt + 7) >> 3;
489            const int tl0 = (rbg - pk.rb0) * MT;
490            const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;
491            const int tbase = pk.tile0 + tl0;
492            const uint8_t* We = pk.blob;
493            const uint32_t* T = a.tab;
494            const int* Xi = reinterpret_cast<const int*>(a.Xq);
495            // the codebook into local memory: thread lt copies its eighth of each segment
496            if constexpr (F == T_IQ3S) {
497#pragma unroll
498                for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)
499                    slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ3S + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);
500            } else if constexpr (F == T_IQ3XXS) {
501#pragma unroll
502                for (int k = 0; k < 1024 / WGT / 64; ++k)
503                    slm_block_store<uint32_t, 16>(lt * (1024 / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ3XXS + (lt * (1024 / WGT) + 64 * k) / 4, kAl16), kAl16);
504                slm_block_store<uint32_t, 16>(1024 + lt * (512 / WGT), block_load<uint32_t, 16>(T + O_KSIGNS + lt * (512 / WGT) / 4, kAl16), kAl16);
505            } else {   // IQ2_S
506#pragma unroll
507                for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)
508                    slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + O_IQ2S + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);
509            }
510            // staging: this thread's piece of the chunk c (tile, part) into registers, then into stage s
511            const int s_tile = lt / L::SPLIT, s_part = lt % L::SPLIT;
512            simd<int, L::PART / 4> stg;
513            simd<float, 32> stg_dx;
514            simd<uint32_t, 16> lane(0, 1);
515            simd<uint32_t, 16> ro = (lane & 1u) * a.sec_off + ((lane >> 1) + (uint32_t) (8 * nt)) * (uint32_t) a.rowb;
516            simd<float, 128 * MT> acc = 0.f;
517            const int nchunks = (a.dbg & 8) ? 0 : (a.nkb >> 2);
518            if (nchunks > 0) { LOAD_CHUNK(0); STORE_CHUNK(0); }
519            barrier();   // the codebook and chunk 0 are in local memory
520            simd<float, 16> d = 0.f;
521            simd<uint32_t, 16> w0 = 0, w1 = 0, w2 = 0, w3 = 0;
522            for (int c = 0; c < nchunks; ++c) {
523                const int sb = c >> 1;
524                const int stage_off = L::TB + (c & 1) * L::STAGE;
525                if (c + 1 < nchunks) { LOAD_CHUNK(c + 1); }
526                if ((c & 1) == 0) {   // new superblock: its scale and the fields shared by its 8 steps
527                    const uint32_t P = (uint32_t) sb * blk_bytes<F>();
528                    d = half_of(ld16(We, ro + P));
529                    if constexpr (F == T_IQ3S) {
530                        w0 = ld32(We, ro + (P + 106)); w1 = ld32(We, ro + (P + 66)); w2 = ld32(We, ro + (P + 70));
531                    } else if constexpr (F == T_IQ2S) {
532                        w0 = ld32(We, ro + (P + 74)); w1 = ld32(We, ro + (P + 78)); w2 = ld32(We, ro + (P + 66)); w3 = ld32(We, ro + (P + 70));
533                    }
534                }
535                const uint32_t P = (uint32_t) sb * blk_bytes<F>();
536#pragma unroll 1
537                for (int ib4 = 0; ib4 < 4; ++ib4) {
538                    const int ib = ((c & 1) << 2) + ib4;
539                    simd<uint32_t, 128> fr0 = 0x01010101u, fr1 = 0u;
540                    simd<float, 16> sw0 = 1.f, sw1 = 1.f;
541                    if (!(a.dbg & 1)) {
542                        if constexpr (F == T_IQ3S) {
543                            simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));
544                            simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));
545                            simd<uint32_t, 16> sg = ld32(We, ro + (P + 74 + 4 * ib));
546                            simd<uint32_t, 16> qhv = (((ib < 4) ? w1 : w2) >> (8 * (ib & 3))) & 0xffu;
547                            simd<uint32_t, 16> scn = ((w0 >> (8 * (ib >> 1))) >> (4 * (ib & 1))) & 0xfu;
548                            sw0 = d * simd<float, 16>(simd<int, 16>(scn * 2u + 1u));
549#pragma unroll
550                            for (int r = 0; r < 8; ++r) {
551                                simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;
552                                simd<uint32_t, 16> idx = ((qsw >> (8 * (r & 3))) & 0xffu) | (((qhv >> r) & 1u) << 8);
553                                simd<uint32_t, 16> g = slm_gather<uint32_t, 16>(idx << 2);
554                                simd<uint32_t, 16> nib = ((sg >> (8 * (r >> 1))) >> (4 * (r & 1))) & 0xfu;
555                                fr0.template select<16, 1>(16 * r) = apply_signs(g, nib);
556                            }
557                        } else if constexpr (F == T_IQ3XXS) {
558                            simd<uint32_t, 16> q0 = ld32(We, ro + (P + 2 + 8 * ib));
559                            simd<uint32_t, 16> q1 = ld32(We, ro + (P + 6 + 8 * ib));
560                            simd<uint32_t, 16> aux = ld32(We, ro + (P + 66 + 4 * ib));
561                            sw0 = d * simd<float, 16>(simd<int, 16>((aux >> 28) * 2u + 1u)) * 0.25f;
562#pragma unroll
563                            for (int il = 0; il < 4; ++il) {
564                                simd<uint32_t, 16> sbyte = slm_gather<uint32_t, 16>(1024u + (((aux >> (7 * il)) & 127u) << 2));
565#pragma unroll
566                                for (int hh = 0; hh < 2; ++hh) {
567                                    const int r = 2 * il + hh;
568                                    simd<uint32_t, 16> qsw = r < 4 ? q0 : q1;
569                                    simd<uint32_t, 16> idx = (qsw >> (8 * (r & 3))) & 0xffu;
570                                    simd<uint32_t, 16> g = slm_gather<uint32_t, 16>(idx << 2);
571                                    fr0.template select<16, 1>(16 * r) = apply_signs(g, (sbyte >> (4 * hh)) & 0xfu);
572                                }
573                            }
574                        } else if constexpr (F == T_IQ2S) {
575                            simd<uint32_t, 16> idw = ld32(We, ro + (P + 2 + 4 * ib));
576                            simd<uint32_t, 16> sgw = ld32(We, ro + (P + 34 + 4 * ib));
577                            simd<uint32_t, 16> qhb = (((ib < 4) ? w2 : w3) >> (8 * (ib & 3))) & 0xffu;
578                            simd<uint32_t, 16> scb = (((ib < 4) ? w0 : w1) >> (8 * (ib & 3))) & 0xffu;
579                            sw0 = d * simd<float, 16>(simd<int, 16>((scb & 0xfu) * 2u + 1u)) * 0.125f;
580                            sw1 = d * simd<float, 16>(simd<int, 16>((scb >> 4) * 2u + 1u)) * 0.125f;
581#pragma unroll
582                            for (int il = 0; il < 4; ++il) {
583                                simd<uint32_t, 16> idx = ((idw >> (8 * il)) & 0xffu) | ((qhb << (8 - 2 * il)) & 0x300u);
584                                simd<uint32_t, 16> gl = slm_gather<uint32_t, 16>(idx << 3);
585                                simd<uint32_t, 16> gh = slm_gather<uint32_t, 16>((idx << 3) + 4u);
586                                simd<uint32_t, 16> sbyte = (sgw >> (8 * il)) & 0xffu;
587                                simd<uint32_t, 16> vl = apply_signs(gl, sbyte & 0xfu);
588                                simd<uint32_t, 16> vh = apply_signs(gh, sbyte >> 4);
589                                if (il < 2) {
590                                    fr0.template select<16, 1>(16 * (2 * il)) = vl;
591                                    fr0.template select<16, 1>(16 * (2 * il + 1)) = vh;
592                                } else {
593                                    fr1.template select<16, 1>(16 * (2 * il)) = vl;
594                                    fr1.template select<16, 1>(16 * (2 * il + 1)) = vh;
595                                }
596                            }
597                            fr0.template select<64, 1>(64) = 0u;
598                            fr1.template select<64, 1>(0) = 0u;
599                        }
600                    }
601#pragma unroll
602                    for (int i = 0; i < MT; ++i) {
603                        if (i < nvalid) {
604                            simd<int, 64> av = 0x01010101;
605                            simd<float, 8> dxv = 1.f;
606                            if (!(a.dbg & 2)) {
607                                av = slm_block_load<int, 64>(stage_off + i * 1024 + ib4 * 256, kAl16);
608                                dxv = slm_block_load<float, 8>(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16);
609                            }
610                            simd<float, 128> tf = dpas_s8(fr0, av);
611#pragma unroll
612                            for (int r = 0; r < 8; ++r) {
613                                const float dxr = dxv[r];
614                                acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);
615                            }
616                            if constexpr (NS == 2) {
617                                simd<float, 128> tg = dpas_s8(fr1, av);
618#pragma unroll
619                                for (int r = 0; r < 8; ++r) {
620                                    const float dxr = dxv[r];
621                                    acc.template select<16, 1>(128 * i + 16 * r) += tg.template select<16, 1>(16 * r) * (sw1 * dxr);
622                                }
623                            }
624                        }
625                    }
626                }
627                if (c + 1 < nchunks) { STORE_CHUNK((c + 1) & 1); }
628                barrier();
629            }
630#pragma unroll
631            for (int i = 0; i < MT; ++i) {
632                if (i < nvalid) {
633#pragma unroll
634                    for (int r = 0; r < 8; ++r) {
635                        const int rl = (tl0 + i) * 8 + r;
636                        if (rl < cnt && !(a.dbg & 4))
637                            block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));
638                    }
639                }
640            }
641        });
642    });
643}
644
645template <int F, int MT, int G>
646void launch_dn_wg(sycl::queue& q, const GArgs a, int nrowblocks) {
647    using L = WgLayout<F, MT>;
648    auto props = sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<G>};
649    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
650        h.parallel_for<TagDnW<F, MT, G>>(sycl::nd_range<2>(sycl::range<2>((size_t) nrowblocks, (size_t) a.ntiles), sycl::range<2>(1, WGT)), props,
651                                         [=](sycl::nd_item<2> it) SYCL_ESIMD_KERNEL {
652            slm_init<L::TOTAL>();
653            const int rbg = (int) it.get_group(0), lt = (int) it.get_local_id(1), nt = (int) it.get_global_id(1);
654            const Pick pk = pick_expert(a, rbg);
655            const int cnt = pk.cnt;
656            const int ntl = (cnt + 7) >> 3;
657            const int tl0 = (rbg - pk.rb0) * MT;
658            const int nvalid = (ntl - tl0) < MT ? (ntl - tl0) : MT;
659            const int tbase = pk.tile0 + tl0;
660            const uint8_t* We = pk.blob;
661            const uint32_t* T = a.tab;
662            const int* Xi = reinterpret_cast<const int*>(a.Xq);
663            constexpr uint32_t TOFF = (F == T_IQ4NL) ? O_IQ4 : O_Q2;
664#pragma unroll
665            for (int k = 0; k < tab_bytes<F>() / WGT / 64; ++k)
666                slm_block_store<uint32_t, 16>(lt * (tab_bytes<F>() / WGT) + 64 * k, block_load<uint32_t, 16>(T + TOFF + (lt * (tab_bytes<F>() / WGT) + 64 * k) / 4, kAl16), kAl16);
667            const int s_tile = lt / L::SPLIT, s_part = lt % L::SPLIT;
668            simd<int, L::PART / 4> stg;
669            simd<float, 32> stg_dx;
670            simd<uint32_t, 16> lane(0, 1);
671            simd<uint32_t, 16> ro = (lane + (uint32_t) (16 * nt)) * (uint32_t) a.rowb + a.sec_off;
672            simd<float, 128 * MT> acc = 0.f;
673            const int nchunks = (a.dbg & 8) ? 0 : (a.nkb >> 2);
674            if (nchunks > 0) { LOAD_CHUNK(0); STORE_CHUNK(0); }
675            barrier();
676            for (int c = 0; c < nchunks; ++c) {
677                const int stage_off = L::TB + (c & 1) * L::STAGE;
678                if (c + 1 < nchunks) { LOAD_CHUNK(c + 1); }
679#pragma unroll 1
680                for (int ib4 = 0; ib4 < 4; ++ib4) {
681                    const int kb = c * 4 + ib4;
682                    simd<float, 16> sw0 = 1.f;
683                    simd<uint32_t, 128> fr0 = 0x01010101u;
684                    if (!(a.dbg & 1)) {
685                        if constexpr (F == T_IQ4NL) {
686                            const uint32_t P = (uint32_t) kb * 18;
687                            sw0 = half_of(ld16(We, ro + P));
688#pragma unroll
689                            for (int j = 0; j < 4; ++j) {
690                                simd<uint32_t, 16> qd = ld32c(We, ro + (P + 2 + 4 * j), a.lim);
691                                simd<uint32_t, 16> t0 = slm_gather<uint32_t, 16>((qd & 0xffu) << 2);
692                                simd<uint32_t, 16> t1 = slm_gather<uint32_t, 16>(((qd >> 8) & 0xffu) << 2);
693                                simd<uint32_t, 16> t2 = slm_gather<uint32_t, 16>(((qd >> 16) & 0xffu) << 2);
694                                simd<uint32_t, 16> t3 = slm_gather<uint32_t, 16>((qd >> 24) << 2);
695                                fr0.template select<16, 1>(16 * j) = (t0 & 0xffu) | ((t1 & 0xffu) << 8) | ((t2 & 0xffu) << 16) | (t3 << 24);
696                                fr0.template select<16, 1>(16 * (j + 4)) =
697                                    ((t0 >> 8) & 0xffu) | (t1 & 0xff00u) | ((t2 & 0xff00u) << 8) | ((t3 & 0xff00u) << 16);
698                            }
699                        } else {   // T_Q2_0
700                            const uint32_t P = (uint32_t) (kb >> 1) * 18;
701                            const int hb = kb & 1;
702                            sw0 = half_of(ld16(We, ro + P));
703                            simd<uint32_t, 16> q0 = ld32c(We, ro + (P + 2 + 8 * hb), a.lim);
704                            simd<uint32_t, 16> q1 = ld32c(We, ro + (P + 6 + 8 * hb), a.lim);
705#pragma unroll
706                            for (int r = 0; r < 8; ++r) {
707                                simd<uint32_t, 16> qb = ((r < 4 ? q0 : q1) >> (8 * (r & 3))) & 0xffu;
708                                fr0.template select<16, 1>(16 * r) = slm_gather<uint32_t, 16>(qb << 2);
709                            }
710                        }
711                    }
712#pragma unroll
713                    for (int i = 0; i < MT; ++i) {
714                        if (i < nvalid) {
715                            simd<int, 64> av = 0x01010101;
716                            simd<float, 8> dxv = 1.f;
717                            if (!(a.dbg & 2)) {
718                                av = slm_block_load<int, 64>(stage_off + i * 1024 + ib4 * 256, kAl16);
719                                dxv = slm_block_load<float, 8>(stage_off + L::ASZ + i * 128 + ib4 * 32, kAl16);
720                            }
721                            simd<float, 128> tf = dpas_s8(fr0, av);
722#pragma unroll
723                            for (int r = 0; r < 8; ++r) {
724                                const float dxr = dxv[r];
725                                acc.template select<16, 1>(128 * i + 16 * r) += tf.template select<16, 1>(16 * r) * (sw0 * dxr);
726                            }
727                        }
728                    }
729                }
730                if (c + 1 < nchunks) { STORE_CHUNK((c + 1) & 1); }
731                barrier();
732            }
733#pragma unroll
734            for (int i = 0; i < MT; ++i) {
735                if (i < nvalid) {
736#pragma unroll
737                    for (int r = 0; r < 8; ++r) {
738                        const int rl = (tl0 + i) * 8 + r;
739                        if (rl < cnt && !(a.dbg & 4))
740                            block_store<float, 16>(a.Y + ((size_t) (pk.row0 + rl)) * a.ldy + 16 * nt, acc.template select<16, 1>(128 * i + 16 * r));
741                    }
742                }
743            }
744        });
745    });
746}
747
748// MT from the group's mean number of 8-row tiles per expert.
749int pick_mt(const Layout& lo) {
750    const double mean = lo.n ? (double) lo.tile0[lo.n] / lo.n : 0;
751    if (mean <= 2.0) return 2;
752    if (mean <= 4.0) return 4;
753    return 8;
754}
755int dbg_flags() {
756    static const int v = [] { const char* s = std::getenv("STRATA_I8_DBG"); return s ? std::atoi(s) : 0; }();
757    return v;
758}
759int mt_for(const Layout& lo) {
760    static const int mo = [] { const char* s = std::getenv("STRATA_I8_MT"); return s ? std::atoi(s) : 0; }();
761    return mo ? mo : pick_mt(lo);
762}
763
764// register mode per tile height: STRATA_I8_GRF=128 (more threads per EU, spills at MT 8) or 256; default 256
765int wg_for() {
766    static const int v = [] { const char* s = std::getenv("STRATA_I8_WG"); return s ? std::atoi(s) : 1; }();
767    return v;
768}
769int grf_for(int mt) {
770    static const int g = [] { const char* s = std::getenv("STRATA_I8_GRF"); return s ? std::atoi(s) : 256; }();
771    (void) mt;
772    return g == 128 ? 128 : 256;
773}
774
775template <class F>
776bool dispatch_mt(int mt, F&& f) {
777    switch (mt) {
778        case 2: f(std::integral_constant<int, 2>{}); return true;
779        case 4: f(std::integral_constant<int, 4>{}); return true;
780        case 8: f(std::integral_constant<int, 8>{}); return true;
781        default: return false;
782    }
783}
784
785struct QArgs {
786    int n;
787    int row0[kMaxGroup + 1];
788    int tile0[kMaxGroup + 1];
789    int nkb;
790    int ld;   // row length in elements of the source
791};
792class QuantTag;
793class SwigluTag;
794
795}  // namespace
796
797void make_layout(Layout& lo, const int32_t* cnt, int n) {
798    lo.n = n;
799    int r = 0, t = 0;
800    for (int i = 0; i < n; ++i) {
801        lo.cnt[i] = cnt[i];
802        lo.row0[i] = r;
803        lo.tile0[i] = t;
804        r += cnt[i];
805        t += (cnt[i] + 7) / 8;
806    }
807    lo.row0[n] = r;
808    lo.tile0[n] = t;
809}
810
811namespace {
812bool bmg_arch(const sycl::device& d) {
813    namespace ex = sycl::ext::oneapi::experimental;
814    if (!d.is_gpu()) return false;
815    const auto a = d.get_info<ex::info::device::architecture>();
816    return a == ex::architecture::intel_gpu_bmg_g21 || a == ex::architecture::intel_gpu_bmg_g31;
817}
818}  // namespace
819
820bool battlemage(void* stream) {
821    sycl::queue& q = *strata::q_of(stream);
822    return bmg_arch(q.get_device());
823}
824
825bool any_battlemage() {
826    static const bool v = [] {
827        try {
828            for (const auto& d : sycl::device::get_devices(sycl::info::device_type::gpu))
829                if (bmg_arch(d)) return true;
830        } catch (...) {}
831        return false;
832    }();
833    return v;
834}
835
836bool available(void* stream) {
837    sycl::queue& q = *strata::q_of(stream);
838    static std::mutex mu;
839    static std::unordered_map<sycl::device, bool> per_dev;
840    std::lock_guard<std::mutex> lk(mu);
841    const sycl::device d = q.get_device();
842    if (auto it = per_dev.find(d); it != per_dev.end()) return it->second;
843    const bool ok = [&] {
844        const char* v = std::getenv("STRATA_I8_FORCE");
845        if (v && v[0] == '0') return false;
846        if (!d.has(sycl::aspect::ext_intel_esimd)) return false;
847        namespace mx = sycl::ext::oneapi::experimental::matrix;
848        bool s8 = false;
849        for (const auto& c : d.get_info<sycl::ext::oneapi::experimental::info::device::matrix_combinations>())
850            if (c.atype == mx::matrix_type::sint8 && c.btype == mx::matrix_type::sint8 && c.nsize == 16 && c.ksize == 32) s8 = true;
851        return s8;
852    }();
853    per_dev[d] = ok;
854    return ok;
855}
856
857size_t xq_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * 8 * K; }
858size_t dx_bytes(const Layout& lo, int K) { return (size_t) lo.tile0[lo.n] * (K / 32) * 8 * sizeof(float); }
859
860bool workspace(const Layout& lo, int K, int n_ff, Workspace& ws, void* stream) {
861    sycl::queue& q = *strata::q_of(stream);
862    static std::mutex mu;
863    struct St { Workspace cur; size_t cap_x = 0, cap_h = 0; };
864    static std::unordered_map<sycl::device, St> per_dev;
865    std::lock_guard<std::mutex> lk(mu);
866    St& st = per_dev[q.get_device()];
867    Workspace& cur = st.cur;
868    size_t& cap_x = st.cap_x;
869    size_t& cap_h = st.cap_h;
870    const size_t nx = xq_bytes(lo, K), nh = xq_bytes(lo, n_ff);
871    if (nx > cap_x || nh > cap_h) {
872        q.wait();
873        if (cur.xq) { sycl::free(cur.xq, q); sycl::free(cur.dx, q); sycl::free(cur.hq, q); sycl::free(cur.dh, q); }
874        cap_x = std::max(nx, cap_x + cap_x / 4);
875        cap_h = std::max(nh, cap_h + cap_h / 4);
876        cur.xq = sycl::malloc_device<int8_t>(cap_x, q);
877        cur.dx = sycl::malloc_device<float>(cap_x / 32 / 8 * 8 + 64, q);   // rows * K/32 floats = bytes / 32
878        cur.hq = sycl::malloc_device<int8_t>(cap_h, q);
879        cur.dh = sycl::malloc_device<float>(cap_h / 32 + 64, q);
880        if (!cur.xq || !cur.dx || !cur.hq || !cur.dh) { cap_x = cap_h = 0; cur = Workspace{}; ws = Workspace{}; return false; }
881    }
882    ws = cur;
883    return true;
884}
885
886void quantize_rows(const uint16_t* X, const Layout& lo, int K, int8_t* Xq, float* dx, void* stream) {
887    if (lo.tile0[lo.n] == 0) return;
888    sycl::queue& q = *strata::q_of(stream);
889    QArgs a{};
890    a.n = lo.n;
891    for (int i = 0; i <= lo.n; ++i) { a.row0[i] = lo.row0[i]; a.tile0[i] = lo.tile0[i]; }
892    a.nkb = K / 32;
893    a.ld = K;
894    const size_t nthreads = (size_t) lo.tile0[lo.n] * a.nkb;
895    const half* Xh = reinterpret_cast<const half*>(X);
896    uint32_t* Xd = reinterpret_cast<uint32_t*>(Xq);
897    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
898        h.parallel_for<QuantTag>(sycl::range<2>((size_t) lo.tile0[lo.n], (size_t) a.nkb), [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {
899            const int T = (int) id[0], kb = (int) id[1];
900            // the expert of tile T, by constant-index reads of the argument arrays (see pick_expert)
901            int t0e = a.tile0[0], r0e = a.row0[0], r1e = a.row0[1];
902#pragma unroll
903            for (int i = 1; i < kMaxGroup; ++i)
904                if (i < a.n && T >= a.tile0[i]) { t0e = a.tile0[i]; r0e = a.row0[i]; r1e = a.row0[i + 1]; }
905            const int cnt = r1e - r0e;
906            simd<float, 8> dxv = 0.f;
907#pragma unroll
908            for (int r = 0; r < 8; ++r) {
909                const int rl = (T - t0e) * 8 + r;
910                simd<uint32_t, 8> qd = 0u;
911                if (rl < cnt) {
912                    simd<half, 32> xh = block_load<half, 32>(Xh + ((size_t) (r0e + rl)) * a.ld + kb * 32);
913                    simd<float, 32> x = xh;
914                    float amax = hmax<float>(abs(x));
915                    const float dd = amax / 127.f;
916                    const float id127 = amax > 0.f ? 127.f / amax : 0.f;
917                    simd<float, 32> y = x * id127;
918                    simd<float, 32> adj = 0.5f;
919                    adj.merge(simd<float, 32>(-0.5f), y < 0.f);
920                    simd<int, 32> qi = convert<int>(y + adj);
921                    simd<int8_t, 32> q8 = convert<int8_t>(qi);
922                    qd = q8.template bit_cast_view<uint32_t>();
923                    dxv[r] = dd;
924                }
925                block_store<uint32_t, 8>(Xd + ((size_t) T * a.nkb + kb) * 64 + r * 8, qd);
926            }
927            block_store<float, 8>(dx + ((size_t) T * a.nkb + kb) * 8, dxv);
928        });
929    });
930}
931
932void swiglu_quantize(const float* GU, const Layout& lo, int n_ff, int8_t* Hq, float* dh, void* stream) {
933    if (lo.tile0[lo.n] == 0) return;
934    sycl::queue& q = *strata::q_of(stream);
935    QArgs a{};
936    a.n = lo.n;
937    for (int i = 0; i <= lo.n; ++i) { a.row0[i] = lo.row0[i]; a.tile0[i] = lo.tile0[i]; }
938    a.nkb = n_ff / 32;
939    a.ld = 2 * n_ff;
940    const size_t nthreads = (size_t) lo.tile0[lo.n] * a.nkb;
941    uint32_t* Hd = reinterpret_cast<uint32_t*>(Hq);
942    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->submit([&](sycl::handler& h) {
943        h.parallel_for<SwigluTag>(sycl::range<2>((size_t) lo.tile0[lo.n], (size_t) a.nkb), [=](sycl::id<2> id) SYCL_ESIMD_KERNEL {
944            const int T = (int) id[0], kb = (int) id[1];
945            // the expert of tile T, by constant-index reads of the argument arrays (see pick_expert)
946            int t0e = a.tile0[0], r0e = a.row0[0], r1e = a.row0[1];
947#pragma unroll
948            for (int i = 1; i < kMaxGroup; ++i)
949                if (i < a.n && T >= a.tile0[i]) { t0e = a.tile0[i]; r0e = a.row0[i]; r1e = a.row0[i + 1]; }
950            const int cnt = r1e - r0e;
951            simd<float, 8> dxv = 0.f;
952#pragma unroll
953            for (int r = 0; r < 8; ++r) {
954                const int rl = (T - t0e) * 8 + r;
955                simd<uint32_t, 8> qd = 0u;
956                if (rl < cnt) {
957                    simd<float, 64> v = block_load<float, 64>(GU + ((size_t) (r0e + rl)) * a.ld + kb * 64);
958                    simd<float, 32> g = v.template select<32, 2>(0);
959                    simd<float, 32> u = v.template select<32, 2>(1);
960                    simd<float, 32> x = g * u / (1.f + exp(-g));
961                    float amax = hmax<float>(abs(x));
962                    const float dd = amax / 127.f;
963                    const float id127 = amax > 0.f ? 127.f / amax : 0.f;
964                    simd<float, 32> y = x * id127;
965                    simd<float, 32> adj = 0.5f;
966                    adj.merge(simd<float, 32>(-0.5f), y < 0.f);
967                    simd<int, 32> qi = convert<int>(y + adj);
968                    simd<int8_t, 32> q8 = convert<int8_t>(qi);
969                    qd = q8.template bit_cast_view<uint32_t>();
970                    dxv[r] = dd;
971                }
972                block_store<uint32_t, 8>(Hd + ((size_t) T * a.nkb + kb) * 64 + r * 8, qd);
973            }
974            block_store<float, 8>(dh + ((size_t) T * a.nkb + kb) * 8, dxv);
975        });
976    });
977}
978
979bool gate_up(int gu_type, const uint8_t* const* blob, size_t up_off, int n_ff, const Layout& lo, int K, const int8_t* Xq,
980             const float* dx, float* GU, void* stream) {
981    if (lo.n == 0 || lo.tile0[lo.n] == 0) return true;
982    if ((gu_type != T_IQ3S && gu_type != T_IQ3XXS && gu_type != T_IQ2S) || K % 256 != 0 || (2 * n_ff) % 16 != 0 ||
983        (up_off & 3) != 0 || lo.n > kMaxGroup)
984        return false;
985    sycl::queue& q = *strata::q_of(stream);
986    GArgs a{};
987    for (int i = 0; i < lo.n; ++i) a.blob[i] = blob[i];
988    a.sec_off = (uint32_t) up_off;
989    a.Xq = Xq; a.dx = dx; a.Y = GU;
990    a.tab = tables(q);
991    a.ntiles = 2 * n_ff / 16;
992    a.nkb = K / 32;
993    a.rowb = (K / 256) * block_bytes_of(gu_type);
994    a.ldy = 2 * n_ff;
995    a.dbg = dbg_flags();
996    const int mt = mt_for(lo);
997    const int rb = fill_args_mt(a, lo, mt);
998    return dispatch_mt(mt, [&](auto mtc) {
999        constexpr int MT = decltype(mtc)::value;
1000        if (wg_for() && gu_type != T_IQ2S && a.nkb % 4 == 0 && a.ntiles % WGT == 0) {   // IQ2_S: its 8 KB codebook copied into local memory by every group costs more than it saves (35 vs 16 us)
1001            if (gu_type == T_IQ3S) launch_gu_wg<T_IQ3S, MT, 256>(q, a, rb);
1002            else if (gu_type == T_IQ3XXS) launch_gu_wg<T_IQ3XXS, MT, 256>(q, a, rb);
1003            else launch_gu_wg<T_IQ2S, MT, 256>(q, a, rb);
1004        } else         if (grf_for(MT) == 128) {
1005            if (gu_type == T_IQ3S) launch_gu<T_IQ3S, MT, 128>(q, a, rb);
1006            else if (gu_type == T_IQ3XXS) launch_gu<T_IQ3XXS, MT, 128>(q, a, rb);
1007            else launch_gu<T_IQ2S, MT, 128>(q, a, rb);
1008        } else {
1009            if (gu_type == T_IQ3S) launch_gu<T_IQ3S, MT, 256>(q, a, rb);
1010            else if (gu_type == T_IQ3XXS) launch_gu<T_IQ3XXS, MT, 256>(q, a, rb);
1011            else launch_gu<T_IQ2S, MT, 256>(q, a, rb);
1012        }
1013    });
1014}
1015
1016bool down(int d_type, const uint8_t* const* blob, size_t down_off, int n_embd, const Layout& lo, int n_ff, const int8_t* Hq,
1017          const float* dh, float* Dm, void* stream) {
1018    if (lo.n == 0 || lo.tile0[lo.n] == 0) return true;
1019    if ((d_type != T_IQ4NL && d_type != T_Q2_0) || n_ff % block_vals_of(d_type) != 0 || n_embd % 16 != 0 || (down_off & 3) != 0 ||
1020        lo.n > kMaxGroup)
1021        return false;
1022    sycl::queue& q = *strata::q_of(stream);
1023    GArgs a{};
1024    for (int i = 0; i < lo.n; ++i) a.blob[i] = blob[i];
1025    a.sec_off = (uint32_t) down_off;
1026    a.Xq = Hq; a.dx = dh; a.Y = Dm;
1027    a.tab = tables(q);
1028    a.ntiles = n_embd / 16;
1029    a.nkb = n_ff / 32;
1030    a.rowb = (n_ff / block_vals_of(d_type)) * block_bytes_of(d_type);
1031    a.lim = (uint32_t) (down_off + (size_t) n_embd * (size_t) a.rowb) - 4u;
1032    a.ldy = n_embd;
1033    a.dbg = dbg_flags();
1034    const int mt = mt_for(lo);
1035    const int rb = fill_args_mt(a, lo, mt);
1036    return dispatch_mt(mt, [&](auto mtc) {
1037        constexpr int MT = decltype(mtc)::value;
1038        if (wg_for() && a.nkb % 4 == 0 && a.ntiles % WGT == 0) {
1039            if (d_type == T_IQ4NL) launch_dn_wg<T_IQ4NL, MT, 256>(q, a, rb);
1040            else launch_dn_wg<T_Q2_0, MT, 256>(q, a, rb);
1041        } else         if (grf_for(MT) == 128) {
1042            if (d_type == T_IQ4NL) launch_dn<T_IQ4NL, MT, 128>(q, a, rb);
1043            else launch_dn<T_Q2_0, MT, 128>(q, a, rb);
1044        } else {
1045            if (d_type == T_IQ4NL) launch_dn<T_IQ4NL, MT, 256>(q, a, rb);
1046            else launch_dn<T_Q2_0, MT, 256>(q, a, rb);
1047        }
1048    });
1049}
1050
1051}  // namespace strata::prefill::i8
1052#endif  // STRATA_I8_NO_ESIMD