okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
24.8 KiB539 linesraw
1// Strata. The trellis routed experts (TQK6 / TQK7 / TQK5X / TQK4X / TQK5T / TQK4T, ds4_iq.cuh's is_tq) on the device for the
2// DeepSeek-V4.1 engine path.  The weights stay as the file has them (a row of k values = k / 128 blocks of {fp16 d; 4 K stream
3// bytes}); the blob in VRAM is the file's bytes, so the expert cache, the tensor-parallel cuts and the CPU lane read the same
4// layout.  Arithmetic as the CPU lane's (ds4_tq_cpu.cpp): the activations are int8 with an F32 scale per 32 values (the
5// engine's q8_quant), the weights exact (fp16 codebook values times the block's fp16 scale); the sums are F32.
6//
7// gfx12 (RDNA4, R9700): v_wmma_f32_16x16x16_f16.  The weights are the B operand (16 rows of a tile = the 16 columns, a lane
8// holds one row's 8 consecutive k), the activations the A operand (16 entries = the 16 rows, split x = hi + lo in two fp16
9// so the product keeps ~2^-22), D[entry][weight row] in F32: a lane holds the entries 8 kg .. 8 kg + 7 of its row, so the
10// block scale d is the lane's own.  Lane l = r + 16 kg owns row r and the 16 steps 16 kg .. 16 kg + 15 of every block, whose
11// 15-bit states are one 128-bit window of the stream (the tile code of tools/dsv41_lab/wmma_emu.hpp, checked there against a
12// double reference and on the card by tests/dsv41/tqw_hip_test.cpp).  Elsewhere the same lane mapping in plain FMAs.
13#include "ds4_iq.cuh"
14
15#include <cuda_fp16.h>
16
17#include "ggml-common-tq.h"   // tq_lut_f16 (the 2048-point codebook as fp16 bit patterns, __device__)
18
19#include <algorithm>
20#include <cstdint>
21#include <cstdio>
22#include <cstdlib>
23
24#if defined(STRATA_USE_HIP) && !defined(DS4_TQ_PORTABLE) && (defined(__GFX12__) || defined(__gfx1200__) || defined(__gfx1201__))
25#define DS4_TQ_WMMA 1
26#endif
27
28#if !defined(STRATA_USE_HIP) && defined(__CUDACC__)   // (HIP's non-sync shuffle name, for the portable lane on CUDA)
29#define __shfl_xor(v, m) __shfl_xor_sync(0xffffffffu, (v), (m))
30#endif
31namespace strata::ds4::gguf::iq::tq {
32namespace {
33
34constexpr int kWaves = 4, kThreads = kWaves * 32;   // a block: 4 waves, a wave = one 16-row tile of each matrix
35constexpr int kTileRows = 16;
36constexpr int kMaxEnt = 16;   // entries (columns) a pass
37
38#if defined(DS4_TQ_WMMA)
39typedef _Float16 half8_t __attribute__((ext_vector_type(8)));
40typedef float float8_t __attribute__((ext_vector_type(8)));
41#endif
42
43constexpr bool computed_code(int type) { return type == kTQK5X || type == kTQK4X; }
44
45// ---------------------------------------------------------------- the codebook and the stream
46// a step's 15-bit state -> the four weights as two words of two fp16 (lo, hi): w0 w1 | w2 w3
47template <bool COMPUTED>
48__device__ __forceinline__ void step_words(const uint32_t* lut, uint32_t s, uint32_t& w0, uint32_t& w1) {
49    if (COMPUTED) {
50        w0 = ((s * 89226354u + 64248484u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
51        w1 = ((s * 0x9E3779B1u + 0x7F4A7C15u) & 0x8FFF8FFFu) ^ 0x3B603B60u;
52    } else {
53        const uint32_t x = s * 0x9e3779b1u;
54        w0 = lut[x >> 21];
55        w1 = lut[(x >> 10) & 2047u];
56    }
57}
58__device__ __forceinline__ float half_bits_f(uint32_t b) { return __half2float(__ushort_as_half((unsigned short) b)); }
59
60// the 128-bit window of a lane's 16 steps in one block record: record = {u16 d; stream}, lane half kg takes stream bits
61// [(16 - 16 kg) K, (32 - 16 kg) K) plus the 15 - K bits after them (circular), so state(u), u = 0..15, is the 15 bits at
62// (15 - u) K of the window.
63template <int K>
64__device__ __forceinline__ void stream_window(const uint8_t* rec, int kg, uint64_t& lo, uint64_t& hi) {
65    const uint16_t* st = (const uint16_t*) (rec + 2);
66    constexpr int NW = (15 * K + 15 + 15) / 16;   // u16 words that hold 15 K + 15 bits
67    uint64_t w[2] = {0ull, 0ull};
68    if (kg == 1) {
69#pragma unroll
70        for (int i = 0; i < NW; ++i) w[i >> 2] |= (uint64_t) st[i] << (16 * (i & 3));
71    } else {   // the stream's upper half [16 K, 32 K) = K words; the bits past its end wrap to the stream's start
72        const uint16_t* up = st + K;
73#pragma unroll
74        for (int i = 0; i < K; ++i) w[i >> 2] |= (uint64_t) up[i] << (16 * (i & 3));
75        const uint64_t wrap = (uint64_t) st[0] & ((1ull << (15 - K)) - 1ull);   // 15 - K <= 11 bits: inside word 0
76        const int p = 16 * K;
77        w[p >> 6] |= wrap << (p & 63);   // (p & 63) + 15 - K <= 56: never past the word
78    }
79    lo = w[0];
80    hi = w[1];
81}
82__device__ __forceinline__ uint32_t state_at(uint64_t lo, uint64_t hi, int pos) {   // 15 bits at bit pos of the 128-bit window
83    uint64_t v;
84    if (pos + 15 <= 64) v = lo >> pos;
85    else if (pos >= 64) v = hi >> (pos - 64);
86    else v = (lo >> pos) | (hi << (64 - pos));
87    return (uint32_t) v & 0x7fffu;
88}
89
90// ---------------------------------------------------------------- activations: where a lane's 8 values of an entry come from
91// Each loader: valid(m) says entry m (this pass's column) exists; load8(m, k0, v) the 8 values k0..k0+7 as F32.
92struct ActQ8 {   // int8 rows with an F32 scale a 32: entry m = row rows[m] of q (n values a row), scales d (n / 32 a row)
93    const int8_t* q;
94    const float* d;
95    const int* rows;
96    int n;
97    __device__ __forceinline__ void load8(int m, int k0, float* v) const {
98        const size_t r = (size_t) rows[m];
99        const int2 w = *(const int2*) (q + r * n + k0);
100        const float sc = d[r * (n / 32) + (k0 >> 5)];
101        const int8_t* b = (const int8_t*) &w;
102#pragma unroll
103        for (int j = 0; j < 8; ++j) v[j] = (float) b[j] * sc;
104    }
105};
106struct ActF32 {   // F32 rows: entry m = row rows[m] (ld floats a row)
107    const float* x;
108    const int* rows;
109    size_t ld;
110    __device__ __forceinline__ void load8(int m, int k0, float* v) const {
111        const float4* p = (const float4*) (x + (size_t) rows[m] * ld + k0);
112        const float4 a = p[0], b = p[1];
113        v[0] = a.x; v[1] = a.y; v[2] = a.z; v[3] = a.w; v[4] = b.x; v[5] = b.y; v[6] = b.z; v[7] = b.w;
114    }
115};
116struct ActF16 {   // F16 rows: entry m = row rows[m] (ld halves a row)
117    const uint16_t* x;
118    const int* rows;
119    size_t ld;
120    __device__ __forceinline__ void load8(int m, int k0, float* v) const {
121        const uint4 w = *(const uint4*) (x + (size_t) rows[m] * ld + k0);
122        const uint32_t u[4] = {w.x, w.y, w.z, w.w};
123#pragma unroll
124        for (int j = 0; j < 4; ++j) {
125            v[2 * j] = half_bits_f(u[j] & 0xffffu);
126            v[2 * j + 1] = half_bits_f(u[j] >> 16);
127        }
128    }
129};
130
131// ---------------------------------------------------------------- the stream window by 32-bit loads
132// The same 128-bit window as stream_window, from aligned 32-bit loads (a record is 2 + 4 K bytes: its scale, then the stream, at
133// any 2-byte alignment): the array starts at the 4-byte floor of the record, the stream at bit 16 or 32 of it.  Loads past the
134// end of the record are skipped (the window bits above what a lane needs are junk anyway).
135template <int K>
136__device__ __forceinline__ void stream_window_u32(const uint8_t* rec, int kg, uint64_t& lo, uint64_t& hi) {
137    constexpr int bsz = 2 + 4 * K;
138    const uintptr_t ad = (uintptr_t) rec;
139    const uint32_t* pa = (const uint32_t*) (ad & ~(uintptr_t) 3);
140    const int off = 16 + 8 * (int) (ad & 3);                    // the stream's first bit in the array: 16 or 32
141    const int start = off + (kg ? 0 : 16 * K);
142    const int w0 = start >> 5, s = start & 31;
143    const int nwords = (int) (((ad & 3) + bsz + 3) >> 2);       // words that hold the record
144    uint32_t v[5];
145#pragma unroll
146    for (int i = 0; i < 5; ++i) v[i] = (w0 + i < nwords) ? pa[w0 + i] : 0u;
147    uint32_t r[4];
148#pragma unroll
149    for (int i = 0; i < 4; ++i) r[i] = (uint32_t) ((((uint64_t) v[i + 1] << 32) | v[i]) >> s);
150    lo = ((uint64_t) r[1] << 32) | r[0];
151    hi = ((uint64_t) r[3] << 32) | r[2];
152    if (!kg) {   // the upper half [16 K, 32 K) of the stream (16 K >= 64 bits); the bits past its end wrap to the stream's start
153        hi &= (1ull << (16 * K - 64)) - 1ull;
154        const uint32_t first = off == 16 ? (pa[0] >> 16) : pa[1];
155        const uint64_t wrap = (uint64_t) first & ((1ull << (15 - K)) - 1ull);
156        const int p = 16 * K - 64;
157        hi |= wrap << p;
158    }
159}
160
161// ---------------------------------------------------------------- NM 16-row tiles (matrices sharing the activations) over up to 16 entries
162// acc_out[mi][i] (i < 8) = D[entry 8 kg + i][row r] of matrix mi's tile: sum over the row's k values of x_entry * w, k % 128 == 0.
163// wrows[mi]: the tile's row r (this lane's) of matrix mi in the blob; nblk blocks.  The activation fragments are made once for all NM.
164template <int K, bool COMPUTED, int NM, bool WORDS, class Act>
165__device__ __forceinline__ void tile_dot(const uint8_t* const* wrows, int nblk, const uint32_t* lut, const Act& act, int ne,
166                                         float (*acc_out)[8]) {
167    constexpr int bsz = 2 + 4 * K;
168    const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4;
169    float tot[NM][8];
170#pragma unroll
171    for (int mi = 0; mi < NM; ++mi)
172#pragma unroll
173        for (int i = 0; i < 8; ++i) tot[mi][i] = 0.0f;
174    const bool have = r < ne;   // this lane's A rows (the entry m = r)
175    for (int b = 0; b < nblk; ++b) {
176        float d[NM];
177        uint64_t lo[NM], hi[NM];
178#pragma unroll
179        for (int mi = 0; mi < NM; ++mi) {
180            const uint8_t* rec = wrows[mi] + (size_t) b * bsz;
181            d[mi] = half_bits_f(*(const uint16_t*) rec);
182            if (WORDS) stream_window_u32<K>(rec, kg, lo[mi], hi[mi]);
183            else stream_window<K>(rec, kg, lo[mi], hi[mi]);
184        }
185#if defined(DS4_TQ_WMMA)
186        float8_t acc[NM];
187#pragma unroll
188        for (int mi = 0; mi < NM; ++mi) acc[mi] = float8_t{0, 0, 0, 0, 0, 0, 0, 0};
189#pragma unroll
190        for (int m = 0; m < 8; ++m) {
191            half8_t ah, al;
192            {
193                float v[8];
194                if (have) act.load8(r, b * 128 + 64 * kg + 8 * m, v);
195                else {
196#pragma unroll
197                    for (int j = 0; j < 8; ++j) v[j] = 0.0f;
198                }
199#pragma unroll
200                for (int j = 0; j < 8; ++j) {
201                    const _Float16 h = (_Float16) v[j];
202                    ah[j] = h;
203                    al[j] = (_Float16) (v[j] - (float) h);
204                }
205            }
206#pragma unroll
207            for (int mi = 0; mi < NM; ++mi) {
208                half8_t wf;
209#pragma unroll
210                for (int s2 = 0; s2 < 2; ++s2) {
211                    const int u = 2 * m + s2;
212                    uint32_t w0, w1;
213                    step_words<COMPUTED>(lut, state_at(lo[mi], hi[mi], (15 - u) * K), w0, w1);
214                    wf[4 * s2 + 0] = __builtin_bit_cast(_Float16, (uint16_t) (w0 & 0xffffu));
215                    wf[4 * s2 + 1] = __builtin_bit_cast(_Float16, (uint16_t) (w0 >> 16));
216                    wf[4 * s2 + 2] = __builtin_bit_cast(_Float16, (uint16_t) (w1 & 0xffffu));
217                    wf[4 * s2 + 3] = __builtin_bit_cast(_Float16, (uint16_t) (w1 >> 16));
218                }
219                acc[mi] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(ah, wf, acc[mi]);   // D[m = entry][n = weight row]
220                acc[mi] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(al, wf, acc[mi]);
221            }
222        }
223#pragma unroll
224        for (int mi = 0; mi < NM; ++mi)
225#pragma unroll
226            for (int i = 0; i < 8; ++i) tot[mi][i] += d[mi] * acc[mi][i];
227#else
228        // plain FMAs: this lane's row r, its 64 weights of the block against every entry (lane r + 16 kg' sums the halves)
229        float part[NM][kMaxEnt];
230#pragma unroll
231        for (int mi = 0; mi < NM; ++mi)
232#pragma unroll
233            for (int e = 0; e < kMaxEnt; ++e) part[mi][e] = 0.0f;
234#pragma unroll
235        for (int m = 0; m < 8; ++m) {
236            float w[NM][8];
237#pragma unroll
238            for (int mi = 0; mi < NM; ++mi)
239#pragma unroll
240                for (int s2 = 0; s2 < 2; ++s2) {
241                    uint32_t w0, w1;
242                    step_words<COMPUTED>(lut, state_at(lo[mi], hi[mi], (15 - (2 * m + s2)) * K), w0, w1);
243                    w[mi][4 * s2 + 0] = half_bits_f(w0 & 0xffffu);
244                    w[mi][4 * s2 + 1] = half_bits_f(w0 >> 16);
245                    w[mi][4 * s2 + 2] = half_bits_f(w1 & 0xffffu);
246                    w[mi][4 * s2 + 3] = half_bits_f(w1 >> 16);
247                }
248#pragma unroll
249            for (int e = 0; e < kMaxEnt; ++e)
250                if (e < ne) {
251                    float v[8];
252                    act.load8(e, b * 128 + 64 * kg + 8 * m, v);
253#pragma unroll
254                    for (int mi = 0; mi < NM; ++mi)
255#pragma unroll
256                        for (int j = 0; j < 8; ++j) part[mi][e] = fmaf(w[mi][j], v[j], part[mi][e]);
257                }
258        }
259        // entries 0..7 into tot[i] of the kg = 0 lane, 8..15 of the kg = 1 lane, so the output indexing matches the WMMA's
260#pragma unroll
261        for (int mi = 0; mi < NM; ++mi)
262#pragma unroll
263            for (int i = 0; i < 8; ++i) {
264                const float p0 = part[mi][i], p1 = part[mi][8 + i];
265                const float q0 = __shfl_xor_sync(0xffffffffu, p0, 16), q1 = __shfl_xor_sync(0xffffffffu, p1, 16);
266                tot[mi][i] += d[mi] * (kg == 0 ? p0 + q0 : p1 + q1);
267            }
268#endif
269    }
270#pragma unroll
271    for (int mi = 0; mi < NM; ++mi)
272#pragma unroll
273        for (int i = 0; i < 8; ++i) acc_out[mi][i] = tot[mi][i];
274}
275
276__device__ __forceinline__ float swiglu(float gv, float uv, float limit) {   // ds4_iq.cu's
277    if (limit > 0.0f) {
278        gv = fminf(gv, limit);
279        uv = fminf(fmaxf(uv, -limit), limit);
280    }
281    return __fmul_rn(__fdiv_rn(gv, __fadd_rn(1.0f, expf(-gv))), uv);
282}
283
284template <int K, bool COMPUTED>
285__device__ __forceinline__ void load_lut(uint32_t* lut) {
286    if (!COMPUTED) {
287        // the table as the CPU decoder has it (tq_cpu.cpp's int16 state table): fp16 * 2^13 rounded half away from zero, over
288        // 2^13 - exact for values >= 2^-3 and within 2^-14 below; the result is still an exact fp16 (fewer significant bits)
289        for (int i = threadIdx.x; i < 2048; i += blockDim.x) {
290            uint32_t pair = 0;
291#pragma unroll
292            for (int j = 0; j < 2; ++j) {
293                const float v = half_bits_f(tq_lut_f16[2 * i + j]) * 8192.0f;
294                const int n = (int) (v < 0.0f ? v - 0.5f : v + 0.5f);
295                pair |= (uint32_t) __half_as_ushort(__float2half_rn((float) n / 8192.0f)) << (16 * j);
296            }
297            lut[i] = pair;
298        }
299        __syncthreads();
300    }
301}
302
303// ---------------------------------------------------------------- token / window experts
304__device__ __forceinline__ bool group_of(const Args& a, int grp, const uint8_t*& blob, int& m0, int& m1) {
305    if (a.grp_ptr == nullptr) {
306        const unsigned long long p = a.plan_ptr[grp];
307        if (p == 0ull) return false;
308        blob = (const uint8_t*) p;
309        m0 = grp;
310        m1 = grp + 1;
311        return true;
312    }
313    if (grp >= *a.n_groups) return false;
314    blob = (const uint8_t*) a.grp_ptr[grp];
315    m0 = a.grp_start[grp];
316    m1 = a.grp_start[grp + 1];
317    return true;
318}
319
320// grid (n_ff / 64, groups): a wave = a 16-row tile of the gate and of the up of the group's expert, 16 entries a pass
321template <int K, bool COMPUTED, bool WORDS>
322__global__ void __launch_bounds__(kThreads) gate_up_kernel(const Args a) {
323    __shared__ uint32_t lut[COMPUTED ? 1 : 2048];
324    __shared__ int ent[kMaxEnt], xr[kMaxEnt];
325    const uint8_t* blob;
326    int m0, m1;
327    if (!group_of(a, blockIdx.y, blob, m0, m1)) return;   // (uniform)
328    load_lut<K, COMPUTED>(lut);
329    const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
330    const int tile = blockIdx.x * kWaves + wave;
331    const int row = tile * kTileRows + r;
332    const size_t rb = (size_t) (a.n_embd / 128) * (2 + 4 * K);
333    const uint8_t* g = blob + a.tr[0] + (size_t) row * rb;
334    const uint8_t* u = blob + a.tr[1] + (size_t) row * rb;
335    for (int mm = m0; mm < m1; mm += kMaxEnt) {
336        const int ne = min(kMaxEnt, m1 - mm);
337        __syncthreads();
338        if ((int) threadIdx.x < ne) {
339            const int e = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x;
340            ent[threadIdx.x] = e;
341            xr[threadIdx.x] = a.grp_ptr != nullptr ? e >> 3 : 0;
342        }
343        __syncthreads();
344        if (tile * kTileRows >= a.n_ff) continue;
345        const ActQ8 act{a.xq, a.xd, xr, a.n_embd};
346        const uint8_t* wr[2] = {g, u};
347        float gu[2][8];
348        tile_dot<K, COMPUTED, 2, WORDS>(wr, a.n_embd / 128, lut, act, ne, gu);
349#pragma unroll
350        for (int i = 0; i < 8; ++i) {
351            const int m = 8 * kg + i;
352            if (m < ne) a.h[(size_t) ent[m] * a.n_ff + row] = swiglu(gu[0][i], gu[1][i], a.limit);
353        }
354    }
355}
356
357// grid (n_embd / 64, groups): the down's tile of a wave against the entries' int8 h
358template <int K, bool COMPUTED, bool WORDS>
359__global__ void __launch_bounds__(kThreads) down_kernel(const Args a) {
360    __shared__ uint32_t lut[COMPUTED ? 1 : 2048];
361    __shared__ int ent[kMaxEnt];
362    const uint8_t* blob;
363    int m0, m1;
364    if (!group_of(a, blockIdx.y, blob, m0, m1)) return;
365    load_lut<K, COMPUTED>(lut);
366    const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
367    const int tile = blockIdx.x * kWaves + wave;
368    const int row = tile * kTileRows + r;
369    const size_t rb = (size_t) (a.n_ff / 128) * (2 + 4 * K);
370    const uint8_t* d = blob + a.tr[2] + (size_t) row * rb;
371    for (int mm = m0; mm < m1; mm += kMaxEnt) {
372        const int ne = min(kMaxEnt, m1 - mm);
373        __syncthreads();
374        if ((int) threadIdx.x < ne) ent[threadIdx.x] = a.grp_ptr != nullptr ? a.grp_ent[mm + threadIdx.x] : mm + threadIdx.x;
375        __syncthreads();
376        if (tile * kTileRows >= a.n_embd) continue;
377        const ActQ8 act{a.hq, a.hd, ent, a.n_ff};
378        const uint8_t* wr[1] = {d};
379        float dd[1][8];
380        tile_dot<K, COMPUTED, 1, WORDS>(wr, a.n_ff / 128, lut, act, ne, dd);
381#pragma unroll
382        for (int i = 0; i < 8; ++i) {
383            const int m = 8 * kg + i;
384            if (m < ne) a.part[(size_t) ent[m] * a.n_embd + row] = dd[0][i];
385        }
386    }
387}
388
389// ---------------------------------------------------------------- the prompt path's sets
390// grid (n_ff / 64, chunks of 16 rows, n_exp): expert e = blockIdx.z owns the sorted rows [bounds[e], bounds[e + 1]); local
391// row = sorted row - row0.  gate / up: F32 x[idx[local]] (ldx) -> F16 swiglu h[local * ldo + c]; down: F16 xh[local] (ldx) ->
392// F32 y[local * ldo + c].
393template <int K, bool COMPUTED, bool GATE_UP, bool WORDS>
394__global__ void __launch_bounds__(kThreads) set_kernel(const SetArgs a) {
395    __shared__ uint32_t lut[COMPUTED ? 1 : 2048];
396    __shared__ int rowsel[kMaxEnt];
397    const int e = blockIdx.z;
398    const int lo = a.bounds[e] - a.row0, hi = a.bounds[e + 1] - a.row0;
399    const int r0 = lo + blockIdx.y * kMaxEnt;
400    if (r0 >= hi) return;   // (uniform)
401    load_lut<K, COMPUTED>(lut);
402    const int ne = min(kMaxEnt, hi - r0);
403    const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
404    const int N = GATE_UP ? a.n_ff : a.n_embd, Kin = GATE_UP ? a.n_embd : a.n_ff;
405    const int tile = blockIdx.x * kWaves + wave;
406    const int row = tile * kTileRows + r;
407    const size_t rb = (size_t) (Kin / 128) * (2 + 4 * K);
408    const uint8_t* blob = a.wbase + (size_t) e * a.stride;
409    if ((int) threadIdx.x < ne) rowsel[threadIdx.x] = GATE_UP ? a.idx[r0 + threadIdx.x] : r0 + (int) threadIdx.x;
410    __syncthreads();
411    if (tile * kTileRows >= N) return;
412    float res[2][8];
413    if (GATE_UP) {
414        const ActF32 act{a.xf, rowsel, (size_t) a.ldx};
415        const uint8_t* wr[2] = {blob + a.tr[0] + (size_t) row * rb, blob + a.tr[1] + (size_t) row * rb};
416        tile_dot<K, COMPUTED, 2, WORDS>(wr, Kin / 128, lut, act, ne, res);
417    } else {
418        const ActF16 act{a.xh, rowsel, (size_t) a.ldx};
419        const uint8_t* wr[1] = {blob + a.tr[2] + (size_t) row * rb};
420        tile_dot<K, COMPUTED, 1, WORDS>(wr, Kin / 128, lut, act, ne, res);
421    }
422    const int kgl = threadIdx.x >> 4 & 1;
423#pragma unroll
424    for (int i = 0; i < 8; ++i) {
425        const int m = 8 * kgl + i;
426        if (m >= ne) continue;
427        const size_t lr = (size_t) (r0 + m);
428        if (GATE_UP) a.h[lr * a.ldo + row] = __half_as_ushort(__float2half_rn(swiglu(res[0][i], res[1][i], a.limit)));
429        else a.y[lr * a.ldo + row] = res[0][i];
430    }
431}
432
433// ---------------------------------------------------------------- GEMV jobs
434// grid (n / 64): y[c * ycs + r] = alpha (row r . x_c) + bias[r] for ncol (<= 16) int8 activation columns
435template <int K, bool COMPUTED, bool WORDS>
436__global__ void __launch_bounds__(kThreads) mv_kernel(const MvJob j) {
437    __shared__ uint32_t lut[COMPUTED ? 1 : 2048];
438    __shared__ int cols[kMaxEnt];
439    load_lut<K, COMPUTED>(lut);
440    if ((int) threadIdx.x < kMaxEnt) cols[threadIdx.x] = (int) threadIdx.x;
441    __syncthreads();
442    const int lane = threadIdx.x & 31, r = lane & 15, kg = lane >> 4, wave = threadIdx.x >> 5;
443    const int tile = blockIdx.x * kWaves + wave;
444    if (tile * kTileRows >= j.n) return;
445    const int row = tile * kTileRows + r;
446    const ActQ8 act{j.xq, j.xd, cols, j.k};
447    const uint8_t* wr[1] = {j.w + (size_t) row * j.ld};
448    float accm[1][8];
449    tile_dot<K, COMPUTED, 1, WORDS>(wr, j.k / 128, lut, act, j.ncol, accm);
450#pragma unroll
451    for (int i = 0; i < 8; ++i) {
452        const int m = 8 * kg + i;
453        if (m < j.ncol && row < j.n) j.y[(size_t) m * j.ycs + row] = j.alpha * accm[0][i] + (j.bias != nullptr ? j.bias[row] : 0.0f);
454    }
455}
456
457// ---------------------------------------------------------------- dispatch
458#define DS4_TQ_SWITCH(t, F)                         \
459    switch (t) {                                    \
460        case kTQK6: F(6, false); break;             \
461        case kTQK7: F(7, false); break;             \
462        case kTQK5X: F(5, true); break;             \
463        case kTQK4X: F(4, true); break;             \
464        case kTQK5T: F(5, false); break;            \
465        case kTQK4T: F(4, false); break;            \
466        default: return false;                      \
467    }
468
469// 32-bit stream loads (STRATA_DS4_TQ_WORDS=1) or the 16-bit ones (default)
470bool use_words() {
471    static const bool on = [] {
472        const char* e = std::getenv("STRATA_DS4_TQ_WORDS");
473        return e != nullptr && std::atoi(e) != 0;   // (no gain measured on the R9700: 13.8 vs 14.2 ms a token)
474    }();
475    return on;
476}
477
478bool bad(const char* what) {
479    std::fprintf(stderr, "ds4 tq: %s\n", what);
480    return false;
481}
482}  // namespace
483
484bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s) {
485    const bool w = use_words();
486    (void) ne_max;
487    if (a.n_embd % 128 != 0 || a.n_ff % (kWaves * kTileRows) != 0) return bad("gate_up: geometry not covered");
488    const dim3 grid((unsigned) (a.n_ff / (kWaves * kTileRows)), (unsigned) groups);
489#define GU_(K, C) { if (w) gate_up_kernel<K, C, true><<<grid, kThreads, 0, s>>>(a); else gate_up_kernel<K, C, false><<<grid, kThreads, 0, s>>>(a); }
490    DS4_TQ_SWITCH(a.tg, GU_)
491#undef GU_
492    return true;
493}
494
495bool down(const Args& a, int groups, int ne_max, cudaStream_t s) {
496    const bool w = use_words();
497    (void) ne_max;
498    if (a.n_ff % 128 != 0 || a.n_embd % (kWaves * kTileRows) != 0) return bad("down: geometry not covered");
499    const dim3 grid((unsigned) (a.n_embd / (kWaves * kTileRows)), (unsigned) groups);
500#define DN_(K, C) { if (w) down_kernel<K, C, true><<<grid, kThreads, 0, s>>>(a); else down_kernel<K, C, false><<<grid, kThreads, 0, s>>>(a); }
501    DS4_TQ_SWITCH(a.td, DN_)
502#undef DN_
503    return true;
504}
505
506bool set_gate_up(const SetArgs& a, cudaStream_t s) {
507    const bool w = use_words();
508    if (a.n_embd % 128 != 0 || a.n_ff % (kWaves * kTileRows) != 0) return bad("set_gate_up: geometry not covered");
509    const dim3 grid((unsigned) (a.n_ff / (kWaves * kTileRows)), (unsigned) ((a.max_rows + kMaxEnt - 1) / kMaxEnt), (unsigned) a.n_exp);
510#define SG_(K, C) { if (w) set_kernel<K, C, true, true><<<grid, kThreads, 0, s>>>(a); else set_kernel<K, C, true, false><<<grid, kThreads, 0, s>>>(a); }
511    DS4_TQ_SWITCH(a.tg, SG_)
512#undef SG_
513    return true;
514}
515
516bool set_down(const SetArgs& a, cudaStream_t s) {
517    const bool w = use_words();
518    if (a.n_ff % 128 != 0 || a.n_embd % (kWaves * kTileRows) != 0) return bad("set_down: geometry not covered");
519    const dim3 grid((unsigned) (a.n_embd / (kWaves * kTileRows)), (unsigned) ((a.max_rows + kMaxEnt - 1) / kMaxEnt), (unsigned) a.n_exp);
520#define SD_(K, C) { if (w) set_kernel<K, C, false, true><<<grid, kThreads, 0, s>>>(a); else set_kernel<K, C, false, false><<<grid, kThreads, 0, s>>>(a); }
521    DS4_TQ_SWITCH(a.td, SD_)
522#undef SD_
523    return true;
524}
525
526bool mv(const MvJob* jobs, int n, cudaStream_t s) {
527    for (int i = 0; i < n; ++i) {
528        const MvJob& j = jobs[i];
529        const bool w = use_words();
530        if (j.k % 128 != 0 || j.n % kTileRows != 0 || j.ncol < 1 || j.ncol > kMaxEnt) return bad("mv: geometry not covered");
531        const dim3 grid((unsigned) ((j.n + kWaves * kTileRows - 1) / (kWaves * kTileRows)));
532#define MV_(K, C) { if (w) mv_kernel<K, C, true><<<grid, kThreads, 0, s>>>(j); else mv_kernel<K, C, false><<<grid, kThreads, 0, s>>>(j); }
533        DS4_TQ_SWITCH(j.type, MV_)
534#undef MV_
535    }
536    return true;
537}
538
539}  // namespace strata::ds4::gguf::iq::tq