okami.mom/strata

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

Niko1221rc1 merge df2-q4sel (ebac5686f, incl. df2-comm select kernel)f93c5019f

main
59.9 KiB1171 linesraw
1// src/kernels/cuda/dflash2.cu - the small kernels of the DFlash2 drafter.  See include/strata/kernels/dflash2.hpp.
2#include "strata/kernels/dflash2.hpp"
3
4#include "strata/kernels/dp4a.hpp"
5#include "strata/kernels/gfx_arch.hpp"
6
7#include <cuda_fp16.h>
8#include <cuda_runtime.h>
9
10#include <cfloat>
11#include <cmath>
12#include <cstdio>
13#include <cstdlib>
14#include <stdexcept>
15#include <string>
16
17namespace strata::kernels {
18namespace {
19
20constexpr int HD = kDf2Hd;
21int g_gemm_variant = 0;   // bench only (df2_gemm_variant)
22int g_attn_variant = 0;   // bench only (df2_attention_variant)
23
24void check(const char* what) {
25    const cudaError_t e = cudaGetLastError();
26    if (e != cudaSuccess) {
27        std::fprintf(stderr, "dflash2 kernel %s: %s\n", what, cudaGetErrorString(e));
28        throw std::runtime_error(std::string("dflash2 kernel ") + what + ": " + cudaGetErrorString(e));
29    }
30}
31
32__device__ __forceinline__ float bf16f(uint16_t h) { return __uint_as_float((uint32_t) h << 16); }
33
34// ---- the grouped dynamic 2-tap convolution over the block's rows
35__global__ void conv_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base,
36                            const float* __restrict__ resid, float* __restrict__ out, int rows, int H, int group) {
37    const int i = blockIdx.x * blockDim.x + threadIdx.x;
38    if (i >= rows * H) return;
39    const int b = i / H, c = i % H;
40    const int groups = H / group;
41    float acc = 0.0f;
42#pragma unroll
43    for (int o = 0; o < 2; ++o) {
44        if (b - o < 0) continue;
45        const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
46        acc = fmaf(k, x[(size_t) (b - o) * H + c], acc);
47    }
48    out[i] = resid ? resid[i] + acc : acc;
49}
50
51__global__ void rope_table_kernel(const int32_t* __restrict__ pos, int rows, float theta, float* __restrict__ table) {
52    const int r = blockIdx.x, i = threadIdx.x;   // 64 threads
53    if (r >= rows) return;
54    const double inv = pow((double) theta, -(double) (2 * i) / (double) HD);
55    double ang = (double) pos[r] * inv;
56    const double two_pi = 6.283185307179586476925286766559;
57    ang -= two_pi * rint(ang / two_pi);   // [-pi, pi]
58    float s, c;
59    sincosf((float) ang, &s, &c);
60    table[(r * 2 + 0) * 64 + i] = c;
61    table[(r * 2 + 1) * 64 + i] = s;
62}
63
64__global__ void rope_inv_kernel(float theta, double* __restrict__ inv) {
65    const int i = threadIdx.x;   // 64 threads
66    inv[i] = pow((double) theta, -(double) (2 * i) / (double) HD);
67}
68
69__global__ void rope_table_inv_kernel(const int32_t* __restrict__ pos, int rows, const double* __restrict__ inv_tab, float* __restrict__ table) {
70    const int r = blockIdx.x, i = threadIdx.x;   // 64 threads
71    if (r >= rows) return;
72    const double inv = inv_tab[i];
73    double ang = (double) pos[r] * inv;
74    const double two_pi = 6.283185307179586476925286766559;
75    ang -= two_pi * rint(ang / two_pi);   // [-pi, pi]
76    float s, c;
77    sincosf((float) ang, &s, &c);
78    table[(r * 2 + 0) * 64 + i] = c;
79    table[(r * 2 + 1) * 64 + i] = s;
80}
81
82// one block per (row, head), 128 threads: out = rope(rmsnorm(in) * gamma)
83__global__ void norm_rope_kernel(const float* __restrict__ in, int in_stride, const float* __restrict__ gamma, const int32_t* __restrict__ pos,
84                                 const float* __restrict__ table, float* __restrict__ out, int slot_mod, int heads, float eps) {
85    const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
86    __shared__ float red[4];
87    __shared__ float y[HD];
88    const float x = in[(size_t) r * in_stride + h * HD + d];
89    float ss = x * x;
90    for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o);
91    if ((d & 31) == 0) red[d >> 5] = ss;
92    __syncthreads();
93    const float tot = red[0] + red[1] + red[2] + red[3];
94    const float v = x * rsqrtf(tot / (float) HD + eps) * gamma[d];
95    float res = v;
96    if (table != nullptr) {
97        y[d] = v;
98        __syncthreads();
99        const int i = d & 63;
100        const float c = table[(r * 2 + 0) * 64 + i], s = table[(r * 2 + 1) * 64 + i];
101        res = d < 64 ? v * c - y[d + 64] * s : v * c + y[d - 64] * s;
102    }
103    const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r;
104    // a ring (slot_mod > 0) is head-major [head][slot][128], the block's own keys row-major [row][head][128]
105    out[slot_mod > 0 ? ((size_t) h * slot_mod + slot) * HD + d : ((size_t) slot * heads + h) * HD + d] = res;
106}
107
108__global__ void copy_rows_kernel(const float* __restrict__ in, float* __restrict__ out, const int32_t* __restrict__ pos, int slot_mod, int rows, int cols) {
109    const int i = blockIdx.x * blockDim.x + threadIdx.x;
110    if (i >= rows * cols) return;
111    const int r = i / cols, c = i % cols;
112    const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r;
113    out[slot_mod > 0 ? ((size_t) (c / HD) * slot_mod + slot) * HD + c % HD : (size_t) slot * cols + c] = in[i];
114}
115
116// ---- attention.  grid (8 K/V heads, kDf2MaxChunks), 128 threads.  The 32 queries (4 heads x 8 rows) of a K/V head share each key tile;
117// S = Q K^T in 4 x 4 register tiles (64 threads), the online softmax per query, O += P V in 4 x 8 register tiles (128 threads).
118constexpr int AS = 132;   // smem row stride of the Q / K / V tiles (float4 aligned, conflict-free for the 4 x 4 tiles)
119constexpr int PS = 36;    // stride of the transposed probabilities P[key][query]
120__global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict__ q, const float* __restrict__ kring, const float* __restrict__ vring,
121                                                       const float* __restrict__ kblk, const float* __restrict__ vblk,
122                                                       const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part, int variant,
123                                                       const int64_t* __restrict__ tag, const int32_t* __restrict__ epoch_ptr) {
124    __shared__ __align__(16) float Qs[32 * AS];
125    __shared__ __align__(16) float Ks[32 * AS];   // the K tile, then the V tile
126    __shared__ __align__(16) float Ps[32 * PS];
127    __shared__ float Sc[32 * 33];
128    __shared__ float m_s[32], l_s[32], corr_s[32];
129    __shared__ unsigned char kvalid[32];   // key t of the tile holds the context row it should (ring tags, serve: a ring left by another conversation)
130    const int kvh = blockIdx.x, chunk = blockIdx.y, tid = threadIdx.x;
131    const int s = *anchor_pos;
132    const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0;
133    const int nctx = s - lo;
134    const int nkeys = nctx + kDf2Rows;
135    const int k_begin = chunk * kDf2Chunk;
136    const int64_t ep = tag != nullptr ? ((int64_t) *epoch_ptr << 32) : 0;
137    float* const pbase = part + (((size_t) chunk * kDf2Kv + kvh) * 32) * 130;
138    if (k_begin >= nkeys) {
139        for (int i = tid; i < 32 * 130; i += 128) pbase[i] = (i % 130 == 0) ? -INFINITY : 0.0f;
140        return;
141    }
142    const float scale = rsqrtf((float) HD);
143    for (int i = tid; i < 32 * HD / 4; i += 128) {   // Q: 32 queries x 128, float4
144        const int a = i / (HD / 4), d4 = i % (HD / 4);
145        const int row = a >> 2, g = a & 3;
146        float4 v = *reinterpret_cast<const float4*>(q + ((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d4 * 4);
147        v.x *= scale; v.y *= scale; v.z *= scale; v.w *= scale;
148        *reinterpret_cast<float4*>(&Qs[a * AS + d4 * 4]) = v;
149    }
150    if (tid < 32) { m_s[tid] = -INFINITY; l_s[tid] = 0.0f; }
151    float O[4][8];
152#pragma unroll
153    for (int i = 0; i < 4; ++i)
154#pragma unroll
155        for (int j = 0; j < 8; ++j) O[i][j] = 0.0f;
156    const int qg_pv = tid >> 4, dg_pv = tid & 15;   // PV: queries qg*4 .. +3, dims dg*8 .. +7
157    const int k_end = min(k_begin + kDf2Chunk, nkeys);
158    // a tile is 32 keys x 128 dims = 1024 float4: eight per thread, loaded into registers ahead of their use
159    auto fetch = [&](int k0, float4 (&reg)[8], const float* ring, const float* blk) {
160#pragma unroll
161        for (int u = 0; u < 8; ++u) {
162            const int i = tid + u * 128, t = i / (HD / 4), d4 = i % (HD / 4), k = k0 + t;
163            float4 v = make_float4(0.f, 0.f, 0.f, 0.f);
164            if (k < nctx) v = *reinterpret_cast<const float4*>(ring + ((size_t) kvh * ring_slots + (lo + k) % ring_slots) * HD + d4 * 4);
165            else if (k < nkeys) v = *reinterpret_cast<const float4*>(blk + ((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d4 * 4);
166            reg[u] = v;
167        }
168    };
169    auto put = [&](const float4 (&reg)[8]) {
170#pragma unroll
171        for (int u = 0; u < 8; ++u) {
172            const int i = tid + u * 128, t = i / (HD / 4), d4 = i % (HD / 4);
173            *reinterpret_cast<float4*>(&Ks[t * AS + d4 * 4]) = reg[u];
174        }
175    };
176    float4 kreg[8], vreg[8];
177    fetch(k_begin, kreg, kring, kblk);
178    for (int k0 = k_begin; k0 < k_end; k0 += 32) {
179        __syncthreads();   // Ks free (the last tile's V reads done); Qs / m_s written on the first pass
180        put(kreg);
181        if (tid < 32) {
182            const int k = k0 + tid;
183            kvalid[tid] = (tag == nullptr || k >= nctx || k >= nkeys) ? 1 : (tag[(lo + k) % ring_slots] == (ep | (int64_t) (lo + k)) ? 1 : 0);
184        }
185        fetch(k0, vreg, vring, vblk);   // this tile's V, hidden behind the S stage and the softmax
186        __syncthreads();
187        if (tid < 64) {   // S tile: 4 queries x 4 keys per thread
188            const int qg = tid >> 3, kg = tid & 7;
189            float acc[4][4];
190#pragma unroll
191            for (int i = 0; i < 4; ++i)
192#pragma unroll
193                for (int j = 0; j < 4; ++j) acc[i][j] = 0.0f;
194#pragma unroll 4
195            for (int d = 0; d < ((variant & 1) ? 0 : HD); d += 4) {
196                float4 qv[4], kv[4];
197#pragma unroll
198                for (int i = 0; i < 4; ++i) qv[i] = *reinterpret_cast<const float4*>(&Qs[(qg * 4 + i) * AS + d]);
199#pragma unroll
200                for (int j = 0; j < 4; ++j) kv[j] = *reinterpret_cast<const float4*>(&Ks[(kg * 4 + j) * AS + d]);
201#pragma unroll
202                for (int i = 0; i < 4; ++i)
203#pragma unroll
204                    for (int j = 0; j < 4; ++j)
205                        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;
206            }
207#pragma unroll
208            for (int i = 0; i < 4; ++i)
209#pragma unroll
210                for (int j = 0; j < 4; ++j) {
211                    const int qi = qg * 4 + i, t = kg * 4 + j, k = k0 + t, row = qi >> 2;
212                    bool ok = k < nkeys;
213                    if (ok && k < nctx) ok = (lo + k) > (s + row - window) && kvalid[t];   // s + row - j < window, and the slot holds that row
214                    Sc[qi * 33 + t] = ok ? acc[i][j] : -INFINITY;
215                }
216        }
217        __syncthreads();
218        {   // online softmax: query = tid / 4, 8 keys each, 4 lanes per query
219            const int qi = tid >> 2, sub = tid & 3;
220            float v[8], tmax = -INFINITY;
221#pragma unroll
222            for (int u = 0; u < 8; ++u) { v[u] = Sc[qi * 33 + sub * 8 + u]; tmax = fmaxf(tmax, v[u]); }
223            tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 1));
224            tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 2));
225            const float m_old = m_s[qi];
226            const float mn = fmaxf(m_old, tmax);
227            const float corr = (m_old == -INFINITY) ? 0.0f : __expf(m_old - mn);
228            float psum = 0.0f;
229#pragma unroll
230            for (int u = 0; u < 8; ++u) {
231                const float p = v[u] == -INFINITY ? 0.0f : __expf(v[u] - mn);
232                Ps[(sub * 8 + u) * PS + qi] = p;
233                psum += p;
234            }
235            psum += __shfl_xor_sync(0xffffffffu, psum, 1);
236            psum += __shfl_xor_sync(0xffffffffu, psum, 2);
237            if (sub == 0) { l_s[qi] = l_s[qi] * corr + psum; m_s[qi] = mn; corr_s[qi] = corr; }
238        }
239        __syncthreads();   // Ps, corr_s complete; every read of Ks (the S tile) done
240        put(vreg);
241        if (k0 + 32 < k_end) fetch(k0 + 32, kreg, kring, kblk);   // the next tile's K, hidden behind the PV stage
242        __syncthreads();
243        {
244            const float4 c4 = *reinterpret_cast<const float4*>(&corr_s[qg_pv * 4]);
245            const float cr[4] = {c4.x, c4.y, c4.z, c4.w};
246#pragma unroll
247            for (int i = 0; i < 4; ++i)
248#pragma unroll
249                for (int j = 0; j < 8; ++j) O[i][j] *= cr[i];
250#pragma unroll 4
251            for (int t = 0; t < ((variant & 2) ? 0 : 32); ++t) {
252                const float4 p4 = *reinterpret_cast<const float4*>(&Ps[t * PS + qg_pv * 4]);
253                const float4 va = *reinterpret_cast<const float4*>(&Ks[t * AS + dg_pv * 8]);
254                const float4 vb = *reinterpret_cast<const float4*>(&Ks[t * AS + dg_pv * 8 + 4]);
255                const float pv[4] = {p4.x, p4.y, p4.z, p4.w};
256                const float vv[8] = {va.x, va.y, va.z, va.w, vb.x, vb.y, vb.z, vb.w};
257#pragma unroll
258                for (int i = 0; i < 4; ++i)
259#pragma unroll
260                    for (int j = 0; j < 8; ++j) O[i][j] = fmaf(pv[i], vv[j], O[i][j]);
261            }
262        }
263    }
264    __syncthreads();
265    if (tid < 32) { pbase[tid * 130] = m_s[tid]; pbase[tid * 130 + 1] = l_s[tid]; }
266#pragma unroll
267    for (int i = 0; i < 4; ++i) {
268        float* o = pbase + (size_t) (qg_pv * 4 + i) * 130 + 2 + dg_pv * 8;
269        *reinterpret_cast<float2*>(o) = make_float2(O[i][0], O[i][1]);
270        *reinterpret_cast<float2*>(o + 2) = make_float2(O[i][2], O[i][3]);
271        *reinterpret_cast<float2*>(o + 4) = make_float2(O[i][4], O[i][5]);
272        *reinterpret_cast<float2*>(o + 6) = make_float2(O[i][6], O[i][7]);
273    }
274}
275
276__device__ __forceinline__ void quant_block(float v, int blk, int col, int K, int8_t* __restrict__ xq, float* __restrict__ xd);
277
278__global__ void attn_merge_kernel(const float* __restrict__ part, int8_t* __restrict__ xq, float* __restrict__ xd) {
279    const int a = blockIdx.x;                      // kvh * 32 + qi
280    const int kvh = a >> 5, qi = a & 31, d = threadIdx.x;
281    float M = -INFINITY;
282    for (int c = 0; c < kDf2MaxChunks; ++c) M = fmaxf(M, part[(((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130]);
283    float L = 0.0f, o = 0.0f;
284    for (int c = 0; c < kDf2MaxChunks; ++c) {
285        const float* p = part + (((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130;
286        const float mc = p[0];
287        const float w = (mc == -INFINITY) ? 0.0f : __expf(mc - M);
288        L += p[1] * w;
289        o = fmaf(p[2 + d], w, o);
290    }
291    const int row = qi >> 2, g = qi & 3;
292    // the output row `row`, head kvh * 4 + g, dims d: quant block (kvh * 4 + g) * 4 + d / 32 of the 4096-wide row
293    quant_block(L > 0.0f ? o / L : 0.0f, (kvh * kDf2Gqa + g) * (HD / 32) + (d >> 5), row, 32 * HD, xq, xd);
294}
295
296// ---- Q8 GEMM for up to 8 activation columns (the drafter's matrices)
297//
298// Weights are TILED (df2_q8_tile makes them from GGUF Q8_0 blocks): a group of 8 rows is one unit; per 512 values of the reduction axis (a "step",
299// 16 Q8 blocks) the group stores the 8 rows' 512 int8 one after the other (4 KB), so a warp that works on a group reads 4 KB contiguous per step
300// (lane = block * 2 + half: one 16-byte load per row).  The fp16 block scales follow all the int8 of the matrix, in the same tile order (8 rows x 16
301// blocks = 256 bytes a step).  Activations: x_q (int8 [col][n_in]) and x_d (float [col][n_in / 32]); a column's 512 bytes of a step are contiguous.
302struct Df2Seg { const int8_t* q; const __half* d; float* y; int n_out; int row0; };
303struct Df2Segs { Df2Seg s[3]; int n; };
304
305// The matrix a warp's rows belong to.  Constant indices only: a loop over segs.s[si] makes the by-value parameter struct live in local memory (STACK 104 in the spill guard).
306__device__ __forceinline__ Df2Seg df2_pick(const Df2Segs& segs, int row_g) {
307    Df2Seg sg = segs.s[0];
308    if (segs.n > 1 && row_g >= segs.s[1].row0) sg = segs.s[1];
309    if (segs.n > 2 && row_g >= segs.s[2].row0) sg = segs.s[2];
310    return sg;
311}
312
313template <int WARPS, bool COMPUTE, int UNR = 2>
314__global__ void __launch_bounds__(WARPS * 32) gemm8_kernel(Df2Segs segs, const int8_t* __restrict__ xq, const float* __restrict__ xd, int n_in, int ncols) {
315    constexpr int R = 8;
316    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
317    const int row_g = (blockIdx.x * WARPS + warp) * R;   // first row of this warp's group, over all the launch's matrices
318    const Df2Seg sg = df2_pick(segs, row_g);
319    const int row0 = row_g - sg.row0;
320    const int nb = n_in / 32, steps = nb / 16;
321    const int4* wq = reinterpret_cast<const int4*>(sg.q + (size_t) row0 * n_in) + lane;
322    const __half* wd = sg.d + (size_t) row0 * nb + (lane >> 1);
323    const int4* xv = reinterpret_cast<const int4*>(xq) + lane;
324    float acc[R][8];
325#pragma unroll
326    for (int r = 0; r < R; ++r)
327#pragma unroll
328        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
329#pragma unroll UNR
330    for (int st = 0; st < steps; ++st) {
331        int4 w[R];
332        float dw[R];
333#pragma unroll
334        for (int r = 0; r < R; ++r) {
335            w[r] = wq[(size_t) st * 256 + r * 32];
336            dw[r] = __half2float(wd[(size_t) st * 128 + r * 16]);
337        }
338        if (!COMPUTE) {   // bench only: the same loads, almost no arithmetic
339            for (int r = 0; r < R; ++r) acc[r][0] += (float) (w[r].x ^ w[r].y ^ w[r].z ^ w[r].w) * dw[r];
340            continue;
341        }
342        float xs[8];
343#pragma unroll
344        for (int c = 0; c < 8; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
345#pragma unroll
346        for (int c = 0; c < 8; ++c) {
347            const int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
348#pragma unroll
349            for (int r = 0; r < R; ++r) {
350                int isum = STRATA_DP4A(w[r].x, x.x, 0);
351                isum = STRATA_DP4A(w[r].y, x.y, isum);
352                isum = STRATA_DP4A(w[r].z, x.z, isum);
353                isum = STRATA_DP4A(w[r].w, x.w, isum);
354                acc[r][c] = fmaf(dw[r] * xs[c], (float) isum, acc[r][c]);
355            }
356        }
357    }
358#pragma unroll
359    for (int r = 0; r < R; ++r)
360#pragma unroll
361        for (int c = 0; c < 8; ++c) {
362            float v = acc[r][c];
363            v += __shfl_xor_sync(0xffffffffu, v, 16);
364            v += __shfl_xor_sync(0xffffffffu, v, 8);
365            v += __shfl_xor_sync(0xffffffffu, v, 4);
366            v += __shfl_xor_sync(0xffffffffu, v, 2);
367            v += __shfl_xor_sync(0xffffffffu, v, 1);
368            if (lane == 0 && c < ncols) sg.y[(size_t) c * sg.n_out + row0 + r] = v;
369        }
370}
371
372// The same GEMM with R rows a warp instead of 8 (R = 4, 2, 1): a group of 8 rows is shared by 8 / R warps, each reading only its rows' weights.  Every output keeps
373// the arithmetic of gemm8_kernel (lane l's partial sums run over the same steps in the same order, the same shuffle tree), so the result is bitwise the same;
374// what changes is the number of warps in flight: the small matrices (fc 2560 rows = 320 groups, the 640-row convolution kernels) fill only a third of the
375// card with one warp per group, and a warp that waits for its 4 KB step per row stalls the group.
376template <int WARPS, int R, int UNR>
377__global__ void __launch_bounds__(WARPS * 32) gemm_rows_kernel(Df2Segs segs, const int8_t* __restrict__ xq, const float* __restrict__ xd, int n_in, int ncols) {
378    constexpr int SUBS = 8 / R;
379    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
380    const int wi = blockIdx.x * WARPS + warp;
381    const int row_g = (wi / SUBS) * 8, sub = wi % SUBS;
382    const Df2Seg sg = df2_pick(segs, row_g);
383    const int row0 = row_g - sg.row0;
384    const int nb = n_in / 32, steps = nb / 16;
385    const int4* wq = reinterpret_cast<const int4*>(sg.q + (size_t) row0 * n_in) + lane + sub * R * 32;
386    const __half* wd = sg.d + (size_t) row0 * nb + (lane >> 1) + sub * R * 16;
387    const int4* xv = reinterpret_cast<const int4*>(xq) + lane;
388    float acc[R][8];
389#pragma unroll
390    for (int r = 0; r < R; ++r)
391#pragma unroll
392        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
393#pragma unroll UNR
394    for (int st = 0; st < steps; ++st) {
395        int4 w[R];
396        float dw[R];
397#pragma unroll
398        for (int r = 0; r < R; ++r) {
399            w[r] = wq[(size_t) st * 256 + r * 32];
400            dw[r] = __half2float(wd[(size_t) st * 128 + r * 16]);
401        }
402        float xs[8];
403#pragma unroll
404        for (int c = 0; c < 8; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
405#pragma unroll
406        for (int c = 0; c < 8; ++c) {
407            const int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
408#pragma unroll
409            for (int r = 0; r < R; ++r) {
410                int isum = STRATA_DP4A(w[r].x, x.x, 0);
411                isum = STRATA_DP4A(w[r].y, x.y, isum);
412                isum = STRATA_DP4A(w[r].z, x.z, isum);
413                isum = STRATA_DP4A(w[r].w, x.w, isum);
414                acc[r][c] = fmaf(dw[r] * xs[c], (float) isum, acc[r][c]);
415            }
416        }
417    }
418#pragma unroll
419    for (int r = 0; r < R; ++r)
420#pragma unroll
421        for (int c = 0; c < 8; ++c) {
422            float v = acc[r][c];
423            v += __shfl_xor_sync(0xffffffffu, v, 16);
424            v += __shfl_xor_sync(0xffffffffu, v, 8);
425            v += __shfl_xor_sync(0xffffffffu, v, 4);
426            v += __shfl_xor_sync(0xffffffffu, v, 2);
427            v += __shfl_xor_sync(0xffffffffu, v, 1);
428            if (lane == 0 && c < ncols) sg.y[(size_t) c * sg.n_out + row0 + sub * R + r] = v;
429        }
430}
431
432// ---- Q4_0 variant of the same GEMM (opt-in drafter pack, dtype "q4_0"; a weight is 4 bits, the activations stay int8)
433//
434// Same tiling as the Q8 plane: a group of 8 rows is a unit and a step is 512 values of the reduction axis.  A row's 512 values are 256 bytes in the
435// step (2 KB for the group), lane = block * 2 + half takes 8 bytes = 16 values as two words.  Word 0 holds values 0-3 in its four low nibbles and
436// 4-7 in its four high nibbles, word 1 holds 8-11 and 12-15, so (w & 0x0F0F0F0F) and ((w >> 4) & 0x0F0F0F0F) are the int8 words dp4a wants, as
437// unsigned q = 0..15 (value = (q - 8) * d, ggml Q4_0).  sum((q - 8) x) = sum(q x) - 8 sum(x): the sum of the lane's 16 activations is one more dp4a
438// per word and column, shared by the 8 rows.  The fp16 block scales follow the nibble plane (n_out * n_in / 2 bytes) in the Q8 plane's order.
439template <int WARPS, int UNR = 2>
440__global__ void __launch_bounds__(WARPS * 32) gemm4_kernel(Df2Segs segs, const int8_t* __restrict__ xq, const float* __restrict__ xd, int n_in, int ncols) {
441    constexpr int R = 8;
442    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
443    const int row_g = (blockIdx.x * WARPS + warp) * R;
444    const Df2Seg sg = df2_pick(segs, row_g);
445    const int row0 = row_g - sg.row0;
446    const int nb = n_in / 32, steps = nb / 16;
447    const uint2* wq = reinterpret_cast<const uint2*>(sg.q + (size_t) row0 * (n_in / 2)) + lane;
448    const __half* wd = sg.d + (size_t) row0 * nb + (lane >> 1);
449    const int4* xv = reinterpret_cast<const int4*>(xq) + lane;
450    float acc[R][8];
451#pragma unroll
452    for (int r = 0; r < R; ++r)
453#pragma unroll
454        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
455#pragma unroll UNR
456    for (int st = 0; st < steps; ++st) {
457        int4 w[R];
458        float dw[R];
459#pragma unroll
460        for (int r = 0; r < R; ++r) {
461            const uint2 raw = wq[(size_t) st * 256 + r * 32];   // 8 rows x 32 lanes x 8 bytes = 2 KB a step
462            w[r] = make_int4((int) (raw.x & 0x0F0F0F0Fu), (int) ((raw.x >> 4) & 0x0F0F0F0Fu), (int) (raw.y & 0x0F0F0F0Fu), (int) ((raw.y >> 4) & 0x0F0F0F0Fu));
463            dw[r] = __half2float(wd[(size_t) st * 128 + r * 16]);
464        }
465        float xs[8];
466#pragma unroll
467        for (int c = 0; c < 8; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
468#pragma unroll
469        for (int c = 0; c < 8; ++c) {
470            const int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
471            int xsum = STRATA_DP4A(0x01010101, x.x, 0);
472            xsum = STRATA_DP4A(0x01010101, x.y, xsum);
473            xsum = STRATA_DP4A(0x01010101, x.z, xsum);
474            xsum = STRATA_DP4A(0x01010101, x.w, xsum);
475#pragma unroll
476            for (int r = 0; r < R; ++r) {
477                int isum = STRATA_DP4A(w[r].x, x.x, 0);
478                isum = STRATA_DP4A(w[r].y, x.y, isum);
479                isum = STRATA_DP4A(w[r].z, x.z, isum);
480                isum = STRATA_DP4A(w[r].w, x.w, isum);
481                acc[r][c] = fmaf(dw[r] * xs[c], (float) (isum - 8 * xsum), acc[r][c]);
482            }
483        }
484    }
485#pragma unroll
486    for (int r = 0; r < R; ++r)
487#pragma unroll
488        for (int c = 0; c < 8; ++c) {
489            float v = acc[r][c];
490            v += __shfl_xor_sync(0xffffffffu, v, 16);
491            v += __shfl_xor_sync(0xffffffffu, v, 8);
492            v += __shfl_xor_sync(0xffffffffu, v, 4);
493            v += __shfl_xor_sync(0xffffffffu, v, 2);
494            v += __shfl_xor_sync(0xffffffffu, v, 1);
495            if (lane == 0 && c < ncols) sg.y[(size_t) c * sg.n_out + row0 + r] = v;
496        }
497}
498
499// The Q4_0 GEMM with R rows a warp (R = 4, 2, 1) instead of 8, as gemm_rows_kernel is to gemm8_kernel: a group of 8 rows is shared by 8 / R warps, each reading only its
500// rows' nibbles and scales; every output keeps the arithmetic of gemm4_kernel (same steps in the same order per lane, the same xsum and shuffle tree), so the result is bitwise
501// the same.  The activations' per-column sum is recomputed by each of the group's warps (4 dp4a a column and step).
502template <int WARPS, int R, int UNR>
503__global__ void __launch_bounds__(WARPS * 32) gemm4_rows_kernel(Df2Segs segs, const int8_t* __restrict__ xq, const float* __restrict__ xd, int n_in, int ncols) {
504    constexpr int SUBS = 8 / R;
505    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
506    const int wi = blockIdx.x * WARPS + warp;
507    const int row_g = (wi / SUBS) * 8, sub = wi % SUBS;
508    const Df2Seg sg = df2_pick(segs, row_g);
509    const int row0 = row_g - sg.row0;
510    const int nb = n_in / 32, steps = nb / 16;
511    const uint2* wq = reinterpret_cast<const uint2*>(sg.q + (size_t) row0 * (n_in / 2)) + lane + sub * R * 32;
512    const __half* wd = sg.d + (size_t) row0 * nb + (lane >> 1) + sub * R * 16;
513    const int4* xv = reinterpret_cast<const int4*>(xq) + lane;
514    float acc[R][8];
515#pragma unroll
516    for (int r = 0; r < R; ++r)
517#pragma unroll
518        for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f;
519#pragma unroll UNR
520    for (int st = 0; st < steps; ++st) {
521        int4 w[R];
522        float dw[R];
523#pragma unroll
524        for (int r = 0; r < R; ++r) {
525            const uint2 raw = wq[(size_t) st * 256 + r * 32];
526            w[r] = make_int4((int) (raw.x & 0x0F0F0F0Fu), (int) ((raw.x >> 4) & 0x0F0F0F0Fu), (int) (raw.y & 0x0F0F0F0Fu), (int) ((raw.y >> 4) & 0x0F0F0F0Fu));
527            dw[r] = __half2float(wd[(size_t) st * 128 + r * 16]);
528        }
529        float xs[8];
530#pragma unroll
531        for (int c = 0; c < 8; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)];
532#pragma unroll
533        for (int c = 0; c < 8; ++c) {
534            const int4 x = xv[(size_t) c * (n_in / 16) + st * 32];
535            int xsum = STRATA_DP4A(0x01010101, x.x, 0);
536            xsum = STRATA_DP4A(0x01010101, x.y, xsum);
537            xsum = STRATA_DP4A(0x01010101, x.z, xsum);
538            xsum = STRATA_DP4A(0x01010101, x.w, xsum);
539#pragma unroll
540            for (int r = 0; r < R; ++r) {
541                int isum = STRATA_DP4A(w[r].x, x.x, 0);
542                isum = STRATA_DP4A(w[r].y, x.y, isum);
543                isum = STRATA_DP4A(w[r].z, x.z, isum);
544                isum = STRATA_DP4A(w[r].w, x.w, isum);
545                acc[r][c] = fmaf(dw[r] * xs[c], (float) (isum - 8 * xsum), acc[r][c]);
546            }
547        }
548    }
549#pragma unroll
550    for (int r = 0; r < R; ++r)
551#pragma unroll
552        for (int c = 0; c < 8; ++c) {
553            float v = acc[r][c];
554            v += __shfl_xor_sync(0xffffffffu, v, 16);
555            v += __shfl_xor_sync(0xffffffffu, v, 8);
556            v += __shfl_xor_sync(0xffffffffu, v, 4);
557            v += __shfl_xor_sync(0xffffffffu, v, 2);
558            v += __shfl_xor_sync(0xffffffffu, v, 1);
559            if (lane == 0 && c < ncols) sg.y[(size_t) c * sg.n_out + row0 + sub * R + r] = v;
560        }
561}
562
563// quantize one 32-block of one row to the planar activation layout (a warp: lane = element)
564__device__ __forceinline__ void quant_block(float v, int blk, int col, int K, int8_t* __restrict__ xq, float* __restrict__ xd) {
565    const int lane = threadIdx.x & 31;
566    float amax = fabsf(v);
567    for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
568    const float d = amax / 127.0f;
569    const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
570    const int q = __float2int_rn(v * inv);
571    xq[(size_t) col * K + blk * 32 + lane] = (int8_t) q;
572    if (lane == 0) xd[(size_t) col * (K / 32) + blk] = d;
573}
574
575// rows [ncols][K] -> planar; grid (ceil(K / 32 / 8), ncols), 256 threads (a warp per block)
576__global__ void quant_rows_kernel(const float* __restrict__ x, int K, int8_t* __restrict__ xq, float* __restrict__ xd) {
577    const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), col = blockIdx.y, lane = threadIdx.x & 31;
578    if (blk * 32 >= K) return;
579    quant_block(x[(size_t) col * K + blk * 32 + lane], blk, col, K, xq, xd);
580}
581
582// RMS norm of row `col` (N values) then the planar quantization of the normalized values; also writes them when xn != null.  One block of 256 per row.
583__global__ void rms_quant_kernel(const float* __restrict__ h, const float* __restrict__ gamma, float* __restrict__ xn, int N, float eps,
584                                 int8_t* __restrict__ xq, float* __restrict__ xd) {
585    const int col = blockIdx.x, tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
586    __shared__ float red[8];
587    float ss = 0.0f;
588    for (int i = tid; i < N; i += 256) { const float v = h[(size_t) col * N + i]; ss += v * v; }
589    for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o);
590    if (lane == 0) red[warp] = ss;
591    __syncthreads();
592    float tot = 0.0f;
593    for (int w = 0; w < 8; ++w) tot += red[w];
594    const float scale = rsqrtf(tot / (float) N + eps);
595    for (int blk = warp; blk * 32 < N; blk += 8) {
596        const int i = blk * 32 + lane;
597        const float v = h[(size_t) col * N + i] * scale * gamma[i];
598        if (xn) xn[(size_t) col * N + i] = v;
599        quant_block(v, blk, col, N, xq, xd);
600    }
601}
602
603// conv (as conv_kernel, no residual) then the planar quantization: grid (ceil(H / 32 / 8), rows), 256 threads
604__global__ void conv_quant_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base, int H, int group,
605                                  int8_t* __restrict__ xq, float* __restrict__ xd) {
606    const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), b = blockIdx.y, lane = threadIdx.x & 31;
607    if (blk * 32 >= H) return;
608    const int c = blk * 32 + lane, groups = H / group;
609    float acc = 0.0f;
610#pragma unroll
611    for (int o = 0; o < 2; ++o) {
612        if (b - o < 0) continue;
613        const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
614        acc = fmaf(k, x[(size_t) (b - o) * H + c], acc);
615    }
616    quant_block(acc, blk, b, H, xq, xd);
617}
618
619// h += conv(x) (the finish convolution with its residual), then RMS norm of the new h with `gamma` -> xn (optional) and the planar quantization.
620// One block of 1024 threads per row: a warp owns whole 32-blocks (80 of them for 2560), so the quantization needs no exchange.
621__global__ void __launch_bounds__(1024) conv_rms_quant_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base,
622                                                              float* __restrict__ h, const float* __restrict__ gamma, float* __restrict__ xn, int H, int group,
623                                                              float eps, int8_t* __restrict__ xq, float* __restrict__ xd) {
624    const int b = blockIdx.x, warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
625    const int groups = H / group, nb = H / 32;
626    __shared__ float red[32];
627    float v[3];
628    float ss = 0.0f;
629#pragma unroll
630    for (int j = 0; j < 3; ++j) {
631        const int blk = warp + j * 32;
632        v[j] = 0.0f;
633        if (blk < nb) {
634            const int c = blk * 32 + lane;
635            float acc = 0.0f;
636#pragma unroll
637            for (int o = 0; o < 2; ++o) {
638                if (b - o < 0) continue;
639                const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group];
640                acc = fmaf(k, x[(size_t) (b - o) * H + c], acc);
641            }
642            v[j] = h[(size_t) b * H + c] + acc;
643            h[(size_t) b * H + c] = v[j];
644            ss += v[j] * v[j];
645        }
646    }
647    for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o);
648    if (lane == 0) red[warp] = ss;
649    __syncthreads();
650    float tot = 0.0f;
651    for (int w = 0; w < 32; ++w) tot += red[w];
652    const float scale = rsqrtf(tot / (float) H + eps);
653#pragma unroll
654    for (int j = 0; j < 3; ++j) {
655        const int blk = warp + j * 32;
656        if (blk < nb) {
657            const int c = blk * 32 + lane;
658            const float y = v[j] * scale * gamma[c];
659            if (xn) xn[(size_t) b * H + c] = y;
660            quant_block(y, blk, b, H, xq, xd);
661        }
662    }
663}
664
665// q and k of the block: per (row, head) RMS norm and rope; blockIdx.y < q_heads is a q head (-> qo, row-major rows), the rest k heads (-> ko)
666__global__ void norm_rope_qk_kernel(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ gq, const float* __restrict__ gk,
667                                    const float* __restrict__ table, float* __restrict__ qo, float* __restrict__ ko, int q_heads, int k_heads, float eps) {
668    const int r = blockIdx.x, hh = blockIdx.y, d = threadIdx.x;
669    const bool isq = hh < q_heads;
670    const int h = isq ? hh : hh - q_heads, heads = isq ? q_heads : k_heads;
671    const float* in = isq ? q : k;
672    const float* gamma = isq ? gq : gk;
673    float* out = isq ? qo : ko;
674    __shared__ float red[4];
675    __shared__ float y[HD];
676    const float x = in[((size_t) r * heads + h) * HD + d];
677    float ss = x * x;
678    for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o);
679    if ((d & 31) == 0) red[d >> 5] = ss;
680    __syncthreads();
681    const float v = x * rsqrtf((red[0] + red[1] + red[2] + red[3]) / (float) HD + eps) * gamma[d];
682    y[d] = v;
683    __syncthreads();
684    const int i = d & 63;
685    const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i];
686    out[((size_t) r * heads + h) * HD + d] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn;
687}
688
689// 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
690__global__ void kv_ring_kernel(const float* __restrict__ kin, const float* __restrict__ vin, const float* __restrict__ gk, const int32_t* __restrict__ pos,
691                               const float* __restrict__ table, float* __restrict__ kring, float* __restrict__ vring, int slots, int heads, float eps,
692                               int64_t* __restrict__ tag, const int32_t* __restrict__ epoch_ptr) {
693    const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x;
694    __shared__ float red[4];
695    __shared__ float y[HD];
696    const float x = kin[((size_t) r * heads + h) * HD + d];
697    float ss = x * x;
698    for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o);
699    if ((d & 31) == 0) red[d >> 5] = ss;
700    __syncthreads();
701    const float v = x * rsqrtf((red[0] + red[1] + red[2] + red[3]) / (float) HD + eps) * gk[d];
702    y[d] = v;
703    __syncthreads();
704    const int i = d & 63;
705    const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i];
706    const int slot = (int) (pos[r] % slots);
707    const size_t at = ((size_t) h * slots + slot) * HD + d;
708    kring[at] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn;
709    vring[at] = vin[((size_t) r * heads + h) * HD + d];
710    if (tag != nullptr && h == 0 && d == 0) tag[slot] = ((int64_t) *epoch_ptr << 32) | (int64_t) pos[r];
711}
712
713// silu(gate) * up then the planar quantization: grid (ceil(I / 32 / 8), rows), 256 threads
714__global__ void swiglu_quant_kernel(const float* __restrict__ gate, const float* __restrict__ up, int I, int8_t* __restrict__ xq, float* __restrict__ xd) {
715    const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), b = blockIdx.y, lane = threadIdx.x & 31;
716    if (blk * 32 >= I) return;
717    const size_t i = (size_t) b * I + blk * 32 + lane;
718    const float g = gate[i];
719    quant_block(g / (1.0f + __expf(-g)) * up[i], blk, b, I, xq, xd);
720}
721
722// GGUF Q8_0 blocks (34 bytes: fp16 d, 32 int8) of a [n_out][n_in] matrix -> the tiled qs plane (n_out * n_in bytes) and the tiled d plane; one thread per block
723__global__ void q8_tile_kernel(const uint8_t* __restrict__ blocks, int8_t* __restrict__ qs, __half* __restrict__ dpl, int n_in, int64_t count) {
724    const int64_t b = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
725    if (b >= count) return;
726    const int nb = n_in / 32;
727    const int64_t row = b / nb;
728    const int blk = (int) (b % nb);
729    const int64_t g = row / 8;
730    const int r = (int) (row % 8), st = blk / 16, bi = blk % 16;
731    const uint8_t* src = blocks + b * 34;
732    const uint16_t dh = (uint16_t) src[0] | ((uint16_t) src[1] << 8);
733    dpl[(g * 8 * nb) + (int64_t) st * 128 + r * 16 + bi] = __ushort_as_half(dh);
734    int8_t* o = qs + g * 8 * n_in + (int64_t) st * 4096 + r * 512 + bi * 32;
735    for (int i = 0; i < 32; ++i) o[i] = (int8_t) src[2 + i];
736}
737
738// 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
739// nibble plane (n_out * n_in / 2 bytes, the layout above) and the tiled d plane; one thread per block
740__global__ void q4_tile_kernel(const uint8_t* __restrict__ blocks, uint8_t* __restrict__ qs, __half* __restrict__ dpl, int n_in, int64_t count) {
741    const int64_t b = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
742    if (b >= count) return;
743    const int nb = n_in / 32;
744    const int64_t row = b / nb;
745    const int blk = (int) (b % nb);
746    const int64_t g = row / 8;
747    const int r = (int) (row % 8), st = blk / 16, bi = blk % 16;
748    const uint8_t* src = blocks + b * 18;
749    const uint16_t dh = (uint16_t) src[0] | ((uint16_t) src[1] << 8);
750    dpl[(g * 8 * nb) + (int64_t) st * 128 + r * 16 + bi] = __ushort_as_half(dh);
751    for (int half = 0; half < 2; ++half) {   // values half * 16 .. +15 of the block
752        uint32_t wd[2];
753        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
754            uint32_t v = 0;
755            for (int p = 0; p < 4; ++p) {
756                const uint8_t b_lo = src[2 + w * 8 + p], b_hi = src[2 + w * 8 + 4 + p];
757                const uint32_t q_lo = half == 0 ? (b_lo & 15u) : (b_lo >> 4), q_hi = half == 0 ? (b_hi & 15u) : (b_hi >> 4);
758                v |= (q_lo | (q_hi << 4)) << (p * 8);
759            }
760            wd[w] = v;
761        }
762        uint8_t* o = qs + g * 8 * (n_in / 2) + (int64_t) st * 2048 + r * 256 + (bi * 2 + half) * 8;
763        *reinterpret_cast<uint2*>(o) = make_uint2(wd[0], wd[1]);
764    }
765}
766
767// ---- top-16
768constexpr int TK_CHUNK_MAX = 4096;
769__device__ __forceinline__ bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); }
770
771__global__ void topk_part_kernel(const float* __restrict__ logits, int n, float* __restrict__ cval, int32_t* __restrict__ cidx) {
772    __shared__ float vals[TK_CHUNK_MAX];
773    __shared__ float wv[8];
774    __shared__ int wi[8];
775    __shared__ int win;
776    const int row = blockIdx.x, blk = blockIdx.y, tid = threadIdx.x;
777    const int cs = (n + kDf2TopBlocks - 1) / kDf2TopBlocks;
778    const int c0 = blk * cs, c1 = min(c0 + cs, n);
779    for (int i = tid; i < cs; i += 256) vals[i] = (c0 + i < c1) ? logits[(size_t) row * n + c0 + i] : -INFINITY;
780    __syncthreads();
781    for (int k = 0; k < kDf2TopK; ++k) {
782        float bv = -INFINITY;
783        int bi = 0x7fffffff;
784        for (int i = tid; i < cs; i += 256)
785            if (better(vals[i], i, bv, bi)) { bv = vals[i]; bi = i; }
786        for (int o = 16; o > 0; o >>= 1) {
787            const float ov = __shfl_xor_sync(0xffffffffu, bv, o);
788            const int oi = __shfl_xor_sync(0xffffffffu, bi, o);
789            if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; }
790        }
791        if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; }
792        __syncthreads();
793        if (tid == 0) {
794            float v = wv[0];
795            int ix = wi[0];
796            for (int w = 1; w < 8; ++w)
797                if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; }
798            const size_t o = ((size_t) row * kDf2TopBlocks + blk) * kDf2TopK + k;
799            cval[o] = v;
800            cidx[o] = v == -INFINITY ? -1 : c0 + ix;
801            win = ix;
802            if (v != -INFINITY) vals[ix] = -INFINITY;
803        }
804        __syncthreads();
805    }
806}
807
808__global__ void topk_merge_kernel(const float* __restrict__ cval, const int32_t* __restrict__ cidx, const int32_t* __restrict__ idx_map,
809                                  float* __restrict__ val, int32_t* __restrict__ tok) {
810    constexpr int NC = kDf2TopBlocks * kDf2TopK;
811    __shared__ float sv[NC];
812    __shared__ int si[NC];
813    __shared__ float wv[8];
814    __shared__ int wi[8], wp[8];
815    const int row = blockIdx.x, tid = threadIdx.x;
816    for (int i = tid; i < NC; i += 256) { sv[i] = cval[(size_t) row * NC + i]; si[i] = cidx[(size_t) row * NC + i]; }
817    __syncthreads();
818    for (int k = 0; k < kDf2TopK; ++k) {
819        float bv = -INFINITY;
820        int bi = 0x7fffffff, bp = -1;
821        for (int i = tid; i < NC; i += 256)
822            if (si[i] >= 0 && better(sv[i], si[i], bv, bi)) { bv = sv[i]; bi = si[i]; bp = i; }
823        for (int o = 16; o > 0; o >>= 1) {
824            const float ov = __shfl_xor_sync(0xffffffffu, bv, o);
825            const int oi = __shfl_xor_sync(0xffffffffu, bi, o);
826            const int op = __shfl_xor_sync(0xffffffffu, bp, o);
827            if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; bp = op; }
828        }
829        if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; wp[tid >> 5] = bp; }
830        __syncthreads();
831        if (tid == 0) {
832            float v = wv[0];
833            int ix = wi[0], p = wp[0];
834            for (int w = 1; w < 8; ++w)
835                if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; p = wp[w]; }
836            if (p >= 0) { si[p] = -1; }
837            val[row * kDf2TopK + k] = v;
838            tok[row * kDf2TopK + k] = p >= 0 ? (idx_map ? idx_map[ix] : ix) : 0;
839        }
840        __syncthreads();
841    }
842}
843
844// one value / eight values of a ggml Q4_0 row of 256 (8 blocks of 18 bytes: fp16 d, then 16 bytes with value i in the low nibble of byte i and value i + 16 in the high one)
845__device__ __forceinline__ float q4row_at(const uint8_t* row, int i) {
846    const uint8_t* blk = row + (size_t) (i >> 5) * 18;
847    const float d = __half2float(__ushort_as_half(*reinterpret_cast<const uint16_t*>(blk)));
848    const int j = i & 31, byte = blk[2 + (j & 15)];
849    return (float) ((j < 16 ? (byte & 15) : (byte >> 4)) - 8) * d;
850}
851
852// ---- the selector's walk: one block of 256 threads
853template <bool Q4>
854__global__ void select_kernel(const float* __restrict__ hp, const float* __restrict__ unary, const int32_t* __restrict__ tok,
855                              const uint16_t* __restrict__ pred_cb, const uint16_t* __restrict__ succ_cb, int rank, int rows,
856                              const int32_t* __restrict__ anchor_tok, int32_t* __restrict__ out_tok, float* __restrict__ out_prob) {
857    __shared__ float vp[256];
858    __shared__ float sc[kDf2TopK];
859    __shared__ int prev;
860    const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31;
861    if (tid == 0) prev = *anchor_tok;
862    __syncthreads();
863    for (int i = 0; i < rows; ++i) {
864        if (Q4) vp[tid] = q4row_at(reinterpret_cast<const uint8_t*>(pred_cb) + (size_t) prev * (rank / 32 * 18), tid) * hp[(size_t) i * rank + tid];
865        else vp[tid] = bf16f(pred_cb[(size_t) prev * rank + tid]) * hp[(size_t) i * rank + tid];
866        __syncthreads();
867        for (int j = w * 2; j < w * 2 + 2; ++j) {
868            const int t = tok[i * kDf2TopK + j];
869            float acc = 0.0f;
870            if (Q4) {
871                const uint8_t* row = reinterpret_cast<const uint8_t*>(succ_cb) + (size_t) t * (rank / 32 * 18);
872#pragma unroll
873                for (int e = 0; e < 8; ++e) acc = fmaf(q4row_at(row, lane * 8 + e), vp[lane * 8 + e], acc);
874            } else {
875                const uint4 raw = *reinterpret_cast<const uint4*>(succ_cb + (size_t) t * rank + lane * 8);
876                const uint32_t u[4] = {raw.x, raw.y, raw.z, raw.w};
877#pragma unroll
878                for (int e = 0; e < 4; ++e) {
879                    acc = fmaf(__uint_as_float(u[e] << 16), vp[lane * 8 + e * 2], acc);
880                    acc = fmaf(__uint_as_float(u[e] & 0xffff0000u), vp[lane * 8 + e * 2 + 1], acc);
881                }
882            }
883            for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o);
884            if (lane == 0) sc[j] = unary[i * kDf2TopK + j] + acc;
885        }
886        __syncthreads();
887        if (tid == 0) {
888            int bj = 0;
889            float bv = sc[0];
890            for (int j = 1; j < kDf2TopK; ++j)
891                if (sc[j] > bv) { bv = sc[j]; bj = j; }
892            float z = 0.0f;
893            for (int j = 0; j < kDf2TopK; ++j) z += __expf(sc[j] - bv);
894            out_tok[i] = tok[i * kDf2TopK + bj];
895            out_prob[i] = 1.0f / z;
896            prev = out_tok[i];
897        }
898        __syncthreads();
899    }
900}
901
902__global__ void tap_rows_kernel(const float* __restrict__ R, float* __restrict__ out, int64_t out_stride, int64_t n, int hc) {
903    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
904    const int r = blockIdx.y;
905    if (i >= n) return;
906    float s = 0.0f;
907    for (int c = 0; c < hc; ++c) s += R[((size_t) r * hc + c) * n + i];
908    out[(size_t) r * out_stride + i] = s / (float) hc;
909}
910
911__global__ void tap_gr_kernel(const float* __restrict__ R, int64_t R_stride, const float* __restrict__ bo, int64_t bo_stride,
912                              const float* __restrict__ inject, int64_t inj_stride, float* __restrict__ out, int64_t out_stride, int64_t n, int hc) {
913    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
914    const int r = blockIdx.y;
915    if (i >= n) return;
916    float wsum = 0.0f, rs = 0.0f;
917    for (int c = 0; c < hc; ++c) {
918        const float x = inject[(size_t) r * inj_stride + c] / (float) hc;
919        wsum += 2.0f / (1.0f + expf(-x));
920        rs += R[(size_t) r * R_stride + (size_t) c * n + i];
921    }
922    out[(size_t) r * out_stride + i] = (rs + bo[(size_t) r * bo_stride + i] * wsum) / (float) hc;
923}
924
925}  // namespace
926
927void 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,
928                int rows, int64_t n_embd, int hc, void* stream) {
929    tap_gr_kernel<<<dim3((unsigned) ((n_embd + 255) / 256), rows), 256, 0, (cudaStream_t) stream>>>(R, R_stride, bo, bo_stride, inject, inj_stride, out,
930                                                                                                  out_stride, n_embd, hc);
931    check("tap_gr");
932}
933
934void 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,
935              void* stream) {
936    const int n = rows * H;
937    conv_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(x, dyn, dyn_stride, base, resid, out, rows, H, group);
938    check("conv");
939}
940
941void df2_rope_table(const int32_t* pos, int rows, float theta, float* table, void* stream) {
942    rope_table_kernel<<<rows, 64, 0, (cudaStream_t) stream>>>(pos, rows, theta, table);
943    check("rope_table");
944}
945
946void 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,
947                   int rows, int heads, float eps, void* stream) {
948    norm_rope_kernel<<<dim3(rows, heads), HD, 0, (cudaStream_t) stream>>>(in, in_stride, gamma, pos, rope_table, out, slot_mod, heads, eps);
949    check("norm_rope");
950}
951
952void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod, int rows, int cols, void* stream) {
953    const int n = rows * cols;
954    copy_rows_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(in, out, pos, slot_mod, rows, cols);
955    check("copy_rows");
956}
957
958void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos,
959                   int ring_slots, int window, float* part, void* xq, float* xd, void* stream, const int64_t* tag, const int32_t* epoch) {
960    attn_part_kernel<<<dim3(kDf2Kv, kDf2MaxChunks), 128, 0, (cudaStream_t) stream>>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part, g_attn_variant, tag, epoch);
961    check("attn_part");
962    attn_merge_kernel<<<kDf2Kv * 32, HD, 0, (cudaStream_t) stream>>>(part, static_cast<int8_t*>(xq), xd);
963    check("attn_merge");
964}
965
966void 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,
967                        float eps, void* xq, float* xd, void* stream) {
968    if (H > 3 * 1024) throw std::invalid_argument("df2_conv_rms_quant: H too large");
969    conv_rms_quant_kernel<<<rows, 1024, 0, (cudaStream_t) stream>>>(x, dyn, dyn_stride, base, h, gamma, xn, H, group, eps, static_cast<int8_t*>(xq), xd);
970    check("conv_rms_quant");
971}
972
973void 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,
974                      float eps, void* stream) {
975    norm_rope_qk_kernel<<<dim3(rows, q_heads + k_heads), HD, 0, (cudaStream_t) stream>>>(q, k, gq, gk, table, qo, ko, q_heads, k_heads, eps);
976    check("norm_rope_qk");
977}
978
979void 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,
980                 int heads, float eps, void* stream, int64_t* tag, const int32_t* epoch) {
981    kv_ring_kernel<<<dim3(rows, heads), HD, 0, (cudaStream_t) stream>>>(kin, vin, gk, pos, table, kring, vring, slots, heads, eps, tag, epoch);
982    check("kv_ring");
983}
984
985void df2_rope_inv(float theta, double* inv, void* stream) {
986    rope_inv_kernel<<<1, 64, 0, (cudaStream_t) stream>>>(theta, inv);
987    check("rope_inv");
988}
989
990void df2_rope_table_inv(const int32_t* pos, int rows, const double* inv, float* table, void* stream) {
991    rope_table_inv_kernel<<<rows, 64, 0, (cudaStream_t) stream>>>(pos, rows, inv, table);
992    check("rope_table_inv");
993}
994
995void df2_gemm_variant(int v) { g_gemm_variant = v; }
996void df2_attention_variant(int v) { g_attn_variant = v; }
997
998// The Q4_0 variant by matrix size (rows = all the launch's output rows).  17 (two warps a block, two rows a warp, unroll 2): dflash2_gemm_bench q4 best on l620 (sm_120,
999// 110 SMs) for every matrix, within 0-2 us of the best on a 188-SM RTX PRO 6000.  gfx12 (R9700, gfx1201, p620, 8 columns, cold weights, two bench runs): the same shape with unroll 1
1000// (26) is 25-45% faster on every matrix of 1000 rows and more (gate+up 56 -> 44.5 us, down 39 -> 23.4, qkv 26.8 -> 21.4, o 23.6 -> 14.9, fc 61.5 -> 35.2, kv 15.2 -> 10.0), and one
1001// warp a row with unroll 1 (31) is 2x faster on the 256 and 640 row matrices (akp / mkp 12.1 -> 6.3 us, selector 11.1 -> 5.2); all bitwise the same results.
1002static int df2_q4_auto(int rows) {
1003#if defined(STRATA_USE_HIP)
1004    static const bool gfx12 = [] {
1005        int dev = 0;
1006        cudaDeviceProp p;
1007        return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName);
1008    }();
1009    if (gfx12) return rows <= 640 ? 31 : 26;
1010#endif
1011    (void) rows;
1012    return 17;
1013}
1014#ifndef DF2_Q4_AUTO
1015#define DF2_Q4_AUTO(rows) df2_q4_auto(rows)
1016#endif
1017void df2_gemm(const Df2Mat* mats, int n, const void* xq, const float* xd, int n_in, int ncols, void* stream) {
1018    if (n < 1 || n > 3 || n_in % 512 != 0 || ncols < 1 || ncols > 8) throw std::invalid_argument("df2_gemm: unsupported shape");
1019    Df2Segs segs;
1020    int rows = 0;
1021    for (int i = 0; i < n; ++i) {
1022        if (mats[i].n_out % 16 != 0) throw std::invalid_argument("df2_gemm: n_out must be a multiple of 16");
1023        if (mats[i].q4 != mats[0].q4) throw std::invalid_argument("df2_gemm: one launch, one weight format");
1024        const int8_t* q = static_cast<const int8_t*>(mats[i].w);
1025        segs.s[i] = Df2Seg{q, reinterpret_cast<const __half*>(q + (size_t) mats[i].n_out * n_in / (mats[i].q4 ? 2 : 1)), mats[i].y, mats[i].n_out, rows};
1026        rows += mats[i].n_out;
1027    }
1028    segs.n = n;
1029    const int8_t* xqp = static_cast<const int8_t*>(xq);
1030    cudaStream_t st = (cudaStream_t) stream;
1031    if (mats[0].q4) {   // the Q4_0 pack: 4 warps a block when the rows allow, else 2; the rows-a-warp variants (bitwise the same results) by matrix size
1032        static const int tune4 = [] { const char* e = std::getenv("STRATA_DF2_GEMM4"); return e ? std::atoi(e) : 0; }();   // 0: the table; 1: 8 rows a warp as before; 10 and up: that variant for every matrix (bench / A/B)
1033        int v4 = g_gemm_variant != 0 ? g_gemm_variant : tune4 >= 10 ? tune4 : tune4 != 0 ? 1 : DF2_Q4_AUTO(rows);
1034#define DF2_ROWS4_CASE(V, W, R, U) case V: gemm4_rows_kernel<W, R, U><<<(rows / 8) * (8 / R) / W, W * 32, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1035        switch (v4) {
1036            DF2_ROWS4_CASE(10, 4, 4, 2)
1037            DF2_ROWS4_CASE(11, 4, 2, 2)
1038            DF2_ROWS4_CASE(12, 4, 1, 2)
1039            DF2_ROWS4_CASE(13, 8, 2, 2)
1040            DF2_ROWS4_CASE(14, 8, 1, 2)
1041            DF2_ROWS4_CASE(15, 4, 2, 4)
1042            DF2_ROWS4_CASE(16, 4, 1, 4)
1043            DF2_ROWS4_CASE(17, 2, 2, 2)
1044            DF2_ROWS4_CASE(18, 8, 1, 4)
1045            DF2_ROWS4_CASE(19, 4, 4, 4)
1046            DF2_ROWS4_CASE(20, 4, 1, 8)
1047            DF2_ROWS4_CASE(21, 8, 1, 8)
1048            DF2_ROWS4_CASE(22, 8, 2, 4)
1049            DF2_ROWS4_CASE(23, 2, 1, 4)
1050            DF2_ROWS4_CASE(24, 1, 2, 2)
1051            DF2_ROWS4_CASE(25, 1, 4, 2)
1052            DF2_ROWS4_CASE(26, 2, 2, 1)
1053            DF2_ROWS4_CASE(27, 2, 4, 2)
1054            DF2_ROWS4_CASE(28, 1, 1, 2)
1055            DF2_ROWS4_CASE(29, 1, 2, 4)
1056            DF2_ROWS4_CASE(30, 2, 2, 4)
1057            DF2_ROWS4_CASE(31, 1, 1, 1)
1058            DF2_ROWS4_CASE(32, 1, 1, 4)
1059            DF2_ROWS4_CASE(33, 1, 1, 8)
1060            DF2_ROWS4_CASE(34, 2, 1, 2)
1061            DF2_ROWS4_CASE(35, 4, 1, 2)
1062            DF2_ROWS4_CASE(36, 4, 2, 1)
1063            DF2_ROWS4_CASE(37, 8, 2, 1)
1064            DF2_ROWS4_CASE(38, 2, 1, 1)
1065            DF2_ROWS4_CASE(39, 4, 1, 1)
1066            DF2_ROWS4_CASE(40, 1, 2, 1)
1067            DF2_ROWS4_CASE(41, 1, 4, 1)
1068            DF2_ROWS4_CASE(42, 2, 4, 1)
1069            DF2_ROWS4_CASE(43, 4, 4, 1)
1070            DF2_ROWS4_CASE(44, 8, 1, 1)
1071            DF2_ROWS4_CASE(45, 1, 8, 1)
1072            case 2: gemm4_kernel<2><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1073            default: if (rows % 32 == 0) gemm4_kernel<4><<<rows / 32, 128, 0, st>>>(segs, xqp, xd, n_in, ncols);
1074                     else gemm4_kernel<2><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols);
1075                     break;
1076        }
1077        check("gemm4");
1078        return;
1079    }
1080    static const int tune = [] { const char* e = std::getenv("STRATA_DF2_GEMM"); return e ? std::atoi(e) : 1; }();   // 1 (default): rows a warp by matrix size, bitwise the same results; 0: 8 rows a warp as before
1081    const int variant = g_gemm_variant != 0 ? g_gemm_variant
1082                        : tune == 0         ? (rows % 32 == 0 ? 1 : 2)
1083                        : rows <= 1024      ? 20
1084                        : rows <= 3072      ? 13
1085                        : rows >= 15000     ? 10
1086                                            : (rows % 32 == 0 ? 1 : 2);
1087#define DF2_ROWS_CASE(V, W, R, U) case V: gemm_rows_kernel<W, R, U><<<(rows / 8) * (8 / R) / W, W * 32, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1088    switch (variant) {
1089        DF2_ROWS_CASE(10, 4, 4, 2)
1090        DF2_ROWS_CASE(11, 4, 2, 2)
1091        DF2_ROWS_CASE(12, 4, 1, 2)
1092        DF2_ROWS_CASE(13, 8, 2, 2)
1093        DF2_ROWS_CASE(14, 8, 1, 2)
1094        DF2_ROWS_CASE(15, 4, 2, 4)
1095        DF2_ROWS_CASE(16, 4, 1, 4)
1096        DF2_ROWS_CASE(17, 2, 2, 2)
1097        DF2_ROWS_CASE(18, 8, 1, 4)
1098        DF2_ROWS_CASE(19, 4, 4, 4)
1099        DF2_ROWS_CASE(20, 4, 1, 8)
1100        DF2_ROWS_CASE(21, 8, 1, 8)
1101        DF2_ROWS_CASE(22, 8, 2, 4)
1102        DF2_ROWS_CASE(23, 2, 1, 4)
1103        case 3: gemm8_kernel<2, false><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1104        case 4: gemm8_kernel<1, true, 2><<<rows / 8, 32, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1105        case 5: gemm8_kernel<2, true, 1><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1106        case 6: gemm8_kernel<2, true, 4><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1107        case 7: gemm8_kernel<4, true, 4><<<rows / 32, 128, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1108        case 8: gemm8_kernel<8, true, 2><<<rows / 64, 256, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1109        case 9: gemm8_kernel<4, false><<<rows / 32, 128, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1110        case 2: gemm8_kernel<2, true><<<rows / 16, 64, 0, st>>>(segs, xqp, xd, n_in, ncols); break;   // 16 rows a block: every n_out is a multiple of 16
1111        default: gemm8_kernel<4, true><<<rows / 32, 128, 0, st>>>(segs, xqp, xd, n_in, ncols); break;
1112    }
1113    check("gemm8");
1114}
1115
1116void df2_q4_tile(const void* blocks, void* qs, void* dpl, int n_in, int64_t count, void* stream) {
1117    q4_tile_kernel<<<(unsigned) ((count + 255) / 256), 256, 0, (cudaStream_t) stream>>>(static_cast<const uint8_t*>(blocks), static_cast<uint8_t*>(qs),
1118                                                                                         static_cast<__half*>(dpl), n_in, count);
1119    check("q4_tile");
1120}
1121
1122void df2_quant_rows(const float* x, int K, int ncols, void* xq, float* xd, void* stream) {
1123    quant_rows_kernel<<<dim3((K / 32 + 7) / 8, ncols), 256, 0, (cudaStream_t) stream>>>(x, K, static_cast<int8_t*>(xq), xd);
1124    check("quant_rows");
1125}
1126
1127void df2_rms_quant(const float* h, const float* gamma, float* xn, int rows, int N, float eps, void* xq, float* xd, void* stream) {
1128    rms_quant_kernel<<<rows, 256, 0, (cudaStream_t) stream>>>(h, gamma, xn, N, eps, static_cast<int8_t*>(xq), xd);
1129    check("rms_quant");
1130}
1131
1132void 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) {
1133    conv_quant_kernel<<<dim3((H / 32 + 7) / 8, rows), 256, 0, (cudaStream_t) stream>>>(x, dyn, dyn_stride, base, H, group, static_cast<int8_t*>(xq), xd);
1134    check("conv_quant");
1135}
1136
1137void df2_swiglu_quant(const float* gate, const float* up, int rows, int I, void* xq, float* xd, void* stream) {
1138    swiglu_quant_kernel<<<dim3((I / 32 + 7) / 8, rows), 256, 0, (cudaStream_t) stream>>>(gate, up, I, static_cast<int8_t*>(xq), xd);
1139    check("swiglu_quant");
1140}
1141
1142void df2_q8_tile(const void* blocks, void* qs, void* dpl, int n_in, int64_t count, void* stream) {
1143    q8_tile_kernel<<<(unsigned) ((count + 255) / 256), 256, 0, (cudaStream_t) stream>>>(static_cast<const uint8_t*>(blocks), static_cast<int8_t*>(qs),
1144                                                                                      static_cast<__half*>(dpl), n_in, count);
1145    check("q8_tile");
1146}
1147
1148void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream) {
1149    if ((n + kDf2TopBlocks - 1) / kDf2TopBlocks > TK_CHUNK_MAX) throw std::invalid_argument("df2_topk: too many logits per row");
1150    float* cval = reinterpret_cast<float*>(scratch);
1151    int32_t* cidx = reinterpret_cast<int32_t*>(scratch + (size_t) rows * kDf2TopBlocks * kDf2TopK);
1152    topk_part_kernel<<<dim3(rows, kDf2TopBlocks), 256, 0, (cudaStream_t) stream>>>(logits, n, cval, cidx);
1153    check("topk_part");
1154    topk_merge_kernel<<<rows, 256, 0, (cudaStream_t) stream>>>(cval, cidx, idx_map, val, tok);
1155    check("topk_merge");
1156}
1157
1158void 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,
1159                const int32_t* anchor_tok, int32_t* out_tok, float* out_prob, void* stream, bool cb_q4) {
1160    if (rank != 256) throw std::invalid_argument("df2_select: the selector rank must be 256");
1161    if (cb_q4) select_kernel<true><<<1, 256, 0, (cudaStream_t) stream>>>(hp, unary, tok, pred_cb, succ_cb, rank, rows, anchor_tok, out_tok, out_prob);
1162    else select_kernel<false><<<1, 256, 0, (cudaStream_t) stream>>>(hp, unary, tok, pred_cb, succ_cb, rank, rows, anchor_tok, out_tok, out_prob);
1163    check("select");
1164}
1165
1166void df2_tap_rows(const float* R, float* out, int64_t out_stride, int64_t n_embd, int hc, int rows, void* stream) {
1167    tap_rows_kernel<<<dim3((unsigned) ((n_embd + 255) / 256), rows), 256, 0, (cudaStream_t) stream>>>(R, out, out_stride, n_embd, hc);
1168    check("tap_rows");
1169}
1170
1171}  // namespace strata::kernels