okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
18.7 KiB356 linesraw
1// src/prefill/lat_q3k_fused.cu - see include/strata/prefill/lat_q3k_fused.hpp.
2//
3// M3 of the q3k latent A stage: the whole A stage in one call - gate/up (Q3_K), SwiGLU, the q8_1 of H, then the down
4// (IQ4_NL) - in TWO launches, the shape experts_latent has: the gate/up kernel's epilogue is moe_fused.cu's
5// latent_kernel<true> epilogue (SwiGLU + q8_1 into the staged H rows), and the down is the shipped lat_q3k_down
6// kernel called as it is.  Nothing between them goes through the host.
7//
8// The gate/up half here is lat_q3k_gu.cu's kernel (frozen, sha256 53a56961...) with ONE difference, its epilogue:
9// M2a stores the products to gate[]/up[] and M2b quantizes them in a second pass, this one keeps the products in
10// registers and runs SwiGLU + q8_1 there (exactly as latent_kernel<true>: the block's amax over the warp's mg
11// dimension via xor 16/8/4 and the four i in registers, `h = __fmul_rn(__fdiv_rn(gt, 1 + __expf(-gt)), up)`,
12// `q8_1_finite(amax / 127)`, `q8_1_quant`), which is byte for byte what M2b's warp-per-block quantizer writes.
13// Everything else - the decode, the stage buffers, the mma, the work item, the grid - is that file's, unchanged.
14//
15// The staged weight row built from Q3_K instead of NVFP4:
16//   staged row (80 B): 4 x 16 int8 codes at 16 * s, four fp32 sub-scales at 64 + 4 * s
17//   a lane multiplies word k, byte c of its weight sub-block with word k, byte c of the activation sub-block, so both
18//   hold the sub-block's value 4c + k; the sub-block's scale multiplies the whole 16-value product.
19//
20// The decode.  block_q3_K (110 B, 256 values): hmask[32], qs[64], scales[12], half d.  Value v of the super-block is
21//   code(v) = ((qs[B] >> 2t) & 3) - 4 + 4 * ((hmask[B] >> m) & 1)                     in [-4, 3]
22//   scale   = d * (sc[s] - 32),  s = v / 16,  sc = the 6-bit scale of that sub-block
23// with B = 32 * (v / 128) + 16 * ((v / 16) & 1) + (v & 15), t = (v / 32) & 3 and m = t + 4 * (v / 128) - exactly
24// ggml-quants.c's dequantize_row_q3_K (:1305): its 16 sub-blocks per 128-value half, its `shift += 2; m <<= 1`.
25// The 16 6-bit scales come from the 12 scale bytes the same way: sub-block s takes the low (s < 8) or high nibble of
26// byte s & 7 and the two high bits 2 * (s / 4) of byte 8 + (s & 3).
27// A 64-value chunk of a row is four sub-blocks: 32 qs bytes and 32 hmask bytes of one half at ONE 2-bit field.  Two
28// threads a row: thread `whalf` takes the two sub-blocks of field j = 2 * (chunk & 1) + whalf.
29//
30// The rows are 550 B apart, so an address inside a row is 4-byte aligned or 2 mod 4: the 16-byte groups are read with
31// one funnel shift (lat_ld4).  The reads can reach up to 6 bytes past a row's last scale byte, which is inside the
32// blob (the down section follows the gate/up rows) and never past the blob.
33#include "strata/prefill/lat_q3k_fused.hpp"
34#include "strata/prefill/lat_q3k_down.hpp"
35#include "strata/kernels/q8_1_finite.hpp"
36
37#include <cuda_fp16.h>
38#include <cuda_runtime.h>
39
40#include "ggml.h"
41
42#define GGML_COMMON_DECL_CUDA
43#define GGML_COMMON_IMPL_CUDA
44#include "ggml-common.h"
45
46#include <algorithm>
47#include <cstdio>
48#include <cstdlib>
49
50namespace strata::prefill {
51namespace {
52
53void dck(cudaError_t e, const char* what) {
54    if (e != cudaSuccess) {
55        std::fprintf(stderr, "lat q3k fused: %s: %s\n", what, cudaGetErrorString(e));
56        std::exit(1);
57    }
58}
59
60constexpr int64_t kNE = 1280;          // K (ell): 5 Q3_K super-blocks
61constexpr int64_t kFF = 640;           // gate/up rows per projection
62constexpr size_t kUpOff = 352000;      // native_expert_layout(11, 20, 1280, 640)
63constexpr size_t kGuRow = 550;         // 5 x 110 B
64constexpr int kChunks = 20;            // 1280 / 64
65constexpr int kItems = 5;              // 640 features / 128 a work item
66
67constexpr int LTHREADS = 512;
68constexpr int WROWS = 256;             // 128 gate rows + their 128 up rows
69constexpr int LWPITCH = 80;            // 4 x 16 codes, 4 fp32 sub-scales
70constexpr int LAPITCH = 80;            // 64 activation codes, {d0, d1}, pad
71constexpr int kTileRows = 64;
72constexpr int kXqRow = 1440;           // 40 q8_1 blocks of 36 B
73constexpr int kHqRow = 800;            // a staged H row: 10 chunks of 80 B (n_ff / 32 = 20 blocks)
74
75inline size_t lat_smem_bytes() {
76    return (size_t) 2 * WROWS * LWPITCH + (size_t) 2 * kTileRows * LAPITCH + (size_t) kTileRows * 4;
77}
78
79#if !defined(__HIPCC__)
80
81// 16 bytes at p as four words; `sh` is 0 or 16, from the row's 2-byte misalignment (550 B rows)
82__device__ __forceinline__ void lat_ld4(const uint8_t* p, int sh, uint32_t (&w)[4]) {
83    const uint32_t* q = (const uint32_t*) (p - (sh >> 3));
84    w[0] = __funnelshift_r(q[0], q[1], sh);
85    w[1] = __funnelshift_r(q[1], q[2], sh);
86    w[2] = __funnelshift_r(q[2], q[3], sh);
87    w[3] = __funnelshift_r(q[3], q[4], sh);
88}
89
90// One 16-value sub-block's 4 code words (A[m] byte c = the sub-block's value 4m + c) into the staged order: out[k]'s
91// byte c is the sub-block's value 4c + k (the order the staged activations use, so both mma operands agree).
92__device__ __forceinline__ void lat_stage_codes(const uint32_t* A, uint32_t (&out)[4]) {
93#pragma unroll
94    for (int k = 0; k < 4; ++k)
95        out[k] = __byte_perm(__byte_perm(A[0], A[1], k | ((k + 4) << 4)),
96                             __byte_perm(A[2], A[3], k | ((k + 4) << 4)), 0x5410u);
97}
98
99// This thread's two sub-blocks of one 64-value chunk, staged.
100struct GuStaged {
101    uint32_t w[2][4];
102    float sc[2];
103};
104
105__device__ __forceinline__ GuStaged lat_gu_decode(const uint8_t* blk, int kb, int whalf) {
106    const int cl = kb & 3;                        // the chunk inside the 256-value super-block
107    const int half = cl >> 1;                     // the dequantizer's n = 128 * half
108    const int j = 2 * (cl & 1) + whalf;           // the 2-bit field (and, with +4*half, the hmask bit)
109    const int hb = j + 4 * half;                  // the hmask bit of this thread's two sub-blocks
110    const int sh = 8 * ((int) ((uintptr_t) blk & 3));
111    uint32_t qg[2][4], hg[2][4], sw[4];
112    lat_ld4(blk + 32 + 32 * half + 0, sh, qg[0]);     // the even sub-block's 16 qs bytes
113    lat_ld4(blk + 32 + 32 * half + 16, sh, qg[1]);    // the odd one's
114    // the hmask is NOT advanced across the 128-value halves (ggml reads hm[l] / hm[l + 16] both times, the bit
115    // j + 4 * half picking the half): its two 16-byte groups are 0 and 16
116    lat_ld4(blk + 0, sh, hg[0]);
117    lat_ld4(blk + 16, sh, hg[1]);
118    lat_ld4(blk + 96, sh, sw);                        // scales[12] then d (and 2 pad bytes)
119    const float d = __half2float(__ushort_as_half((unsigned short) (sw[3] & 0xFFFFu)));
120    GuStaged r;
121#pragma unroll
122    for (int g = 0; g < 2; ++g) {                 // sub-block s_local = 2 * whalf + g
123        const int s = 4 * cl + 2 * whalf + g;
124        uint32_t nat[4];
125#pragma unroll
126        for (int m = 0; m < 4; ++m) {
127            const uint32_t lo2 = (qg[g][m] >> (2 * j)) & 0x03030303u;             // 2 low bits per value
128            const uint32_t hi1 = (hg[g][m] >> hb) & 0x01010101u;                  // the high bit -> 4
129            // the -4 offset ggml's vec_dot folds in with a second dp4a, folded into the code here: [0, 7] - 4 =
130            // [-4, 3].  Byte-wise, not a 32-bit subtract: a byte underflow would borrow from its neighbour.
131            nat[m] = __vsub4(lo2 | (4u * hi1), 0x04040404u);
132        }
133        lat_stage_codes(nat, r.w[g]);
134        // the sub-block's 6-bit scale: nibble (low/high per half) of byte s & 7, two high bits of byte 8 + (s & 3)
135        const uint32_t nib_byte = (sw[(s & 7) >> 2] >> (8 * (s & 3))) & 0xFFu;
136        const uint32_t nib = (nib_byte >> (4 * (s >> 3))) & 0xFu;
137        const uint32_t hi2 = (sw[2] >> (8 * (s & 3) + 2 * (s >> 2))) & 3u;
138        r.sc[g] = d * (float) ((int) (nib | (hi2 << 4)) - 32);
139    }
140    return r;
141}
142
143// ---- the kernel: 128 gate rows and their up rows per work item ------------------------------------------------
144__global__ void __launch_bounds__(LTHREADS, 1)
145lat_q3k_fused_gu_kernel(const uint8_t* const* __restrict__ blob, const int32_t* __restrict__ starts, int n_groups,
146                        const uint8_t* __restrict__ xq, uint8_t* __restrict__ hbuf,
147                        const int32_t* __restrict__ counts, const int32_t* __restrict__ ent_tok) {
148#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
149    extern __shared__ __align__(16) uint8_t smem[];
150    uint8_t* wst[2] = {smem, smem + WROWS * LWPITCH};
151    uint8_t* ast[2] = {smem + 2 * WROWS * LWPITCH, smem + 2 * WROWS * LWPITCH + kTileRows * LAPITCH};
152    int* srow = (int*) (smem + 2 * WROWS * LWPITCH + 2 * kTileRows * LAPITCH);
153
154    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, mg = lane >> 2, tig = lane & 3;
155    const int wf = warp & 3, nb0 = 16 * (warp >> 2);
156    const int wrow = tid >> 1, whalf = tid & 1;         // 2 threads a weight row, one 32-value half each
157    const int arow = tid >> 1, ahalf = tid & 1;
158
159    const int fb = blockIdx.x;                          // this launch's 128 features of the item
160    for (int g = blockIdx.y; g < n_groups; g += gridDim.y) {
161        const uint8_t* bl = blob[g];
162        if (bl == nullptr) continue;
163        const int e0 = starts[g];
164        // the group's row count: counts[] when the caller has it (the engine's flushes are not in group order)
165        const int e1 = counts != nullptr ? e0 + counts[g] : starts[g + 1];
166        for (int row0 = e0 + (int) blockIdx.z * kTileRows; row0 < e1; row0 += (int) gridDim.z * kTileRows) {
167            const int nrows = min(kTileRows, e1 - row0);
168            const int arows = min(kTileRows, (nrows + 15) & ~15);
169            // the stage's row: gate rows 128 * fb .. , then their up rows 128 rows later
170            const int fr = 128 * fb + (wrow & 127);
171            const uint8_t* wsrc = wrow < 128 ? bl + (size_t) fr * kGuRow : bl + kUpOff + (size_t) fr * kGuRow;
172            __syncthreads();
173            // the activation row of a tile row: the entry itself, or the token row ent_tok gives it (H stays
174            // entry-indexed: row0 + r is the entry)
175            if (tid < kTileRows) {
176                const int er = row0 + min(tid, nrows - 1);
177                srow[tid] = ent_tok != nullptr ? ent_tok[er] : er;
178            }
179            __syncthreads();
180
181            GuStaged wc[2];
182            uint32_t aq[8], adw = 0;
183            auto load_chunk = [&](int kb) {
184                const uint8_t* blk = wsrc + 110 * (kb >> 2);
185                wc[kb & 1] = lat_gu_decode(blk, kb, whalf);
186                if (tid < 2 * arows) {
187                    // the plain q8_1 row: 72 B a chunk (two 32-value blocks), word 0 of a block is its ds
188                    const uint32_t* ap = (const uint32_t*) (xq + (size_t) srow[arow] * kXqRow + (size_t) 72 * kb);
189#pragma unroll
190                    for (int i = 0; i < 8; ++i) aq[i] = ap[1 + 9 * ahalf + i];
191                    adw = ap[9 * ahalf];
192                }
193            };
194            auto store_chunk = [&](int kb) {
195                uint8_t* wr = wst[kb & 1] + (size_t) wrow * LWPITCH;
196                const GuStaged& w = wc[kb & 1];
197#pragma unroll
198                for (int gg = 0; gg < 2; ++gg) {
199                    const int s = 2 * whalf + gg;
200#pragma unroll
201                    for (int k = 0; k < 4; ++k) *(uint32_t*) (wr + 16 * s + 4 * k) = w.w[gg][k];
202                    *(float*) (wr + 64 + 4 * s) = w.sc[gg];
203                }
204                if (tid < 2 * arows) {
205                    uint8_t* ar = ast[kb & 1] + (size_t) arow * LAPITCH;
206#pragma unroll
207                    for (int h = 0; h < 2; ++h) {
208                        const int s = 2 * ahalf + h;
209                        const uint32_t* wp = &aq[4 * h];
210#pragma unroll
211                        for (int k = 0; k < 4; ++k) {
212                            const uint32_t p1 = __byte_perm(wp[0], wp[1], k | ((k + 4) << 4));
213                            const uint32_t p2 = __byte_perm(wp[2], wp[3], k | ((k + 4) << 4));
214                            *(uint32_t*) (ar + 16 * s + 4 * k) = __byte_perm(p1, p2, 0x5410u);
215                        }
216                    }
217                    *(__half*) (ar + 64 + 2 * ahalf) = __ushort_as_half((unsigned short) (adw & 0xFFFFu));
218                }
219            };
220
221            load_chunk(0);
222            store_chunk(0);
223            if (kChunks > 1) load_chunk(1);
224            const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
225            float acc[4][2][4];
226#pragma unroll
227            for (int i = 0; i < 4; ++i)
228#pragma unroll
229                for (int n = 0; n < 2; ++n)
230#pragma unroll
231                    for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
232            for (int kb = 0; kb < kChunks; ++kb) {
233                __syncthreads();
234                if (on0) {
235                    const uint8_t* wc8 = wst[kb & 1];
236                    const uint8_t* ac = ast[kb & 1];
237                    for (int s = 0; s < 4; ++s) {
238                        uint32_t bq[2];
239                        float dx0[2], dx1[2];
240                        for (int n = 0; n < 2; ++n) {
241                            if (n == 1 && !on1) break;
242                            const uint8_t* ar = ac + (size_t) (nb0 + 8 * n + mg) * LAPITCH;
243                            bq[n] = *(const uint32_t*) (ar + 16 * s + 4 * tig);
244                            const half2 ds0 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig) * LAPITCH + 64);
245                            const half2 ds1 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig + 1) * LAPITCH + 64);
246                            dx0[n] = __half2float((s & 2) ? ds0.y : ds0.x);
247                            dx1[n] = __half2float((s & 2) ? ds1.y : ds1.x);
248                        }
249                        for (int i = 0; i < 4; ++i) {
250                            const int ra = 32 * wf + 8 * i + mg;          // the gate row (its up row is ra + 128)
251                            const int rb = ra + 128;
252                            const uint32_t a0 = *(const uint32_t*) (wc8 + (size_t) ra * LWPITCH + 16 * s + 4 * tig);
253                            const uint32_t a1 = *(const uint32_t*) (wc8 + (size_t) rb * LWPITCH + 16 * s + 4 * tig);
254                            const float da = *(const float*) (wc8 + (size_t) ra * LWPITCH + 64 + 4 * s);
255                            const float db = *(const float*) (wc8 + (size_t) rb * LWPITCH + 64 + 4 * s);
256                            for (int n = 0; n < 2; ++n) {
257                                if (n == 1 && !on1) break;
258                                int d[4] = {0, 0, 0, 0};
259                                asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, "
260                                    "{%0,%1,%2,%3};\n"
261                                    : "+r"(d[0]), "+r"(d[1]), "+r"(d[2]), "+r"(d[3])
262                                    : "r"(a0), "r"(a1), "r"(bq[n]));
263                                acc[i][n][0] += (da * dx0[n]) * (float) d[0];
264                                acc[i][n][1] += (da * dx1[n]) * (float) d[1];
265                                acc[i][n][2] += (db * dx0[n]) * (float) d[2];
266                                acc[i][n][3] += (db * dx1[n]) * (float) d[3];
267                            }
268                        }
269                    }
270                }
271                __syncthreads();
272                if (kb + 1 < kChunks) {
273                    store_chunk(kb + 1);
274                    if (kb + 2 < kChunks) load_chunk(kb + 2);
275                }
276            }
277            if (!on0) continue;
278            // SwiGLU of feature 32 * (4 * fb + wf) + 8 i + mg, H to q8_1 as q8_1_store (the amax over the warp's 32
279            // features, d = q8_1_finite(amax / 127), the code rounding) into the staged row the down half reads -
280            // moe_fused.cu's latent_kernel<true> epilogue, with no NVFP4 tail (the q3k pack has none: scales 1)
281            const int blk = 4 * fb + wf;
282            for (int n = 0; n < 2; ++n) {
283                if (n == 1 && !on1) break;
284                for (int c = 0; c < 2; ++c) {
285                    float h[4], am = 0.0f;
286#pragma unroll
287                    for (int i = 0; i < 4; ++i) {
288                        const float gt = acc[i][n][c], uv = acc[i][n][2 + c];
289                        h[i] = __fmul_rn(__fdiv_rn(gt, 1.0f + __expf(-gt)), uv);
290                        am = fmaxf(am, fabsf(h[i]));
291                    }
292                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 16));
293                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 8));
294                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 4));
295                    const float d = strata::kernels::q8_1_finite(__fdiv_rn(am, 127.0f));
296                    const int r = nb0 + 8 * n + 2 * tig + c;
297                    if (r < nrows) {
298                        uint8_t* o = hbuf + (size_t) (row0 + r) * kHqRow + (size_t) (blk >> 1) * LAPITCH;
299                        const int hh = blk & 1;
300#pragma unroll
301                        for (int i = 0; i < 4; ++i) {
302                            const int v = 8 * i + mg;
303                            o[16 * (2 * hh + (v >> 4)) + 4 * (v & 3) + ((v & 15) >> 2)] =
304                                (uint8_t) strata::kernels::q8_1_quant(h[i], d, am);
305                        }
306                        if (mg == 0) *(__half*) (o + 64 + 2 * hh) = __float2half(d);
307                    }
308                }
309            }
310        }
311    }
312#endif
313}
314
315#endif  // !__HIPCC__
316
317int lat_sms() {
318    static const int sms = [] {
319        int dev = 0, n = 0;
320        return cudaGetDevice(&dev) == cudaSuccess &&
321                       cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && n > 0
322                   ? n
323                   : 0;
324    }();
325    return sms;
326}
327
328}  // namespace
329
330void lat_q3k_fused(const uint8_t* const* blob, const int32_t* starts, int n_groups, const void* xq, void* hbuf,
331                   float* out, int64_t ld, void* stream, const int32_t* counts, const int32_t* ent_tok,
332                   const int32_t* ent_dst) {
333    if (n_groups <= 0 || blob == nullptr || starts == nullptr || xq == nullptr || hbuf == nullptr || out == nullptr)
334        return;
335#if defined(__HIPCC__)
336    std::fprintf(stderr, "lat q3k fused: the latent A stage's kernels are CUDA-only\n");
337    std::exit(1);
338#else
339    static const bool once = [] {
340        dck(cudaFuncSetAttribute(lat_q3k_fused_gu_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
341                                 (int) lat_smem_bytes()), "smem");
342        return true;
343    }();
344    (void) once;
345    const int sms = lat_sms();
346    const unsigned gy = (unsigned) std::min(n_groups, 512);
347    const unsigned gz = (sms > 0 && (int) (gy * kItems) < sms) ? 8u : 1u;
348    lat_q3k_fused_gu_kernel<<<dim3((unsigned) kItems, gy, gz), LTHREADS, lat_smem_bytes(), (cudaStream_t) stream>>>(
349        blob, starts, n_groups, (const uint8_t*) xq, (uint8_t*) hbuf, counts, ent_tok);
350    dck(cudaGetLastError(), "launch gu+swiglu+q8_1");
351    // the down: the shipped M1 kernel, on the H rows just written (same stream, so ordered)
352    lat_q3k_down(blob, starts, n_groups, hbuf, out, ld, (void*) stream, counts, ent_dst);
353#endif
354}
355
356}  // namespace strata::prefill