okami.mom/strata

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

Niko1221SYCL links again after df2-q4sel: df2_select takes the new cb_q4 argument of the shared header and refuses Q4_0 selector codebooks (SYCL stays on the bf16 pack)523b78e21

main
60.2 KiB1106 linesraw
1// sycl/src/kernels/cuda/dflash2.dp.cpp - the small kernels of the DFlash2 drafter on SYCL (Intel Arc).  Hand port of src/kernels/cuda/dflash2.cu for the
2// Q4_0 drafter pack; the interface is include/strata/kernels/dflash2.hpp (a `stream` is a sycl::queue*, null = the default in-order queue).
3//
4// Differences from the CUDA file, all on purpose:
5//   * Q4_0 pack only (df2_gemm throws for a Q8 matrix, df2_q8_tile is absent).
6//   * DF-03, active columns: the GEMM is instantiated per column count NC = 1..8 (acc[R][NC]); the arithmetic of a column does not depend on NC (same steps,
7//     same fma order, same shuffle tree), so the first n columns of an 8-column launch are bitwise the n-column launch.  Alchemist has 128 GRFs a thread:
8//     at 32 lanes a float is 4 GRFs, so acc[8][8] cannot live in registers; fewer columns is the difference between spilling and not.
9//   * conv_rms_quant takes 256 threads (a work-group is at most 512 on Alchemist), the sum of the squares reduces over 8 sub-group partials, not 32.
10//   * attention: no register staging of the next K/V tile (loads go to local memory directly).
11//   * math: sycl::exp / rsqrt / rint (precise) where CUDA uses __expf / rsqrtf.
12// Everything is asynchronous on the queue, allocates nothing and can be recorded into a sycl graph.
13#define DPCT_PROFILING_ENABLED
14#include <sycl/sycl.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/sycl_queue.hpp"
17#include "strata/kernels/dflash2.hpp"
18#include "strata/kernels/dp4a.hpp"
19
20#include <cfloat>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <stdexcept>
25#include <string>
26
27namespace strata::kernels {
28namespace {
29
30constexpr int HD = kDf2Hd;
31#ifndef DF2_ATTN_CHUNK_AUTO
32#define DF2_ATTN_CHUNK_AUTO 64
33#endif
34#ifndef DF2_ATTN_AUTO
35#define DF2_ATTN_AUTO 2
36#endif
37int g_gemm_variant = 0;   // bench only (df2_gemm_variant)
38int g_attn_chunk = 0;     // bench only (df2_attention_chunk)
39int g_attn_variant = 0;   // 0: STRATA_DF2_ATTN or the default; 1: the CUDA file kernel (128 work-items); 2: 256 work-items, O[2][8]
40
41#define DF2_SG32 [[sycl::reqd_sub_group_size(32)]]
42#define DF2_SG16 [[sycl::reqd_sub_group_size(16)]]
43
44using sycl::nd_item;
45inline float bf16f(uint16_t h) { return sycl::bit_cast<float>((uint32_t) h << 16); }
46inline float xorf(const sycl::sub_group& sg, float v, int o) { return sycl::permute_group_by_xor(sg, v, (unsigned) o); }
47inline int xori(const sycl::sub_group& sg, int v, int o) { return sycl::permute_group_by_xor(sg, v, (unsigned) o); }
48inline void bar(const nd_item<1>& it) { sycl::group_barrier(it.get_group()); }
49inline void bar(const nd_item<2>& it) { sycl::group_barrier(it.get_group()); }
50
51// one 32-block of one row to the planar activation layout (a sub-group: lane = element)
52inline void quant_block(const sycl::sub_group& sg, float v, int blk, int col, int K, int8_t* xq, float* xd) {
53    const int lane = (int) sg.get_local_linear_id();
54    float amax = sycl::fabs(v);
55    for (int o = 16; o > 0; o >>= 1) amax = sycl::fmax(amax, xorf(sg, amax, o));
56    const float d = amax / 127.0f;
57    const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
58    const int q = (int) sycl::rint(v * inv);
59    xq[(size_t) col * K + blk * 32 + lane] = (int8_t) q;
60    if (lane == 0) xd[(size_t) col * (K / 32) + blk] = d;
61}
62
63// ---- the grouped dynamic 2-tap convolution over the block's rows
64void conv_launch(sycl::queue* q, const float* x, const float* dyn, int dyn_stride, const float* base, const float* resid, float* out, int rows, int H, int group) {
65    const int n = rows * H;
66    q->parallel_for(sycl::nd_range<1>((size_t) ((n + 255) / 256) * 256, 256), [=](nd_item<1> it) {
67        const int i = (int) it.get_global_id(0);
68        if (i >= n) return;
69        const int b = i / H, c = i % H;
70        const int groups = H / group;
71        float acc = 0.0f;
72        #pragma unroll
73        for (int o = 0; o < 2; ++o) {
74            if (b - o < 0) continue;
75            const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
76            acc = sycl::fma(k, x[(size_t) (b - o) * H + c], acc);
77        }
78        out[i] = resid ? resid[i] + acc : acc;
79    });
80}
81
82inline void rope_cs(double inv, int32_t pos, float& c, float& s) {
83    double ang = (double) pos * inv;
84    const double two_pi = 6.283185307179586476925286766559;
85    ang -= two_pi * sycl::rint(ang / two_pi);   // [-pi, pi]
86    s = sycl::sin((float) ang);
87    c = sycl::cos((float) ang);
88}
89
90// ---- norm + rope of one (row, head), 128 work-items: out = rope(rmsnorm(in) * gamma)
91inline float head_norm(const nd_item<2>& it, const sycl::local_accessor<float, 1>& red, float x, float eps) {
92    const sycl::sub_group sg = it.get_sub_group();
93    const int d = (int) it.get_local_id(1);
94    float ss = x * x;
95    for (int o = 16; o > 0; o >>= 1) ss += xorf(sg, ss, o);
96    if ((d & 31) == 0) red[d >> 5] = ss;
97    bar(it);
98    const float tot = red[0] + red[1] + red[2] + red[3];
99    return tot;
100}
101
102}  // namespace
103
104void df2_conv(const float* x, const float* dyn, int dyn_stride, const float* base, const float* resid, float* out, int rows, int H, int group, void* stream) {
105    conv_launch(strata::q_of(stream), x, dyn, dyn_stride, base, resid, out, rows, H, group);
106}
107
108void df2_rope_inv(float theta, double* inv, void* stream) {
109    strata::q_of(stream)->parallel_for(sycl::nd_range<1>(64, 64), [=](nd_item<1> it) {
110        const int i = (int) it.get_local_id(0);
111        inv[i] = sycl::pow((double) theta, -(double) (2 * i) / (double) HD);
112    });
113}
114
115void df2_rope_table(const int32_t* pos, int rows, float theta, float* table, void* stream) {
116    strata::q_of(stream)->parallel_for(sycl::nd_range<1>((size_t) rows * 64, 64), [=](nd_item<1> it) {
117        const int r = (int) it.get_group(0), i = (int) it.get_local_id(0);
118        const double inv = sycl::pow((double) theta, -(double) (2 * i) / (double) HD);
119        float c, s;
120        rope_cs(inv, pos[r], c, s);
121        table[(r * 2 + 0) * 64 + i] = c;
122        table[(r * 2 + 1) * 64 + i] = s;
123    });
124}
125
126void df2_rope_table_inv(const int32_t* pos, int rows, const double* inv_tab, float* table, void* stream) {
127    strata::q_of(stream)->parallel_for(sycl::nd_range<1>((size_t) rows * 64, 64), [=](nd_item<1> it) {
128        const int r = (int) it.get_group(0), i = (int) it.get_local_id(0);
129        float c, s;
130        rope_cs(inv_tab[i], pos[r], c, s);
131        table[(r * 2 + 0) * 64 + i] = c;
132        table[(r * 2 + 1) * 64 + i] = s;
133    });
134}
135
136void df2_rope_table_cpu(const int32_t* pos, int rows, float theta, float* table) {
137    const double two_pi = 6.283185307179586476925286766559;
138    for (int i = 0; i < 64; ++i) {
139        const double inv = std::pow((double) theta, -(double) (2 * i) / (double) HD);
140        for (int r = 0; r < rows; ++r) {
141            double ang = (double) pos[r] * inv;
142            ang -= two_pi * std::nearbyint(ang / two_pi);   // [-pi, pi]
143            table[(r * 2 + 0) * 64 + i] = (float) std::cos((float) ang);
144            table[(r * 2 + 1) * 64 + i] = (float) std::sin((float) ang);
145        }
146    }
147}
148
149void df2_norm_rope(const float* in, int in_stride, const float* gamma, const int32_t* pos, const float* rope_table, float* out, int slot_mod, int rows, int heads,
150                   float eps, void* stream) {
151    sycl::queue* q = strata::q_of(stream);
152    q->submit([&](sycl::handler& h) {
153        sycl::local_accessor<float, 1> red(4, h), y(HD, h);
154        h.parallel_for(sycl::nd_range<2>({(size_t) heads, (size_t) rows * HD}, {1, HD}), [=](nd_item<2> it) DF2_SG32 {
155            const int hh = (int) it.get_group(0), r = (int) it.get_group(1), d = (int) it.get_local_id(1);
156            const float x = in[(size_t) r * in_stride + hh * HD + d];
157            const float tot = head_norm(it, red, x, eps);
158            const float v = x * sycl::rsqrt(tot / (float) HD + eps) * gamma[d];
159            float res = v;
160            if (rope_table != nullptr) {
161                y[d] = v;
162                bar(it);
163                const int i = d & 63;
164                const float c = rope_table[(r * 2 + 0) * 64 + i], s = rope_table[(r * 2 + 1) * 64 + i];
165                res = d < 64 ? v * c - y[d + 64] * s : v * c + y[d - 64] * s;
166            }
167            const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r;
168            out[slot_mod > 0 ? ((size_t) hh * slot_mod + slot) * HD + d : ((size_t) slot * heads + hh) * HD + d] = res;
169        });
170    });
171}
172
173void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod, int rows, int cols, void* stream) {
174    const int n = rows * cols;
175    strata::q_of(stream)->parallel_for(sycl::nd_range<1>((size_t) ((n + 255) / 256) * 256, 256), [=](nd_item<1> it) {
176        const int i = (int) it.get_global_id(0);
177        if (i >= n) return;
178        const int r = i / cols, c = i % cols;
179        const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r;
180        out[slot_mod > 0 ? ((size_t) (c / HD) * slot_mod + slot) * HD + c % HD : (size_t) slot * cols + c] = in[i];
181    });
182}
183
184// ---- attention.  grid (8 K/V heads, kDf2MaxChunks), 128 work-items.  The 32 queries (4 heads x 8 rows) of a K/V head share each key tile;
185// S = Q K^T in 4 x 4 register tiles (64 work-items), the online softmax per query, O += P V in 4 x 8 register tiles (128 work-items).
186namespace {
187constexpr int AS4 = 33;   // local row stride of the Q / K / V tiles in float4 (132 floats: conflict-free for the 4 x 4 tiles)
188constexpr int PS4 = 9;    // stride of the transposed probabilities P[key][query] in float4 (36 floats)
189}
190
191void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, int ring_slots,
192                   int window, float* part, void* xq, float* xd, void* stream, const int64_t* tag, const int32_t* epoch_ptr) {
193    sycl::queue* qu = strata::q_of(stream);
194    static const int env_v = [] { const char* e = std::getenv("STRATA_DF2_ATTN"); return e ? std::atoi(e) : 0; }();
195    const int av = g_attn_variant != 0 ? g_attn_variant : env_v != 0 ? env_v : DF2_ATTN_AUTO;
196    static const int env_ck = [] { const char* e = std::getenv("STRATA_DF2_ATTN_CHUNK"); return e ? std::atoi(e) : 0; }();
197    const int CK = g_attn_chunk != 0 ? g_attn_chunk : env_ck == 128 ? 128 : DF2_ATTN_CHUNK_AUTO;   // keys per work-group: 64 (33 chunks) or 128 (17)
198    const int nch = CK == 128 ? kDf2MaxChunks : kDf2PartChunks;
199    if (av == 2) {
200        qu->submit([&](sycl::handler& h) {
201            sycl::local_accessor<sycl::float4, 1> Qs(32 * AS4, h), Ks(32 * AS4, h), Ps(32 * PS4, h);
202            sycl::local_accessor<float, 1> Sc(32 * 33, h), m_s(32, h), l_s(32, h), corr_s(32, h);
203            sycl::local_accessor<unsigned char, 1> kvalid(32, h);
204            h.parallel_for(sycl::nd_range<2>({(size_t) nch, (size_t) kDf2Kv * 256}, {1, 256}), [=](nd_item<2> it) DF2_SG16 {
205                const sycl::sub_group sg = it.get_sub_group();
206                const int chunk = (int) it.get_group(0), kvh = (int) it.get_group(1), tid = (int) it.get_local_id(1);
207                float* Psf = reinterpret_cast<float*>(&Ps[0]);
208                const int s = *anchor_pos;
209                const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0;
210                const int nctx = s - lo;
211                const int nkeys = nctx + kDf2Rows;
212                const int k_begin = chunk * CK;
213                const int64_t ep = tag != nullptr ? ((int64_t) *epoch_ptr << 32) : 0;
214                float* const pbase = part + (((size_t) chunk * kDf2Kv + kvh) * 32) * 130;
215                if (k_begin >= nkeys) {
216                    for (int i = tid; i < 32 * 130; i += 256) pbase[i] = (i % 130 == 0) ? -INFINITY : 0.0f;
217                    return;
218                }
219                const float scale = sycl::rsqrt((float) HD);
220#pragma unroll
221                for (int u = 0; u < 4; ++u) {   // Q: 32 queries x 128, float4
222                    const int i = tid + u * 256;
223                    const int a = i / (HD / 4), d4 = i % (HD / 4);
224                    const int row = a >> 2, g = a & 3;
225                    sycl::float4 v = *reinterpret_cast<const sycl::float4*>(q + ((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d4 * 4);
226                    Qs[a * AS4 + d4] = v * scale;
227                }
228                if (tid < 32) { m_s[tid] = -INFINITY; l_s[tid] = 0.0f; }
229                float O[2][8];
230#pragma unroll
231                for (int i = 0; i < 2; ++i)
232#pragma unroll
233                    for (int j = 0; j < 8; ++j) O[i][j] = 0.0f;
234                const int qg_pv = tid >> 4, dg_pv = tid & 15;   // PV: queries qg*2, qg*2+1, dims dg*8 .. +7
235                const int qg = tid >> 4, kg = tid & 15;         // S: queries qg*2 .. +1, keys kg*2 .. +1
236                const int k_end = sycl::min(k_begin + CK, nkeys);
237                auto load_tile = [&](int k0, const float* ring, const float* blk) {
238#pragma unroll
239                    for (int u = 0; u < 4; ++u) {
240                        const int i = tid + u * 256, t = i / (HD / 4), d4 = i % (HD / 4), k = k0 + t;
241                        sycl::float4 v(0.f, 0.f, 0.f, 0.f);
242                        if (k < nctx) v = *reinterpret_cast<const sycl::float4*>(ring + ((size_t) kvh * ring_slots + (lo + k) % ring_slots) * HD + d4 * 4);
243                        else if (k < nkeys) v = *reinterpret_cast<const sycl::float4*>(blk + ((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d4 * 4);
244                        Ks[t * AS4 + d4] = v;
245                    }
246                };
247                for (int k0 = k_begin; k0 < k_end; k0 += 32) {
248                    bar(it);
249                    load_tile(k0, kring, kblk);
250                    if (tid < 32) {
251                        const int k = k0 + tid;
252                        kvalid[tid] = (tag == nullptr || k >= nctx || k >= nkeys) ? 1 : (tag[(lo + k) % ring_slots] == (ep | (int64_t) (lo + k)) ? 1 : 0);
253                    }
254                    bar(it);
255                    {   // S tile: 2 queries x 2 keys per work-item
256                        float acc[2][2];
257#pragma unroll
258                        for (int i = 0; i < 2; ++i)
259#pragma unroll
260                            for (int j = 0; j < 2; ++j) acc[i][j] = 0.0f;
261#pragma unroll 4
262                        for (int d4 = 0; d4 < HD / 4; ++d4) {
263                            sycl::float4 qv[2], kv[2];
264#pragma unroll
265                            for (int i = 0; i < 2; ++i) qv[i] = Qs[(qg * 2 + i) * AS4 + d4];
266#pragma unroll
267                            for (int j = 0; j < 2; ++j) kv[j] = Ks[(kg * 2 + j) * AS4 + d4];
268#pragma unroll
269                            for (int i = 0; i < 2; ++i)
270#pragma unroll
271                                for (int j = 0; j < 2; ++j) acc[i][j] += qv[i].x() * kv[j].x() + qv[i].y() * kv[j].y() + qv[i].z() * kv[j].z() + qv[i].w() * kv[j].w();
272                        }
273#pragma unroll
274                        for (int i = 0; i < 2; ++i)
275#pragma unroll
276                            for (int j = 0; j < 2; ++j) {
277                                const int qi = qg * 2 + i, t = kg * 2 + j, k = k0 + t, row = qi >> 2;
278                                bool ok = k < nkeys;
279                                if (ok && k < nctx) ok = (lo + k) > (s + row - window) && kvalid[t];
280                                Sc[qi * 33 + t] = ok ? acc[i][j] : -INFINITY;
281                            }
282                    }
283                    bar(it);
284                    {   // online softmax: query = tid / 8, 4 keys each, 8 lanes per query
285                        const int qi = tid >> 3, sub = tid & 7;
286                        float v[4], tmax = -INFINITY;
287#pragma unroll
288                        for (int u = 0; u < 4; ++u) { v[u] = Sc[qi * 33 + sub * 4 + u]; tmax = sycl::fmax(tmax, v[u]); }
289                        tmax = sycl::fmax(tmax, xorf(sg, tmax, 1));
290                        tmax = sycl::fmax(tmax, xorf(sg, tmax, 2));
291                        tmax = sycl::fmax(tmax, xorf(sg, tmax, 4));
292                        const float m_old = m_s[qi];
293                        const float mn = sycl::fmax(m_old, tmax);
294                        const float corr = (m_old == -INFINITY) ? 0.0f : sycl::exp(m_old - mn);
295                        float psum = 0.0f;
296#pragma unroll
297                        for (int u = 0; u < 4; ++u) {
298                            const float p = v[u] == -INFINITY ? 0.0f : sycl::exp(v[u] - mn);
299                            Psf[(sub * 4 + u) * (PS4 * 4) + qi] = p;
300                            psum += p;
301                        }
302                        psum += xorf(sg, psum, 1);
303                        psum += xorf(sg, psum, 2);
304                        psum += xorf(sg, psum, 4);
305                        if (sub == 0) { l_s[qi] = l_s[qi] * corr + psum; m_s[qi] = mn; corr_s[qi] = corr; }
306                    }
307                    bar(it);
308                    load_tile(k0, vring, vblk);
309                    bar(it);
310                    {
311                        const float cr[2] = {corr_s[qg_pv * 2], corr_s[qg_pv * 2 + 1]};
312#pragma unroll
313                        for (int i = 0; i < 2; ++i)
314#pragma unroll
315                            for (int j = 0; j < 8; ++j) O[i][j] *= cr[i];
316#pragma unroll 4
317                        for (int t = 0; t < 32; ++t) {
318                            const float p0 = Psf[t * (PS4 * 4) + qg_pv * 2], p1 = Psf[t * (PS4 * 4) + qg_pv * 2 + 1];
319                            const sycl::float4 va = Ks[t * AS4 + dg_pv * 2], vb = Ks[t * AS4 + dg_pv * 2 + 1];
320                            const float vv[8] = {va.x(), va.y(), va.z(), va.w(), vb.x(), vb.y(), vb.z(), vb.w()};
321#pragma unroll
322                            for (int j = 0; j < 8; ++j) { O[0][j] = sycl::fma(p0, vv[j], O[0][j]); O[1][j] = sycl::fma(p1, vv[j], O[1][j]); }
323                        }
324                    }
325                }
326                bar(it);
327                if (tid < 32) { pbase[tid * 130] = m_s[tid]; pbase[tid * 130 + 1] = l_s[tid]; }
328#pragma unroll
329                for (int i = 0; i < 2; ++i) {
330                    float* o = pbase + (size_t) (qg_pv * 2 + i) * 130 + 2 + dg_pv * 8;
331#pragma unroll
332                    for (int j = 0; j < 8; ++j) o[j] = O[i][j];
333                }
334            });
335        });
336    } else
337    qu->submit([&](sycl::handler& h) {
338        sycl::local_accessor<sycl::float4, 1> Qs(32 * AS4, h), Ks(32 * AS4, h), Ps(32 * PS4, h);
339        sycl::local_accessor<float, 1> Sc(32 * 33, h), m_s(32, h), l_s(32, h), corr_s(32, h);
340        sycl::local_accessor<unsigned char, 1> kvalid(32, h);
341        h.parallel_for(sycl::nd_range<2>({(size_t) nch, (size_t) kDf2Kv * 128}, {1, 128}), [=](nd_item<2> it) DF2_SG16 {
342            const sycl::sub_group sg = it.get_sub_group();
343            const int chunk = (int) it.get_group(0), kvh = (int) it.get_group(1), tid = (int) it.get_local_id(1);
344            float* Psf = reinterpret_cast<float*>(&Ps[0]);
345            const int s = *anchor_pos;
346            const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0;
347            const int nctx = s - lo;
348            const int nkeys = nctx + kDf2Rows;
349            const int k_begin = chunk * CK;
350            const int64_t ep = tag != nullptr ? ((int64_t) *epoch_ptr << 32) : 0;
351            float* const pbase = part + (((size_t) chunk * kDf2Kv + kvh) * 32) * 130;
352            if (k_begin >= nkeys) {
353                for (int i = tid; i < 32 * 130; i += 128) pbase[i] = (i % 130 == 0) ? -INFINITY : 0.0f;
354                return;
355            }
356            const float scale = sycl::rsqrt((float) HD);
357            for (int i = tid; i < 32 * HD / 4; i += 128) {   // Q: 32 queries x 128, float4
358                const int a = i / (HD / 4), d4 = i % (HD / 4);
359                const int row = a >> 2, g = a & 3;
360                sycl::float4 v = *reinterpret_cast<const sycl::float4*>(q + ((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d4 * 4);
361                Qs[a * AS4 + d4] = v * scale;
362            }
363            if (tid < 32) { m_s[tid] = -INFINITY; l_s[tid] = 0.0f; }
364            float O[4][8];
365            #pragma unroll
366            for (int i = 0; i < 4; ++i)
367                #pragma unroll
368                for (int j = 0; j < 8; ++j) O[i][j] = 0.0f;
369            const int qg_pv = tid >> 4, dg_pv = tid & 15;   // PV: queries qg*4 .. +3, dims dg*8 .. +7
370            const int k_end = sycl::min(k_begin + CK, nkeys);
371            // a tile is 32 keys x 128 dims = 1024 float4: eight per work-item
372            auto load_tile = [&](int k0, const float* ring, const float* blk) {
373                #pragma unroll
374                for (int u = 0; u < 8; ++u) {
375                    const int i = tid + u * 128, t = i / (HD / 4), d4 = i % (HD / 4), k = k0 + t;
376                    sycl::float4 v(0.f, 0.f, 0.f, 0.f);
377                    if (k < nctx) v = *reinterpret_cast<const sycl::float4*>(ring + ((size_t) kvh * ring_slots + (lo + k) % ring_slots) * HD + d4 * 4);
378                    else if (k < nkeys) v = *reinterpret_cast<const sycl::float4*>(blk + ((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d4 * 4);
379                    Ks[t * AS4 + d4] = v;
380                }
381            };
382            for (int k0 = k_begin; k0 < k_end; k0 += 32) {
383                bar(it);   // Ks free (the last tile's V reads done); Qs / m_s written on the first pass
384                load_tile(k0, kring, kblk);
385                if (tid < 32) {
386                    const int k = k0 + tid;
387                    kvalid[tid] = (tag == nullptr || k >= nctx || k >= nkeys) ? 1 : (tag[(lo + k) % ring_slots] == (ep | (int64_t) (lo + k)) ? 1 : 0);
388                }
389                bar(it);
390                if (tid < 64) {   // S tile: 4 queries x 4 keys per work-item
391                    const int qg = tid >> 3, kg = tid & 7;
392                    float acc[4][4];
393                    #pragma unroll
394                    for (int i = 0; i < 4; ++i)
395                        #pragma unroll
396                        for (int j = 0; j < 4; ++j) acc[i][j] = 0.0f;
397                    #pragma unroll 4
398                    for (int d4 = 0; d4 < HD / 4; ++d4) {
399                        sycl::float4 qv[4], kv[4];
400                        #pragma unroll
401                        for (int i = 0; i < 4; ++i) qv[i] = Qs[(qg * 4 + i) * AS4 + d4];
402                        #pragma unroll
403                        for (int j = 0; j < 4; ++j) kv[j] = Ks[(kg * 4 + j) * AS4 + d4];
404                        #pragma unroll
405                        for (int i = 0; i < 4; ++i)
406                            #pragma unroll
407                            for (int j = 0; j < 4; ++j) acc[i][j] += qv[i].x() * kv[j].x() + qv[i].y() * kv[j].y() + qv[i].z() * kv[j].z() + qv[i].w() * kv[j].w();
408                    }
409                    #pragma unroll
410                    for (int i = 0; i < 4; ++i)
411                        #pragma unroll
412                        for (int j = 0; j < 4; ++j) {
413                            const int qi = qg * 4 + i, t = kg * 4 + j, k = k0 + t, row = qi >> 2;
414                            bool ok = k < nkeys;
415                            if (ok && k < nctx) ok = (lo + k) > (s + row - window) && kvalid[t];   // s + row - j < window, and the slot holds that row
416                            Sc[qi * 33 + t] = ok ? acc[i][j] : -INFINITY;
417                        }
418                }
419                bar(it);
420                {   // online softmax: query = tid / 4, 8 keys each, 4 lanes per query
421                    const int qi = tid >> 2, sub = tid & 3;
422                    float v[8], tmax = -INFINITY;
423                    #pragma unroll
424                    for (int u = 0; u < 8; ++u) { v[u] = Sc[qi * 33 + sub * 8 + u]; tmax = sycl::fmax(tmax, v[u]); }
425                    tmax = sycl::fmax(tmax, xorf(sg, tmax, 1));
426                    tmax = sycl::fmax(tmax, xorf(sg, tmax, 2));
427                    const float m_old = m_s[qi];
428                    const float mn = sycl::fmax(m_old, tmax);
429                    const float corr = (m_old == -INFINITY) ? 0.0f : sycl::exp(m_old - mn);
430                    float psum = 0.0f;
431                    #pragma unroll
432                    for (int u = 0; u < 8; ++u) {
433                        const float p = v[u] == -INFINITY ? 0.0f : sycl::exp(v[u] - mn);
434                        Psf[(sub * 8 + u) * (PS4 * 4) + qi] = p;
435                        psum += p;
436                    }
437                    psum += xorf(sg, psum, 1);
438                    psum += xorf(sg, psum, 2);
439                    if (sub == 0) { l_s[qi] = l_s[qi] * corr + psum; m_s[qi] = mn; corr_s[qi] = corr; }
440                }
441                bar(it);   // Ps, corr_s complete; every read of Ks (the S tile) done
442                load_tile(k0, vring, vblk);
443                bar(it);
444                {
445                    const float cr[4] = {corr_s[qg_pv * 4], corr_s[qg_pv * 4 + 1], corr_s[qg_pv * 4 + 2], corr_s[qg_pv * 4 + 3]};
446                    #pragma unroll
447                    for (int i = 0; i < 4; ++i)
448                        #pragma unroll
449                        for (int j = 0; j < 8; ++j) O[i][j] *= cr[i];
450                    #pragma unroll 4
451                    for (int t = 0; t < 32; ++t) {
452                        const sycl::float4 p4 = Ps[t * PS4 + qg_pv];
453                        const sycl::float4 va = Ks[t * AS4 + dg_pv * 2], vb = Ks[t * AS4 + dg_pv * 2 + 1];
454                        const float pv[4] = {p4.x(), p4.y(), p4.z(), p4.w()};
455                        const float vv[8] = {va.x(), va.y(), va.z(), va.w(), vb.x(), vb.y(), vb.z(), vb.w()};
456                        #pragma unroll
457                        for (int i = 0; i < 4; ++i)
458                            #pragma unroll
459                            for (int j = 0; j < 8; ++j) O[i][j] = sycl::fma(pv[i], vv[j], O[i][j]);
460                    }
461                }
462            }
463            bar(it);
464            if (tid < 32) { pbase[tid * 130] = m_s[tid]; pbase[tid * 130 + 1] = l_s[tid]; }
465            #pragma unroll
466            for (int i = 0; i < 4; ++i) {
467                float* o = pbase + (size_t) (qg_pv * 4 + i) * 130 + 2 + dg_pv * 8;
468                #pragma unroll
469                for (int j = 0; j < 8; ++j) o[j] = O[i][j];
470            }
471        });
472    });
473    qu->parallel_for(sycl::nd_range<1>((size_t) kDf2Kv * 32 * HD, HD), [=](nd_item<1> it) DF2_SG32 {
474        const sycl::sub_group sg = it.get_sub_group();
475        const int a = (int) it.get_group(0);   // kvh * 32 + qi
476        const int kvh = a >> 5, qi = a & 31, d = (int) it.get_local_id(0);
477        float M = -INFINITY;
478        for (int c = 0; c < nch; ++c) M = sycl::fmax(M, part[(((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130]);
479        float L = 0.0f, o = 0.0f;
480        for (int c = 0; c < nch; ++c) {
481            const float* p = part + (((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130;
482            const float mc = p[0];
483            const float w = (mc == -INFINITY) ? 0.0f : sycl::exp(mc - M);
484            L += p[1] * w;
485            o = sycl::fma(p[2 + d], w, o);
486        }
487        const int row = qi >> 2, g = qi & 3;
488        // the output row `row`, head kvh * 4 + g, dims d: quant block (kvh * 4 + g) * 4 + d / 32 of the 4096-wide row
489        quant_block(sg, L > 0.0f ? o / L : 0.0f, (kvh * kDf2Gqa + g) * (HD / 32) + (d >> 5), row, 32 * HD, static_cast<int8_t*>(xq), xd);
490    });
491}
492
493// ---- Q4_0 GEMM for up to 8 activation columns (the drafter's matrices); NC = the columns that are computed (DF-03)
494//
495// Weights are TILED (df2_q4_tile makes them from ggml Q4_0 blocks): a group of 8 rows is one unit; per 512 values of the reduction axis (a "step", 16
496// Q4_0 blocks) the group stores the 8 rows' nibbles one after the other (2 KB), a lane (block * 2 + half) takes 8 bytes = 16 values as two words.  Word 0
497// holds values 0-3 in its four low nibbles and 4-7 in its four high nibbles, word 1 holds 8-11 and 12-15, so (w & 0x0F0F0F0F) and ((w >> 4) & 0x0F0F0F0F)
498// are the int8 words dp4a wants, as unsigned q = 0..15 (value = (q - 8) * d).  sum((q - 8) x) = sum(q x) - 8 sum(x).  The fp16 block scales follow the
499// nibble plane (n_out * n_in / 2 bytes) in the same tile order.  Activations: xq (int8 [col][n_in]) and xd (float [col][n_in / 32]).
500namespace {
501struct Df2Seg { const int8_t* q; const sycl::half* d; float* y; int n_out; int row0; };
502struct Df2Segs { Df2Seg s[3]; int n; };
503
504inline Df2Seg df2_pick(const Df2Segs& segs, int row_g) {
505    Df2Seg sg = segs.s[0];
506    if (segs.n > 1 && row_g >= segs.s[1].row0) sg = segs.s[1];
507    if (segs.n > 2 && row_g >= segs.s[2].row0) sg = segs.s[2];
508    return sg;
509}
510
511template <int WARPS, int R, int UNR, int NC>
512void gemm4_launch(sycl::queue* q, const Df2Segs& segs, const int8_t* xq, const float* xd, int n_in, int rows) {
513    constexpr int SUBS = 8 / R;
514    const size_t groups = (size_t) (rows / 8) * SUBS / WARPS;
515    q->parallel_for(sycl::nd_range<1>(groups * WARPS * 32, WARPS * 32), [=](nd_item<1> it) DF2_SG32 {
516        const sycl::sub_group sg = it.get_sub_group();
517        const int warp = (int) (it.get_local_id(0) >> 5), lane = (int) sg.get_local_linear_id();
518        const int wi = (int) it.get_group(0) * WARPS + warp;
519        const int row_g = (wi / SUBS) * 8, sub = wi % SUBS;
520        const Df2Seg sgm = df2_pick(segs, row_g);
521        const int row0 = row_g - sgm.row0;
522        const int nb = n_in / 32, steps = nb / 16;
523        const sycl::uint2* wq = reinterpret_cast<const sycl::uint2*>(sgm.q + (size_t) row0 * (n_in / 2)) + lane + sub * R * 32;
524        const sycl::half* wd = sgm.d + (size_t) row0 * nb + (lane >> 1) + sub * R * 16;
525        const sycl::int4* xv = reinterpret_cast<const sycl::int4*>(xq) + lane;
526        float acc[R][NC];
527        #pragma unroll
528        for (int r = 0; r < R; ++r)
529            #pragma unroll
530            for (int c = 0; c < NC; ++c) acc[r][c] = 0.0f;
531#pragma unroll UNR
532        for (int st = 0; st < steps; ++st) {
533            int w[R][4];
534            float dw[R];
535            #pragma unroll
536            for (int r = 0; r < R; ++r) {
537                const sycl::uint2 raw = wq[(size_t) st * 256 + r * 32];
538                // bytewise (q - 8) for q = 0..15: ((q | 0x80) - 8) ^ 0x80, no borrow across bytes; sum((q - 8) x) is the integer the CUDA kernel gets as sum(q x) - 8 sum(x)
539                w[r][0] = (int) ((((raw.x() & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
540                w[r][1] = (int) (((((raw.x() >> 4) & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
541                w[r][2] = (int) ((((raw.y() & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
542                w[r][3] = (int) (((((raw.y() >> 4) & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
543                dw[r] = (float) wd[(size_t) st * 128 + r * 16];
544            }
545            float xs[NC];
546            #pragma unroll
547            for (int c = 0; c < NC; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
548            #pragma unroll
549            for (int c = 0; c < NC; ++c) {
550                const sycl::int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
551                #pragma unroll
552                for (int r = 0; r < R; ++r) {
553                    int isum = STRATA_DP4A(w[r][0], x.x(), 0);
554                    isum = STRATA_DP4A(w[r][1], x.y(), isum);
555                    isum = STRATA_DP4A(w[r][2], x.z(), isum);
556                    isum = STRATA_DP4A(w[r][3], x.w(), isum);
557                    acc[r][c] = sycl::fma(dw[r] * xs[c], (float) isum, acc[r][c]);
558                }
559            }
560        }
561        #pragma unroll
562        for (int r = 0; r < R; ++r)
563            #pragma unroll
564            for (int c = 0; c < NC; ++c) {
565                float v = acc[r][c];
566                v += xorf(sg, v, 16);
567                v += xorf(sg, v, 8);
568                v += xorf(sg, v, 4);
569                v += xorf(sg, v, 2);
570                v += xorf(sg, v, 1);
571                if (lane == 0) sgm.y[(size_t) c * sgm.n_out + row0 + sub * R + r] = v;
572            }
573    });
574}
575
576template <int WARPS, int R, int UNR>
577void gemm4_nc(sycl::queue* q, const Df2Segs& segs, const int8_t* xq, const float* xd, int n_in, int rows, int ncols) {
578    switch (ncols) {
579        case 1: gemm4_launch<WARPS, R, UNR, 1>(q, segs, xq, xd, n_in, rows); break;
580        case 2: gemm4_launch<WARPS, R, UNR, 2>(q, segs, xq, xd, n_in, rows); break;
581        case 3: gemm4_launch<WARPS, R, UNR, 3>(q, segs, xq, xd, n_in, rows); break;
582        case 4: gemm4_launch<WARPS, R, UNR, 4>(q, segs, xq, xd, n_in, rows); break;
583        case 5: gemm4_launch<WARPS, R, UNR, 5>(q, segs, xq, xd, n_in, rows); break;
584        case 6: gemm4_launch<WARPS, R, UNR, 6>(q, segs, xq, xd, n_in, rows); break;
585        case 7: gemm4_launch<WARPS, R, UNR, 7>(q, segs, xq, xd, n_in, rows); break;
586        default: gemm4_launch<WARPS, R, UNR, 8>(q, segs, xq, xd, n_in, rows); break;
587    }
588}
589
590
591// The same GEMM on sub-groups of 16 (SIMD16: a variable takes 2 GRFs, not 4, so R rows a lane fit without spilling): the 32 lanes of the CUDA warp are two
592// sub-groups, `half` 0 for lanes 0-15 and `half` 1 for lanes 16-31 of the same row group, each lane doing the work of its virtual lane l = half * 16 + l16 exactly
593// (same steps, same fma order).  The xor-16 stage of the shuffle tree is acc[l] + acc[l + 16], an add that commutes, so half 1 hands its sums over through local
594// memory and half 0 finishes the tree (8, 4, 2, 1): bitwise the result of gemm4_launch.
595template <int R, int NC, int PAIRS, int UNR>
596void gemm4p_launch(sycl::queue* q, const Df2Segs& segs, const int8_t* xq, const float* xd, int n_in, int rows) {
597    constexpr int SUBS = 8 / R;
598    const size_t pairs = (size_t) (rows / 8) * SUBS;
599    q->submit([&](sycl::handler& hd) {
600        sycl::local_accessor<float, 1> slm((size_t) PAIRS * R * NC * 16, hd);
601        hd.parallel_for(sycl::nd_range<1>((pairs / PAIRS) * PAIRS * 32, PAIRS * 32), [=](nd_item<1> it) DF2_SG16 {
602            const sycl::sub_group sg = it.get_sub_group();
603            const int l16 = (int) sg.get_local_linear_id();
604            const int sgi = (int) (it.get_local_id(0) >> 4);
605            const int pair = sgi >> 1, half = sgi & 1;
606            const int lane = half * 16 + l16;
607            const size_t gp = it.get_group(0) * PAIRS + pair;
608            const int row_g = (int) (gp / SUBS) * 8, sub = (int) (gp % SUBS);
609            const Df2Seg sgm = df2_pick(segs, row_g);
610            const int row0 = row_g - sgm.row0;
611            const int nb = n_in / 32, steps = nb / 16;
612            const sycl::uint2* wq = reinterpret_cast<const sycl::uint2*>(sgm.q + (size_t) row0 * (n_in / 2)) + lane + sub * R * 32;
613            const sycl::half* wd = sgm.d + (size_t) row0 * nb + (lane >> 1) + sub * R * 16;
614            const sycl::int4* xv = reinterpret_cast<const sycl::int4*>(xq) + lane;
615            float acc[R][NC];
616#pragma unroll
617            for (int r = 0; r < R; ++r)
618#pragma unroll
619                for (int c = 0; c < NC; ++c) acc[r][c] = 0.0f;
620#pragma unroll UNR
621            for (int st = 0; st < steps; ++st) {
622                int w[R][4];
623                float dw[R];
624#pragma unroll
625                for (int r = 0; r < R; ++r) {
626                    const sycl::uint2 raw = wq[(size_t) st * 256 + r * 32];
627                    w[r][0] = (int) ((((raw.x() & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
628                    w[r][1] = (int) (((((raw.x() >> 4) & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
629                    w[r][2] = (int) ((((raw.y() & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
630                    w[r][3] = (int) (((((raw.y() >> 4) & 0x0F0F0F0Fu) | 0x80808080u) - 0x08080808u) ^ 0x80808080u);
631                    dw[r] = (float) wd[(size_t) st * 128 + r * 16];
632                }
633                float xs[NC];
634#pragma unroll
635                for (int c = 0; c < NC; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
636#pragma unroll
637                for (int c = 0; c < NC; ++c) {
638                    const sycl::int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
639#pragma unroll
640                    for (int r = 0; r < R; ++r) {
641                        int isum = STRATA_DP4A(w[r][0], x.x(), 0);
642                        isum = STRATA_DP4A(w[r][1], x.y(), isum);
643                        isum = STRATA_DP4A(w[r][2], x.z(), isum);
644                        isum = STRATA_DP4A(w[r][3], x.w(), isum);
645                        acc[r][c] = sycl::fma(dw[r] * xs[c], (float) isum, acc[r][c]);
646                    }
647                }
648            }
649            if (half == 1) {
650#pragma unroll
651                for (int r = 0; r < R; ++r)
652#pragma unroll
653                    for (int c = 0; c < NC; ++c) slm[((pair * R + r) * NC + c) * 16 + l16] = acc[r][c];
654            }
655            sycl::group_barrier(it.get_group());
656            if (half == 0) {
657#pragma unroll
658                for (int r = 0; r < R; ++r)
659#pragma unroll
660                    for (int c = 0; c < NC; ++c) {
661                        float v = acc[r][c] + slm[((pair * R + r) * NC + c) * 16 + l16];   // the xor-16 stage
662                        v += xorf(sg, v, 8);
663                        v += xorf(sg, v, 4);
664                        v += xorf(sg, v, 2);
665                        v += xorf(sg, v, 1);
666                        if (l16 == 0) sgm.y[(size_t) c * sgm.n_out + row0 + sub * R + r] = v;
667                    }
668            }
669        });
670    });
671}
672
673template <int R, int PAIRS, int UNR>
674void gemm4p_nc(sycl::queue* q, const Df2Segs& segs, const int8_t* xq, const float* xd, int n_in, int rows, int ncols) {
675    switch (ncols) {
676        case 1: gemm4p_launch<R, 1, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
677        case 2: gemm4p_launch<R, 2, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
678        case 3: gemm4p_launch<R, 3, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
679        case 4: gemm4p_launch<R, 4, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
680        case 5: gemm4p_launch<R, 5, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
681        case 6: gemm4p_launch<R, 6, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
682        case 7: gemm4p_launch<R, 7, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
683        default: gemm4p_launch<R, 8, PAIRS, UNR>(q, segs, xq, xd, n_in, rows); break;
684    }
685}
686
687// ---- planar quantization / norm kernels
688void quant_rows_launch(sycl::queue* q, const float* x, int K, int ncols, int8_t* xq, float* xd) {
689    q->parallel_for(sycl::nd_range<2>({(size_t) ncols, (size_t) ((K / 32 + 7) / 8) * 256}, {1, 256}), [=](nd_item<2> it) DF2_SG32 {
690        const sycl::sub_group sg = it.get_sub_group();
691        const int col = (int) it.get_group(0), blk = (int) it.get_group(1) * 8 + (int) (it.get_local_id(1) >> 5), lane = (int) sg.get_local_linear_id();
692        if (blk * 32 >= K) return;
693        quant_block(sg, x[(size_t) col * K + blk * 32 + lane], blk, col, K, xq, xd);
694    });
695}
696}  // namespace
697
698#ifndef DF2_Q4_AUTO
699#define DF2_Q4_AUTO(rows) ((rows) <= 1024 ? 40 : 41)   // SIMD16 pair kernels (bitwise the same results): 2 rows a lane for the big matrices, 1 for the 640-row ones
700#endif
701
702void df2_gemm(const Df2Mat* mats, int n, const void* xq, const float* xd, int n_in, int ncols, void* stream) {
703    if (n < 1 || n > 3 || n_in % 512 != 0 || ncols < 1 || ncols > 8) throw std::invalid_argument("df2_gemm: unsupported shape");
704    Df2Segs segs;
705    int rows = 0;
706    for (int i = 0; i < n; ++i) {
707        if (mats[i].n_out % 16 != 0) throw std::invalid_argument("df2_gemm: n_out must be a multiple of 16");
708        if (!mats[i].q4) throw std::invalid_argument("df2_gemm: the SYCL drafter runs the Q4_0 pack only");
709        const int8_t* qw = static_cast<const int8_t*>(mats[i].w);
710        segs.s[i] = Df2Seg{qw, reinterpret_cast<const sycl::half*>(qw + (size_t) mats[i].n_out * n_in / 2), mats[i].y, mats[i].n_out, rows};
711        rows += mats[i].n_out;
712    }
713    segs.n = n;
714    const int8_t* xqp = static_cast<const int8_t*>(xq);
715    sycl::queue* q = strata::q_of(stream);
716    static const int env_v = [] { const char* e = std::getenv("STRATA_DF2_GEMM4"); return e ? std::atoi(e) : 0; }();
717    const int v = g_gemm_variant != 0 ? g_gemm_variant : env_v != 0 ? env_v : DF2_Q4_AUTO(rows);
718    switch (v) {   // the ids are the CUDA file's (W warps a block, R rows a warp)
719        case 10: gemm4_nc<4, 4, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
720        case 11: gemm4_nc<4, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
721        case 12: gemm4_nc<4, 1, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
722        case 24: gemm4_nc<1, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
723        case 25: gemm4_nc<1, 4, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
724        case 28: gemm4_nc<1, 1, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
725        case 34: gemm4_nc<2, 1, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
726        case 17: gemm4_nc<2, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
727        case 40: gemm4p_nc<1, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;   // sub-groups of 16, two per row group (R rows a lane, PAIRS pairs a work-group)
728        case 41: gemm4p_nc<2, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
729        case 42: gemm4p_nc<4, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
730        case 43: gemm4p_nc<8, 2, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;
731        default: gemm4_nc<1, 1, 2>(q, segs, xqp, xd, n_in, rows, ncols); break;   // 28
732    }
733}
734
735void df2_gemm_variant(int v) { g_gemm_variant = v; }
736void df2_attention_variant(int v) { g_attn_variant = v; }
737void df2_attention_chunk(int ck) { g_attn_chunk = ck; }
738
739void df2_quant_rows(const float* x, int K, int ncols, void* xq, float* xd, void* stream) {
740    quant_rows_launch(strata::q_of(stream), x, K, ncols, static_cast<int8_t*>(xq), xd);
741}
742
743// RMS norm of row `col` (N values) then the planar quantization of the normalized values; also writes them when xn != null.  One group of 256 per row.
744void df2_rms_quant(const float* h, const float* gamma, float* xn, int rows, int N, float eps, void* xq, float* xd, void* stream) {
745    sycl::queue* q = strata::q_of(stream);
746    int8_t* xqi = static_cast<int8_t*>(xq);
747    q->submit([&](sycl::handler& hd) {
748        sycl::local_accessor<float, 1> red(8, hd);
749        hd.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](nd_item<1> it) DF2_SG32 {
750            const sycl::sub_group sg = it.get_sub_group();
751            const int col = (int) it.get_group(0), tid = (int) it.get_local_id(0), warp = tid >> 5, lane = tid & 31;
752            float ss = 0.0f;
753            for (int i = tid; i < N; i += 256) { const float v = h[(size_t) col * N + i]; ss += v * v; }
754            for (int o = 16; o > 0; o >>= 1) ss += xorf(sg, ss, o);
755            if (lane == 0) red[warp] = ss;
756            bar(it);
757            float tot = 0.0f;
758            #pragma unroll
759            for (int w = 0; w < 8; ++w) tot += red[w];
760            const float scale = sycl::rsqrt(tot / (float) N + eps);
761            for (int blk = warp; blk * 32 < N; blk += 8) {
762                const int i = blk * 32 + lane;
763                const float v = h[(size_t) col * N + i] * scale * gamma[i];
764                if (xn) xn[(size_t) col * N + i] = v;
765                quant_block(sg, v, blk, col, N, xqi, xd);
766            }
767        });
768    });
769}
770
771// conv (as df2_conv, no residual) then the planar quantization: grid (ceil(H / 32 / 8), rows), 256 work-items
772void df2_conv_quant(const float* x, const float* dyn, int dyn_stride, const float* base, int rows, int H, int group, void* xq, float* xd, void* stream) {
773    int8_t* xqi = static_cast<int8_t*>(xq);
774    strata::q_of(stream)->parallel_for(sycl::nd_range<2>({(size_t) rows, (size_t) ((H / 32 + 7) / 8) * 256}, {1, 256}), [=](nd_item<2> it) DF2_SG32 {
775        const sycl::sub_group sg = it.get_sub_group();
776        const int b = (int) it.get_group(0), blk = (int) it.get_group(1) * 8 + (int) (it.get_local_id(1) >> 5), lane = (int) sg.get_local_linear_id();
777        if (blk * 32 >= H) return;
778        const int c = blk * 32 + lane, groups = H / group;
779        float acc = 0.0f;
780        #pragma unroll
781        for (int o = 0; o < 2; ++o) {
782            if (b - o < 0) continue;
783            const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
784            acc = sycl::fma(k, x[(size_t) (b - o) * H + c], acc);
785        }
786        quant_block(sg, acc, blk, b, H, xqi, xd);
787    });
788}
789
790// h += conv(x) (the finish convolution with its residual), then RMS norm of the new h with `gamma` -> xn (optional) and the planar quantization.
791// One group of 256 per row: a sub-group owns whole 32-blocks (80 of them for 2560, ten each), so the quantization needs no exchange.
792void df2_conv_rms_quant(const float* x, const float* dyn, int dyn_stride, const float* base, float* h, const float* gamma, float* xn, int rows, int H, int group,
793                        float eps, void* xq, float* xd, void* stream) {
794    constexpr int MAXJ = 12;   // H <= 3072 -> 96 blocks -> 12 per sub-group
795    if (H > 3072) throw std::invalid_argument("df2_conv_rms_quant: H too large");
796    sycl::queue* q = strata::q_of(stream);
797    int8_t* xqi = static_cast<int8_t*>(xq);
798    q->submit([&](sycl::handler& hd) {
799        sycl::local_accessor<float, 1> red(8, hd);
800        hd.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](nd_item<1> it) DF2_SG32 {
801            const sycl::sub_group sg = it.get_sub_group();
802            const int b = (int) it.get_group(0), tid = (int) it.get_local_id(0), warp = tid >> 5, lane = tid & 31;
803            const int groups = H / group, nb = H / 32;
804            float v[MAXJ];
805            float ss = 0.0f;
806            #pragma unroll
807            for (int j = 0; j < MAXJ; ++j) {
808                const int blk = warp + j * 8;
809                v[j] = 0.0f;
810                if (blk < nb) {
811                    const int c = blk * 32 + lane;
812                    float acc = 0.0f;
813                    #pragma unroll
814                    for (int o = 0; o < 2; ++o) {
815                        if (b - o < 0) continue;
816                        const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
817                        acc = sycl::fma(k, x[(size_t) (b - o) * H + c], acc);
818                    }
819                    v[j] = h[(size_t) b * H + c] + acc;
820                    h[(size_t) b * H + c] = v[j];
821                    ss += v[j] * v[j];
822                }
823            }
824            for (int o = 16; o > 0; o >>= 1) ss += xorf(sg, ss, o);
825            if (lane == 0) red[warp] = ss;
826            bar(it);
827            float tot = 0.0f;
828            #pragma unroll
829            for (int w = 0; w < 8; ++w) tot += red[w];
830            const float scale = sycl::rsqrt(tot / (float) H + eps);
831            #pragma unroll
832            for (int j = 0; j < MAXJ; ++j) {
833                const int blk = warp + j * 8;
834                if (blk < nb) {
835                    const int c = blk * 32 + lane;
836                    const float y = v[j] * scale * gamma[c];
837                    if (xn) xn[(size_t) b * H + c] = y;
838                    quant_block(sg, y, blk, b, H, xqi, xd);
839                }
840            }
841        });
842    });
843}
844
845// q and k of the block: per (row, head) RMS norm and rope; group y < q_heads is a q head (-> qo, row-major rows), the rest k heads (-> ko)
846void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const float* gk, const float* table, float* qo, float* ko, int rows, int q_heads, int k_heads,
847                      float eps, void* stream) {
848    sycl::queue* qu = strata::q_of(stream);
849    qu->submit([&](sycl::handler& hd) {
850        sycl::local_accessor<float, 1> red(4, hd), y(HD, hd);
851        hd.parallel_for(sycl::nd_range<2>({(size_t) (q_heads + k_heads), (size_t) rows * HD}, {1, HD}), [=](nd_item<2> it) DF2_SG32 {
852            const int hh = (int) it.get_group(0), r = (int) it.get_group(1), d = (int) it.get_local_id(1);
853            const bool isq = hh < q_heads;
854            const int h = isq ? hh : hh - q_heads, heads = isq ? q_heads : k_heads;
855            const float* in = isq ? q : k;
856            const float* gamma = isq ? gq : gk;
857            float* out = isq ? qo : ko;
858            const float x = in[((size_t) r * heads + h) * HD + d];
859            const float tot = head_norm(it, red, x, eps);
860            const float v = x * sycl::rsqrt(tot / (float) HD + eps) * gamma[d];
861            y[d] = v;
862            bar(it);
863            const int i = d & 63;
864            const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i];
865            out[((size_t) r * heads + h) * HD + d] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn;
866        });
867    });
868}
869
870// the context update's ring write: K norm + rope of (row, head) and the V copy, both into the head-major ring slot pos % slots
871void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, int heads,
872                 float eps, void* stream, int64_t* tag, const int32_t* epoch_ptr) {
873    sycl::queue* qu = strata::q_of(stream);
874    qu->submit([&](sycl::handler& hd) {
875        sycl::local_accessor<float, 1> red(4, hd), y(HD, hd);
876        hd.parallel_for(sycl::nd_range<2>({(size_t) heads, (size_t) rows * HD}, {1, HD}), [=](nd_item<2> it) DF2_SG32 {
877            const int h = (int) it.get_group(0), r = (int) it.get_group(1), d = (int) it.get_local_id(1);
878            const float x = kin[((size_t) r * heads + h) * HD + d];
879            const float tot = head_norm(it, red, x, eps);
880            const float v = x * sycl::rsqrt(tot / (float) HD + eps) * gk[d];
881            y[d] = v;
882            bar(it);
883            const int i = d & 63;
884            const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i];
885            const int slot = (int) (pos[r] % slots);
886            const size_t at = ((size_t) h * slots + slot) * HD + d;
887            kring[at] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn;
888            vring[at] = vin[((size_t) r * heads + h) * HD + d];
889            if (tag != nullptr && h == 0 && d == 0) tag[slot] = ((int64_t) *epoch_ptr << 32) | (int64_t) pos[r];
890        });
891    });
892}
893
894// silu(gate) * up then the planar quantization: grid (ceil(I / 32 / 8), rows), 256 work-items
895void df2_swiglu_quant(const float* gate, const float* up, int rows, int I, void* xq, float* xd, void* stream) {
896    int8_t* xqi = static_cast<int8_t*>(xq);
897    strata::q_of(stream)->parallel_for(sycl::nd_range<2>({(size_t) rows, (size_t) ((I / 32 + 7) / 8) * 256}, {1, 256}), [=](nd_item<2> it) DF2_SG32 {
898        const sycl::sub_group sg = it.get_sub_group();
899        const int b = (int) it.get_group(0), blk = (int) it.get_group(1) * 8 + (int) (it.get_local_id(1) >> 5), lane = (int) sg.get_local_linear_id();
900        if (blk * 32 >= I) return;
901        const size_t i = (size_t) b * I + blk * 32 + lane;
902        const float g = gate[i];
903        quant_block(sg, g / (1.0f + sycl::exp(-g)) * up[i], blk, b, I, xqi, xd);
904    });
905}
906
907// ggml Q4_0 blocks (18 bytes: fp16 d, 16 bytes with value i in the low nibble of byte i and value i + 16 in the high nibble) of a [n_out][n_in] matrix -> the
908// nibble plane (n_out * n_in / 2 bytes, the layout above) and the tiled d plane; one work-item per block
909void df2_q4_tile(const void* blocks_, void* qs_, void* dpl_, int n_in, int64_t count, void* stream) {
910    const uint8_t* blocks = static_cast<const uint8_t*>(blocks_);
911    uint8_t* qs = static_cast<uint8_t*>(qs_);
912    uint16_t* dpl = static_cast<uint16_t*>(dpl_);
913    strata::q_of(stream)->parallel_for(sycl::nd_range<1>((size_t) ((count + 255) / 256) * 256, 256), [=](nd_item<1> it) {
914        const int64_t b = (int64_t) it.get_global_id(0);
915        if (b >= count) return;
916        const int nb = n_in / 32;
917        const int64_t row = b / nb;
918        const int blk = (int) (b % nb);
919        const int64_t g = row / 8;
920        const int r = (int) (row % 8), st = blk / 16, bi = blk % 16;
921        const uint8_t* src = blocks + b * 18;
922        dpl[(g * 8 * nb) + (int64_t) st * 128 + r * 16 + bi] = (uint16_t) src[0] | ((uint16_t) src[1] << 8);
923        #pragma unroll
924        for (int half = 0; half < 2; ++half) {   // values half * 16 .. +15 of the block
925            uint32_t wd[2];
926            #pragma unroll
927            for (int w = 0; w < 2; ++w) {   // word w holds values w * 8 .. w * 8 + 7 of the half: byte p = (value w*8+p, value w*8+4+p) as (low, high) nibble
928                uint32_t v = 0;
929                #pragma unroll
930                for (int p = 0; p < 4; ++p) {
931                    const uint8_t b_lo = src[2 + w * 8 + p], b_hi = src[2 + w * 8 + 4 + p];
932                    const uint32_t q_lo = half == 0 ? (b_lo & 15u) : (b_lo >> 4), q_hi = half == 0 ? (b_hi & 15u) : (b_hi >> 4);
933                    v |= (q_lo | (q_hi << 4)) << (p * 8);
934                }
935                wd[w] = v;
936            }
937            uint8_t* o = qs + g * 8 * (n_in / 2) + (int64_t) st * 2048 + r * 256 + (bi * 2 + half) * 8;
938            reinterpret_cast<sycl::uint2*>(o)[0] = sycl::uint2(wd[0], wd[1]);
939        }
940    });
941}
942
943void df2_q8_tile(const void*, void*, void*, int, int64_t, void*) {
944    throw std::invalid_argument("df2_q8_tile: the SYCL drafter runs the Q4_0 pack only");
945}
946
947// ---- top-16
948namespace {
949constexpr int TK_CHUNK_MAX = 4096;
950inline bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); }
951}
952
953void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream) {
954    if ((n + kDf2TopBlocks - 1) / kDf2TopBlocks > TK_CHUNK_MAX) throw std::invalid_argument("df2_topk: too many logits per row");
955    float* cval = reinterpret_cast<float*>(scratch);
956    int32_t* cidx = reinterpret_cast<int32_t*>(scratch + (size_t) rows * kDf2TopBlocks * kDf2TopK);
957    sycl::queue* q = strata::q_of(stream);
958    q->submit([&](sycl::handler& hd) {
959        sycl::local_accessor<float, 1> vals(TK_CHUNK_MAX, hd), wv(8, hd);
960        sycl::local_accessor<int, 1> wi(8, hd);
961        hd.parallel_for(sycl::nd_range<2>({(size_t) rows, (size_t) kDf2TopBlocks * 256}, {1, 256}), [=](nd_item<2> it) DF2_SG32 {
962            const sycl::sub_group sg = it.get_sub_group();
963            const int row = (int) it.get_group(0), blk = (int) it.get_group(1), tid = (int) it.get_local_id(1);
964            const int cs = (n + kDf2TopBlocks - 1) / kDf2TopBlocks;
965            const int c0 = blk * cs, c1 = sycl::min(c0 + cs, n);
966            for (int i = tid; i < cs; i += 256) vals[i] = (c0 + i < c1) ? logits[(size_t) row * n + c0 + i] : -INFINITY;
967            bar(it);
968            for (int k = 0; k < kDf2TopK; ++k) {
969                float bv = -INFINITY;
970                int bi = 0x7fffffff;
971                for (int i = tid; i < cs; i += 256)
972                    if (better(vals[i], i, bv, bi)) { bv = vals[i]; bi = i; }
973                for (int o = 16; o > 0; o >>= 1) {
974                    const float ov = xorf(sg, bv, o);
975                    const int oi = xori(sg, bi, o);
976                    if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; }
977                }
978                if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; }
979                bar(it);
980                if (tid == 0) {
981                    float v = wv[0];
982                    int ix = wi[0];
983                    for (int w = 1; w < 8; ++w)
984                        if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; }
985                    const size_t o = ((size_t) row * kDf2TopBlocks + blk) * kDf2TopK + k;
986                    cval[o] = v;
987                    cidx[o] = v == -INFINITY ? -1 : c0 + ix;
988                    if (v != -INFINITY) vals[ix] = -INFINITY;
989                }
990                bar(it);
991            }
992        });
993    });
994    q->submit([&](sycl::handler& hd) {
995        constexpr int NC = kDf2TopBlocks * kDf2TopK;
996        sycl::local_accessor<float, 1> sv(NC, hd), wv(8, hd);
997        sycl::local_accessor<int, 1> si(NC, hd), wi(8, hd), wp(8, hd);
998        hd.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](nd_item<1> it) DF2_SG32 {
999            const sycl::sub_group sg = it.get_sub_group();
1000            const int row = (int) it.get_group(0), tid = (int) it.get_local_id(0);
1001            for (int i = tid; i < NC; i += 256) { sv[i] = cval[(size_t) row * NC + i]; si[i] = cidx[(size_t) row * NC + i]; }
1002            bar(it);
1003            for (int k = 0; k < kDf2TopK; ++k) {
1004                float bv = -INFINITY;
1005                int bi = 0x7fffffff, bp = -1;
1006                for (int i = tid; i < NC; i += 256)
1007                    if (si[i] >= 0 && better(sv[i], si[i], bv, bi)) { bv = sv[i]; bi = si[i]; bp = i; }
1008                for (int o = 16; o > 0; o >>= 1) {
1009                    const float ov = xorf(sg, bv, o);
1010                    const int oi = xori(sg, bi, o);
1011                    const int op = xori(sg, bp, o);
1012                    if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; bp = op; }
1013                }
1014                if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; wp[tid >> 5] = bp; }
1015                bar(it);
1016                if (tid == 0) {
1017                    float v = wv[0];
1018                    int ix = wi[0], p = wp[0];
1019                    for (int w = 1; w < 8; ++w)
1020                        if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; p = wp[w]; }
1021                    if (p >= 0) si[p] = -1;
1022                    val[row * kDf2TopK + k] = v;
1023                    tok[row * kDf2TopK + k] = p >= 0 ? (idx_map ? idx_map[ix] : ix) : 0;
1024                }
1025                bar(it);
1026            }
1027        });
1028    });
1029}
1030
1031// ---- the selector's walk: one group of 256 work-items
1032void df2_select(const float* hp, const float* unary, const int32_t* tok, const uint16_t* pred_cb, const uint16_t* succ_cb, int rank, int rows,
1033                const int32_t* anchor_tok, int32_t* out_tok, float* out_prob, void* stream, bool cb_q4) {
1034    if (cb_q4) throw std::invalid_argument("df2_select: Q4_0 selector codebooks are not on SYCL (the loader keeps the bf16 pack)");
1035    if (rank != 256) throw std::invalid_argument("df2_select: the selector rank must be 256");
1036    sycl::queue* q = strata::q_of(stream);
1037    q->submit([&](sycl::handler& hd) {
1038        sycl::local_accessor<float, 1> vp(256, hd), sc(kDf2TopK, hd);
1039        sycl::local_accessor<int, 1> prev(1, hd);
1040        hd.parallel_for(sycl::nd_range<1>(256, 256), [=](nd_item<1> it) DF2_SG32 {
1041            const sycl::sub_group sg = it.get_sub_group();
1042            const int tid = (int) it.get_local_id(0), w = tid >> 5, lane = tid & 31;
1043            if (tid == 0) prev[0] = *anchor_tok;
1044            bar(it);
1045            for (int i = 0; i < rows; ++i) {
1046                vp[tid] = bf16f(pred_cb[(size_t) prev[0] * rank + tid]) * hp[(size_t) i * rank + tid];
1047                bar(it);
1048                for (int j = w * 2; j < w * 2 + 2; ++j) {
1049                    const int t = tok[i * kDf2TopK + j];
1050                    const sycl::uint4 raw = *reinterpret_cast<const sycl::uint4*>(succ_cb + (size_t) t * rank + lane * 8);
1051                    const uint32_t u[4] = {raw.x(), raw.y(), raw.z(), raw.w()};
1052                    float acc = 0.0f;
1053                    #pragma unroll
1054                    for (int e = 0; e < 4; ++e) {
1055                        acc = sycl::fma(sycl::bit_cast<float>(u[e] << 16), vp[lane * 8 + e * 2], acc);
1056                        acc = sycl::fma(sycl::bit_cast<float>(u[e] & 0xffff0000u), vp[lane * 8 + e * 2 + 1], acc);
1057                    }
1058                    for (int o = 16; o > 0; o >>= 1) acc += xorf(sg, acc, o);
1059                    if (lane == 0) sc[j] = unary[i * kDf2TopK + j] + acc;
1060                }
1061                bar(it);
1062                if (tid == 0) {
1063                    int bj = 0;
1064                    float bv = sc[0];
1065                    for (int j = 1; j < kDf2TopK; ++j)
1066                        if (sc[j] > bv) { bv = sc[j]; bj = j; }
1067                    float z = 0.0f;
1068                    for (int j = 0; j < kDf2TopK; ++j) z += sycl::exp(sc[j] - bv);
1069                    out_tok[i] = tok[i * kDf2TopK + bj];
1070                    out_prob[i] = 1.0f / z;
1071                    prev[0] = out_tok[i];
1072                }
1073                bar(it);
1074            }
1075        });
1076    });
1077}
1078
1079void df2_tap_rows(const float* R, float* out, int64_t out_stride, int64_t n_embd, int hc, int rows, void* stream) {
1080    strata::q_of(stream)->parallel_for(sycl::nd_range<2>({(size_t) rows, (size_t) ((n_embd + 255) / 256) * 256}, {1, 256}), [=](nd_item<2> it) {
1081        const int64_t i = (int64_t) it.get_group(1) * 256 + (int64_t) it.get_local_id(1);
1082        const int r = (int) it.get_group(0);
1083        if (i >= n_embd) return;
1084        float s = 0.0f;
1085        for (int c = 0; c < hc; ++c) s += R[((size_t) r * hc + c) * n_embd + i];
1086        out[(size_t) r * out_stride + i] = s / (float) hc;
1087    });
1088}
1089
1090void df2_tap_gr(const float* R, int64_t R_stride, const float* bo, int64_t bo_stride, const float* inject, int64_t inj_stride, float* out, int64_t out_stride, int rows,
1091                int64_t n_embd, int hc, void* stream) {
1092    strata::q_of(stream)->parallel_for(sycl::nd_range<2>({(size_t) rows, (size_t) ((n_embd + 255) / 256) * 256}, {1, 256}), [=](nd_item<2> it) {
1093        const int64_t i = (int64_t) it.get_group(1) * 256 + (int64_t) it.get_local_id(1);
1094        const int r = (int) it.get_group(0);
1095        if (i >= n_embd) return;
1096        float wsum = 0.0f, rs = 0.0f;
1097        for (int c = 0; c < hc; ++c) {
1098            const float x = inject[(size_t) r * inj_stride + c] / (float) hc;
1099            wsum += 2.0f / (1.0f + sycl::exp(-x));
1100            rs += R[(size_t) r * R_stride + (size_t) c * n_embd + i];
1101        }
1102        out[(size_t) r * out_stride + i] = (rs + bo[(size_t) r * bo_stride + i] * wsum) / (float) hc;
1103    });
1104}
1105
1106}  // namespace strata::kernels