okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
31.1 KiB645 linesraw
1// src/prefill/moe_ws_down.cu - weight-stationary down products (see moe_ws.hpp): Q2_0 and IQ4_NL, [2560 x 640] read in
2// place at the blob's down offset, K stopping at 640 (nothing past a matrix is read).  A CTA = 128 or 256 threads =
3// as many weight rows of one expert (a row per thread, all of the chunk's H rows TPP at a time, the sums in registers);
4// per K step the next step's weight bytes and q8_1 words are loaded into registers before this step's compute and
5// stored to shared memory after it (one barrier pair per step).  The H rows are ONE mmq::swiglu_quant over all of the
6// layer's rows: [k/128][rows] block_q8_1_mmq, of which blocks 0-4 are read.  (Measured on a GP100 die: ws / per-group
7// MMQ 0.24-0.29 at 2.5 rows per expert, 0.38-0.49 at 10, 0.52-0.68 at 35, 0.61-0.74 at 160; bit-identical,
8// compute-sanitizer clean with exact-size matrices.)
9#include "common.cuh"
10#include "mmq.cuh"
11
12#include "moe_ws.cuh"
13
14#include <cstdio>
15#include <cstdlib>
16#include <type_traits>
17
18namespace strata::prefill::ws::detail {
19namespace {
20
21constexpr int DN_ROWS = 2560, DN_K = 640;
22
23void ck(cudaError_t e, const char* what) {
24    if (e != cudaSuccess) {
25        std::fprintf(stderr, "prefill ws: %s: %s\n", what, cudaGetErrorString(e));
26        std::exit(1);
27    }
28}
29
30// ---- Q2_0: 18-B blocks {f16 d; 16 B of 2-bit codes}, 180-B rows; a step is 128 values = 2 blocks = 36 B of a row.
31// MMQ's values {-1, 0, 1, 2}[code] (ggml_cuda_mmq_load_tiles_q2_0's PRMT, the selector masked to 3 bits) and the
32// activations' int8 are both made exact fp16 pairs; a 32-value block is 16 HFMA2 into 2 half2 sums, each fp16 lane
33// summing 8 products of magnitude <= 256 - integers <= 2048, exact - added in fp32: the float MMQ's I2F(sumi) gives.
34// Epilogue as MMQ's sm_60 SASS: per 32-value block FMUL.FTZ (dx * dy), FFMA.FTZ (prod, sum, acc), blocks in K order.
35namespace q20 {
36constexpr int NT = 128, ROWB = 180, NSTEP = DN_K / 128, QB = 144, PIECES = DN_ROWS / NT;
37
38__device__ __forceinline__ uint32_t prmt(const uint32_t a, const uint32_t b, const uint32_t s) {
39    uint32_t d;
40    asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(s));
41    return d;
42}
43__device__ __forceinline__ uint32_t hfma2(const uint32_t a, const uint32_t b, const uint32_t c) {
44    uint32_t d;
45    asm("fma.rn.f16x2 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c));
46    return d;
47}
48__device__ __forceinline__ uint32_t hadd2(const uint32_t a, const uint32_t b) {
49    uint32_t d;
50    asm("add.rn.f16x2 %0, %1, %2;" : "=r"(d) : "r"(a), "r"(b));
51    return d;
52}
53// the two fp16 lanes of h converted exactly to f32 and added
54__device__ __forceinline__ float h2sum(const uint32_t h) {
55    float f;
56    asm("{\n\t.reg .f16 lo, hi;\n\t.reg .f32 a, b;\n\tmov.b32 {lo, hi}, %1;\n\t"
57        "cvt.f32.f16 a, lo;\n\tcvt.f32.f16 b, hi;\n\tadd.f32 %0, a, b;\n\t}"
58        : "=f"(f) : "r"(h));
59    return f;
60}
61__device__ __forceinline__ float f16_to_f32(const uint32_t bits16) {
62    float f;
63    asm("{\n\t.reg .b16 h;\n\tcvt.u16.u32 h, %1;\n\tcvt.f32.f16 %0, h;\n\t}" : "=f"(f) : "r"(bits16));
64    return f;
65}
66
67// the 16 values of the int16 qa = x2 & 0xFFFF, qb = x2 >> 16 of a block's codes (value i at bits 2i) as fp16 pairs
68// (v0,v4) (v1,v5) (v2,v6) (v3,v7), qa's to wa and qb's to wb: prmt(H, 0, sel) with nibbles 1 / 3 of sel the code with
69// its low bit flipped and nibbles 0 / 2 zero (byte 0 of H, the zero high byte)
70__device__ __forceinline__ void dec2_h16(const uint32_t x2, uint32_t (&wa)[4], uint32_t (&wb)[4]) {
71    constexpr uint32_t H = 0x3C40BC00u;   // bytes 00 BC 40 3C = fp16 high bytes of {0, -1, +2, +1}[c ^ 1] = {-1,0,1,2}[c]
72    const uint32_t x = x2 ^ 0x55555555u;
73    const uint32_t m0 = (x << 4) & 0x30303030u, m1 = (x << 2) & 0x30303030u, m2 = x & 0x30303030u, m3 = (x >> 2) & 0x30303030u;
74    wa[0] = prmt(H, 0u, m0);
75    wa[1] = prmt(H, 0u, m1);
76    wa[2] = prmt(H, 0u, m2);
77    wa[3] = prmt(H, 0u, m3);
78    wb[0] = prmt(H, 0u, m0 >> 16);
79    wb[1] = prmt(H, 0u, m1 >> 16);
80    wb[2] = prmt(H, 0u, m2 >> 16);
81    wb[3] = prmt(H, 0u, m3 >> 16);
82}
83
84// the 8 int8 of activation words A (values 0-3) and B (4-7) as fp16 pairs (a0,a4) (a1,a5) (a2,a6) (a3,a7):
85// u = a + 128; fp16 bits 0x64uu = 1024 + u exactly; minus 1152 = a exactly
86__device__ __forceinline__ void act_h16(const uint32_t A, const uint32_t B, uint32_t (&a)[4]) {
87    const uint32_t P1 = prmt(A, B, 0x5140u) ^ 0x80808080u;   // u0 u4 u1 u5
88    const uint32_t P2 = prmt(A, B, 0x7362u) ^ 0x80808080u;   // u2 u6 u3 u7
89    constexpr uint32_t M = 0x64646464u, NEG1152 = 0xE480E480u;
90    a[0] = hadd2(prmt(P1, M, 0x4140u), NEG1152);
91    a[1] = hadd2(prmt(P1, M, 0x4342u), NEG1152);
92    a[2] = hadd2(prmt(P2, M, 0x4140u), NEG1152);
93    a[3] = hadd2(prmt(P2, M, 0x4342u), NEG1152);
94}
95
96// the exact integer dot of one 32-value block (weights w[16], activations a0..a3 = 16 fp16 pairs) as a float
97__device__ __forceinline__ float block_sum(const uint32_t (&w)[16], const uint4 a0, const uint4 a1, const uint4 a2,
98                                           const uint4 a3) {
99    uint32_t p = hfma2(w[0], a0.x, 0u), q = hfma2(w[1], a0.y, 0u);
100    p = hfma2(w[2], a0.z, p); q = hfma2(w[3], a0.w, q);
101    p = hfma2(w[4], a1.x, p); q = hfma2(w[5], a1.y, q);
102    p = hfma2(w[6], a1.z, p); q = hfma2(w[7], a1.w, q);
103    p = hfma2(w[8], a2.x, p); q = hfma2(w[9], a2.y, q);
104    p = hfma2(w[10], a2.z, p); q = hfma2(w[11], a2.w, q);
105    p = hfma2(w[12], a3.x, p); q = hfma2(w[13], a3.y, q);
106    p = hfma2(w[14], a3.z, p); q = hfma2(w[15], a3.w, q);
107    return h2sum(p) + h2sum(q);
108}
109
110// TPP tokens per pass; tokens guarded in pairs (a pair's token past the count runs on a clamped row, not written).
111// Per step every thread stages exactly 9 words of the CTA's 128 x 36 B (row stride 9 words: conflict-free decode reads)
112// and threads < 8 TPP one 16-value q8_1 piece each.
113template <int TPP>
114__global__ void __launch_bounds__(NT, 4) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w,
115                                                   const int64_t* __restrict__ xoff, const int64_t xadd,
116                                                   const char* __restrict__ xq, const int total_rows,
117                                                   float* __restrict__ dst) {
118    constexpr int G = 2, WPR = 9, AQ = TPP * 8, AI = (AQ + NT - 1) / NT;
119    static_assert(TPP % G == 0, "");
120    __shared__ int wsm[NT * WPR];
121    __shared__ __align__(16) uint32_t act_s[TPP][4][16];
122    __shared__ __align__(8) float dy_s[4][TPP];
123    int r0;
124    const Chunk c = cta_work<PIECES, NT>(chunks, r0);
125    const char* __restrict__ W = w + xoff[c.j] + xadd + (size_t) r0 * ROWB;
126    const int tid = threadIdx.x;
127    int woff[WPR];   // word tid + NT i of the step's NT x 9 words: row (tid + NT i) / 9, word (tid + NT i) % 9
128#pragma unroll
129    for (int i = 0; i < WPR; ++i) {
130        const int idx = tid + i * NT, r = idx / WPR;
131        woff[i] = r * ROWB + 4 * (idx - r * WPR);
132    }
133    int wpre[WPR];
134    uint4 apre[AI];
135    float dpre[AI];
136    auto load_w = [&](const int st) {
137        const char* __restrict__ Ws = W + st * 36;
138#pragma unroll
139        for (int i = 0; i < WPR; ++i) wpre[i] = __ldg((const int*) (Ws + woff[i]));
140    };
141    auto store_w = [&]() {
142#pragma unroll
143        for (int i = 0; i < WPR; ++i) wsm[tid + i * NT] = wpre[i];
144    };
145    auto load_a = [&](const int st, const int trow0, const int nt) {
146#pragma unroll
147        for (int i = 0; i < AI; ++i) {
148            const int idx = tid + i * NT;
149            if (AQ % NT == 0 || idx < AQ) {
150                const int t = idx >> 3, m = idx & 7;
151                const char* blk = xq + ((size_t) st * total_rows + trow0 + min(t, nt - 1)) * QB;
152                apre[i] = __ldg((const uint4*) (blk + 16) + m);   // values 16m .. 16m + 15 of the 128
153                dpre[i] = __ldg((const float*) blk + (m >> 1));   // d of their 32-value block
154            }
155        }
156    };
157    auto store_a = [&]() {
158#pragma unroll
159        for (int i = 0; i < AI; ++i) {
160            const int idx = tid + i * NT;
161            if (AQ % NT == 0 || idx < AQ) {
162                const int t = idx >> 3, m = idx & 7, b = m >> 1, hf = m & 1;
163                uint32_t p0[4], p1[4];
164                act_h16(apre[i].x, apre[i].y, p0);
165                act_h16(apre[i].z, apre[i].w, p1);
166                uint4* d = (uint4*) &act_s[t][b][8 * hf];
167                d[0] = make_uint4(p0[0], p0[1], p0[2], p0[3]);
168                d[1] = make_uint4(p1[0], p1[1], p1[2], p1[3]);
169                dy_s[b][t] = dpre[i];   // both pieces of a block write the same value
170            }
171        }
172    };
173
174    load_w(0);
175    load_a(0, c.row0, min(TPP, c.rows));
176    for (int p0 = 0; p0 < c.rows; p0 += TPP) {
177        const int nt = min(TPP, c.rows - p0);
178        const int trow0 = c.row0 + p0;
179        float acc[TPP];
180#pragma unroll
181        for (int t = 0; t < TPP; ++t) acc[t] = 0.0f;
182#pragma unroll 1
183        for (int st = 0; st < NSTEP; ++st) {
184            __syncthreads();
185            store_w();
186            store_a();
187            __syncthreads();
188            if (st + 1 < NSTEP) {
189                load_w(st + 1);
190                load_a(st + 1, trow0, nt);
191            } else if (p0 + TPP < c.rows) {
192                load_w(0);
193                load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP));
194            }
195            // the row's 9 step words: block 0 = d0 | qs0 at bytes 0..17 (the codes 2 bytes into a word: funnel shift),
196            // block 1 = d1 in the top half of word 4, qs1 = words 5..8
197            const uint32_t* cw = (const uint32_t*) (wsm + tid * WPR);
198#pragma unroll 1
199            for (int b = 0; b < 4; ++b) {   // 32-value block: Q2_0 block b / 2, half b % 2 (int16 4h .. 4h + 3), K order
200                const int pq = b >> 1, h = b & 1;
201                const int base = pq ? 5 + 2 * h : 2 * h, sh = pq ? 0 : 16;
202                const uint32_t c0 = cw[base], c1 = cw[base + 1], c2 = cw[min(base + 2, WPR - 1)];
203                const float dx = f16_to_f32(pq ? cw[4] >> 16 : cw[0] & 0xFFFFu);
204                uint32_t wv[16], wa[4], wb[4];
205                dec2_h16(__funnelshift_r(c0, c1, sh), wa, wb);   // int16 0 and 1 of the half
206#pragma unroll
207                for (int k = 0; k < 4; ++k) { wv[k] = wa[k]; wv[4 + k] = wb[k]; }
208                dec2_h16(__funnelshift_r(c1, c2, sh), wa, wb);   // int16 2 and 3
209#pragma unroll
210                for (int k = 0; k < 4; ++k) { wv[8 + k] = wa[k]; wv[12 + k] = wb[k]; }
211#pragma unroll
212                for (int t0 = 0; t0 < TPP; t0 += G) {
213                    if (t0 < nt) {
214                        const float2 d2 = *(const float2*) &dy_s[b][t0];
215#pragma unroll
216                        for (int t = t0; t < t0 + G; ++t) {
217                            const uint4* a4 = (const uint4*) act_s[t][b];
218                            const float s = block_sum(wv, a4[0], a4[1], a4[2], a4[3]);
219                            acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), s, acc[t]);
220                        }
221                    }
222                }
223            }
224        }
225#pragma unroll
226        for (int t = 0; t < TPP; ++t)
227            if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + tid] = acc[t];
228    }
229}
230}  // namespace q20
231
232// ---- IQ4_NL: 18-B blocks {f16 d; 16 B of 4-bit indices into kvalues_iq4nl}, 360-B rows; a step is SB blocks (SB 4:
233// 72 B of a row, 8-byte aligned; SB 2: 36 B).  The int8 values are get_int_from_table_16's table lookups (the 16-byte
234// table in registers) without its final byte reorder - the same values paired (v4k, v4k+1), (v4k+16, v4k+17), ... and
235// the activations paired the same way (PRMT 0x9180 / 0xB3A2); one XMAD chain per (row, token, block), then MMQ's sm_60
236// FMUL.FTZ (dx * dy), I2F (sumi), FFMA.FTZ, blocks in K order.  Staging: 3 rows per warp and k (lanes 0-26, a row's 9
237// 4- or 8-byte pieces), the last k guarded so no row past the CTA's is read.
238namespace nl4 {
239constexpr int NB = DN_K / QK4_NL, BB = (int) sizeof(block_iq4_nl), ROWB = NB * BB;   // 20, 18, 360
240static_assert(NB == 20 && BB == 18 && ROWB == 360, "");
241
242// bytes (0,1) and (2,3) of v, each sign-extended to 16 bits
243__device__ __forceinline__ void split01(const int v, int& p01, int& p23) {
244    asm("prmt.b32 %0, %1, 0, 0x9180;" : "=r"(p01) : "r"(v));
245    asm("prmt.b32 %0, %1, 0, 0xB3A2;" : "=r"(p23) : "r"(v));
246}
247// the 16-byte kvalues_iq4nl table as 4 words, read byte by byte
248__device__ __forceinline__ void load_tab(uint32_t (&tab)[4]) {
249#pragma unroll
250    for (int i = 0; i < 4; ++i) {
251        uint32_t v = 0;
252#pragma unroll
253        for (int b = 0; b < 4; ++b) v |= (uint32_t) (uint8_t) kvalues_iq4nl[4 * i + b] << (8 * b);
254        tab[i] = v;
255    }
256}
257// a 32-value block from its 4 qs words (q[k]: values 4k..4k+3 in the low nibbles, 16+4k.. in the high ones): 16 int16
258// pair words against the activation pairs split01 makes of activation words m = 0..7 (at act[2m], act[2m + 1]).
259// get_int_from_table_16's body (CUDA branch) up to its two lookup words tmp[0] = (v4k, v4k+16, v4k+1, v4k+17),
260// tmp[1] = (v4k+2, v4k+18, v4k+3, v4k+19)
261__device__ __forceinline__ void dec(const int (&q)[4], const uint32_t (&tab)[4], int (&wv)[16]) {
262#pragma unroll
263    for (int k = 0; k < 4; ++k) {
264        const uint32_t q4 = (uint32_t) q[k];
265        uint32_t tmp[2];
266        const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));
267#pragma unroll
268        for (uint32_t i = 0; i < 2; ++i) {
269            const uint32_t shift = 16 * i;
270            const uint32_t low = __byte_perm(tab[0], tab[1], q4 >> shift);
271            const uint32_t high = __byte_perm(tab[2], tab[3], q4 >> shift);
272            tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
273        }
274        split2((int) tmp[0], wv[2 * k], wv[2 * (k + 4)]);           // (v4k, v4k+1) | (v16+4k, v17+4k)
275        split2((int) tmp[1], wv[2 * k + 1], wv[2 * (k + 4) + 1]);   // (v4k+2, v4k+3) | (v18+4k, v19+4k)
276    }
277}
278// block PAR of block pair p of the staged step (9 words per pair: even block d = lo16(w0), qs = bytes 2..17 by funnel
279// shifts; odd block d = hi16(w4), qs = w5..w8)
280template <int PAR>
281__device__ __forceinline__ float load_blk(const int* __restrict__ cw, const int p, int (&q)[4]) {
282    const int* c = cw + 9 * p;
283    if constexpr (PAR == 0) {
284#pragma unroll
285        for (int k = 0; k < 4; ++k) q[k] = (int) __funnelshift_r((uint32_t) c[k], (uint32_t) c[k + 1], 16);
286        return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[0] & 0xFFFFu)));
287    } else {
288#pragma unroll
289        for (int k = 0; k < 4; ++k) q[k] = c[5 + k];
290        return __half2float(__ushort_as_half((unsigned short) ((uint32_t) c[4] >> 16)));
291    }
292}
293
294template <int NT, int TPP, int SB, int G, int PAR>
295__device__ __forceinline__ void blk_compute(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4],
296                                            const int (*act_s)[SB][16], const float (*dy_s)[SB], const int nt,
297                                            float (&acc)[TPP]) {
298    const int b = 2 * p + PAR;   // block within the step
299    int wv[16];
300    float dx;
301    {
302        int q[4];
303        dx = load_blk<PAR>(cw, p, q);
304        dec(q, tab, wv);
305    }
306    // tokens in groups of G behind one guard (a group's tokens past nt run on stale shared memory, not written)
307#pragma unroll
308    for (int t0 = 0; t0 < TPP; t0 += G) {
309        if (t0 < nt) {
310#pragma unroll
311            for (int t = t0; t < t0 + G; ++t) {
312                const int4* a4 = (const int4*) act_s[t][b];
313                const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3];
314                const float dy = dy_s[t][b];
315                int s0 = 0;
316                s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0);
317                s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0);
318                s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0);
319                s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0);
320                acc[t] = __fmaf_rn(__fmul_rn(dx, dy), __int2float_rn(s0), acc[t]);
321            }
322        }
323    }
324}
325
326template <int NT, int TPP, int SB, int G>
327__global__ void __launch_bounds__(NT, 1) dn_kernel(const Chunk* __restrict__ chunks, const char* __restrict__ w,
328                                                   const int64_t* __restrict__ xoff, const int64_t xadd,
329                                                   const block_q8_1_mmq* __restrict__ xq, const int total_rows,
330                                                   float* __restrict__ dst) {
331    static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, "");
332    constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT;
333    constexpr int KI = (NT + 3 * NW - 1) / (3 * NW);
334    constexpr int AW = 9 * SB;                     // activation words per token and step (SB d + 8 SB qs words)
335    constexpr int AI = (TPP * AW + NT - 1) / NT;
336    using PT = typename std::conditional<SB == 4, int2, int>::type;
337    __shared__ int wsm[NT * S];
338    __shared__ __align__(16) int act_s[TPP][SB][16];
339    __shared__ float dy_s[TPP][SB];
340    uint32_t tab[4];
341    load_tab(tab);
342    int r0;
343    const Chunk c = cta_work<PIECES, NT>(chunks, r0);
344    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
345    const int sub = lane / 9, pc = lane - 9 * sub;   // sub 3: lanes 27-31, idle
346    const int srow0 = 3 * warp + sub;
347    const bool sact = sub < 3;
348    const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT);
349    int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4);
350    PT pre[KI];
351    int apre[AI];
352    auto load_w = [&](const int st) {
353        if (sact) {
354            const char* g = Wg + st * (SB * BB);
355#pragma unroll
356            for (int k = 0; k < KI; ++k)
357                if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB));
358        }
359    };
360    auto store_w = [&]() {
361        if (sact) {
362#pragma unroll
363            for (int k = 0; k < KI; ++k)
364                if (k < KI - 1 || srow0 + 3 * NW * k < NT) {
365                    if constexpr (SB == 4) {
366                        ws_st[k * 3 * NW * S] = pre[k].x;
367                        ws_st[k * 3 * NW * S + 1] = pre[k].y;
368                    } else {
369                        ws_st[k * 3 * NW * S] = pre[k];
370                    }
371                }
372        }
373    };
374    // word wd of token t's step: d4[b0 + wd] for wd < SB, else qs word 8 b0 + (wd - SB)
375    auto load_a = [&](const int st, const int trow0, const int nt) {
376        const int kb = (st * SB) >> 2, b0 = (st * SB) & 3;   // the 128-value q8_1 block and the first 32-block in it
377#pragma unroll
378        for (int i = 0; i < AI; ++i) {
379            const int idx = threadIdx.x + i * NT;
380            if (idx < nt * AW) {
381                const int t = idx / AW, wd = idx - t * AW;
382                const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t);
383                apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB)));
384            }
385        }
386    };
387    auto store_a = [&](const int nt) {
388#pragma unroll
389        for (int i = 0; i < AI; ++i) {
390            const int idx = threadIdx.x + i * NT;
391            if (idx < nt * AW) {
392                const int t = idx / AW, wd = idx - t * AW;
393                if (wd < SB) {
394                    dy_s[t][wd] = __int_as_float(apre[i]);
395                } else {
396                    const int m = wd - SB, bb = m >> 3, mm = m & 7;
397                    int lo, hi;
398                    split01(apre[i], lo, hi);
399                    *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi);
400                }
401            }
402        }
403    };
404    load_w(0);
405    load_a(0, c.row0, min(TPP, c.rows));
406    const int* cw = wsm + threadIdx.x * S;
407    for (int p0 = 0; p0 < c.rows; p0 += TPP) {
408        const int nt = min(TPP, c.rows - p0);
409        const int trow0 = c.row0 + p0;
410        float acc[TPP];
411#pragma unroll
412        for (int t = 0; t < TPP; ++t) acc[t] = 0.0f;
413#pragma unroll 1
414        for (int st = 0; st < NSTEP; ++st) {
415            __syncthreads();
416            store_w();
417            store_a(nt);
418            __syncthreads();
419            if (st + 1 < NSTEP) {
420                load_w(st + 1);
421                load_a(st + 1, trow0, nt);
422            } else if (p0 + TPP < c.rows) {
423                load_w(0);
424                load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP));
425            }
426#pragma unroll 1
427            for (int p = 0; p < SB / 2; ++p) {
428                blk_compute<NT, TPP, SB, G, 0>(cw, p, tab, act_s, dy_s, nt, acc);
429                blk_compute<NT, TPP, SB, G, 1>(cw, p, tab, act_s, dy_s, nt, acc);
430            }
431        }
432#pragma unroll
433        for (int t = 0; t < TPP; ++t)
434            if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t];
435    }
436}
437
438// ---- STRATA_WS_FAST=1 (ws::fast(), moe_ws.hpp): the 256 x 32 tier (2-block steps, pairs of tokens) with fewer
439// instructions per pass, the same Dm rows bit for bit: every token's operations and their order are dn_kernel's.
440// (Prototyped as a bench variant on one GP100 die: memcmp-equal to dn_kernel on real IQ4_NL layers at T 1024 and
441// 1536, lognormal sigma 0.5 / 1.0 and a flat-32 control; 4.7-9.2% faster, 122 -> 102 registers, still two CTAs per
442// SM.  moe_ws_down_bench checks and times it against dn_kernel.)
443//   DUFF  a switch on the number of token pairs falls through the 16 unrolled pairs (a jump table) instead of a guard
444//         per pair and block
445//   DYT   dy as [block][token]: a pair's two dy in one LDS.64
446template <int NT, int TPP, int SB, int G, int PAR>
447__device__ __forceinline__ void blk_compute_fast(const int* __restrict__ cw, const int p, const uint32_t (&tab)[4],
448                                                 const int (*act_s)[SB][16], const float* __restrict__ dyb, const int nt,
449                                                 float (&acc)[TPP]) {
450    static_assert(TPP / G == 16 && G == 2, "the switch below: 16 token pairs");
451    const int b = 2 * p + PAR;   // block within the step
452    int wv[16];
453    float dx;
454    {
455        int q[4];
456        dx = load_blk<PAR>(cw, p, q);
457        dec(q, tab, wv);
458    }
459    // pairs past nt's run on stale shared memory and are not written, as dn_kernel's
460    auto grp = [&](auto K) {
461        constexpr int t0 = decltype(K)::value * G;
462        const float2 d2 = *(const float2*) &dyb[b * TPP + t0];
463#pragma unroll
464        for (int t = t0; t < t0 + G; ++t) {
465            const int4* a4 = (const int4*) act_s[t][b];
466            const int4 a0 = a4[0], a1 = a4[1], a2 = a4[2], a3 = a4[3];
467            int s0 = 0;
468            s0 = mad2(wv[0], a0.x, s0); s0 = mad2(wv[1], a0.y, s0); s0 = mad2(wv[2], a0.z, s0); s0 = mad2(wv[3], a0.w, s0);
469            s0 = mad2(wv[4], a1.x, s0); s0 = mad2(wv[5], a1.y, s0); s0 = mad2(wv[6], a1.z, s0); s0 = mad2(wv[7], a1.w, s0);
470            s0 = mad2(wv[8], a2.x, s0); s0 = mad2(wv[9], a2.y, s0); s0 = mad2(wv[10], a2.z, s0); s0 = mad2(wv[11], a2.w, s0);
471            s0 = mad2(wv[12], a3.x, s0); s0 = mad2(wv[13], a3.y, s0); s0 = mad2(wv[14], a3.z, s0); s0 = mad2(wv[15], a3.w, s0);
472            acc[t] = __fmaf_rn(__fmul_rn(dx, t == t0 ? d2.x : d2.y), __int2float_rn(s0), acc[t]);
473        }
474    };
475    using std::integral_constant;
476    switch ((nt + G - 1) / G) {
477        case 16: grp(integral_constant<int, 15>{}); [[fallthrough]];
478        case 15: grp(integral_constant<int, 14>{}); [[fallthrough]];
479        case 14: grp(integral_constant<int, 13>{}); [[fallthrough]];
480        case 13: grp(integral_constant<int, 12>{}); [[fallthrough]];
481        case 12: grp(integral_constant<int, 11>{}); [[fallthrough]];
482        case 11: grp(integral_constant<int, 10>{}); [[fallthrough]];
483        case 10: grp(integral_constant<int, 9>{}); [[fallthrough]];
484        case 9: grp(integral_constant<int, 8>{}); [[fallthrough]];
485        case 8: grp(integral_constant<int, 7>{}); [[fallthrough]];
486        case 7: grp(integral_constant<int, 6>{}); [[fallthrough]];
487        case 6: grp(integral_constant<int, 5>{}); [[fallthrough]];
488        case 5: grp(integral_constant<int, 4>{}); [[fallthrough]];
489        case 4: grp(integral_constant<int, 3>{}); [[fallthrough]];
490        case 3: grp(integral_constant<int, 2>{}); [[fallthrough]];
491        case 2: grp(integral_constant<int, 1>{}); [[fallthrough]];
492        case 1: grp(integral_constant<int, 0>{}); [[fallthrough]];
493        default: break;
494    }
495}
496
497// dn_kernel with blk_compute_fast and dy_s as [SB][TPP]; everything else is dn_kernel's
498template <int NT, int TPP, int SB, int G>
499__global__ void __launch_bounds__(NT, 1) dn_kernel_fast(const Chunk* __restrict__ chunks, const char* __restrict__ w,
500                                                        const int64_t* __restrict__ xoff, const int64_t xadd,
501                                                        const block_q8_1_mmq* __restrict__ xq, const int total_rows,
502                                                        float* __restrict__ dst) {
503    static_assert((SB == 2 || SB == 4) && NT % 32 == 0 && TPP % G == 0, "");
504    constexpr int NW = NT / 32, WPS = 9 * SB / 2, S = WPS | 1, NSTEP = NB / SB, PIECES = DN_ROWS / NT;
505    constexpr int KI = (NT + 3 * NW - 1) / (3 * NW);
506    constexpr int AW = 9 * SB;                     // activation words per token and step (SB d + 8 SB qs words)
507    constexpr int AI = (TPP * AW + NT - 1) / NT;
508    using PT = typename std::conditional<SB == 4, int2, int>::type;
509    __shared__ int wsm[NT * S];
510    __shared__ __align__(16) int act_s[TPP][SB][16];
511    __shared__ __align__(8) float dy_s[SB * TPP];  // [SB][TPP]: dy of token t, block b at b * TPP + t
512    uint32_t tab[4];
513    load_tab(tab);
514    int r0;
515    const Chunk c = cta_work<PIECES, NT>(chunks, r0);
516    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
517    const int sub = lane / 9, pc = lane - 9 * sub;   // sub 3: lanes 27-31, idle
518    const int srow0 = 3 * warp + sub;
519    const bool sact = sub < 3;
520    const char* __restrict__ Wg = w + xoff[c.j] + xadd + (size_t) (r0 + srow0) * ROWB + pc * (int) sizeof(PT);
521    int* __restrict__ ws_st = wsm + srow0 * S + pc * (int) (sizeof(PT) / 4);
522    PT pre[KI];
523    int apre[AI];
524    auto load_w = [&](const int st) {
525        if (sact) {
526            const char* g = Wg + st * (SB * BB);
527#pragma unroll
528            for (int k = 0; k < KI; ++k)
529                if (k < KI - 1 || srow0 + 3 * NW * k < NT) pre[k] = __ldg((const PT*) (g + (size_t) k * 3 * NW * ROWB));
530        }
531    };
532    auto store_w = [&]() {
533        if (sact) {
534#pragma unroll
535            for (int k = 0; k < KI; ++k)
536                if (k < KI - 1 || srow0 + 3 * NW * k < NT) {
537                    if constexpr (SB == 4) {
538                        ws_st[k * 3 * NW * S] = pre[k].x;
539                        ws_st[k * 3 * NW * S + 1] = pre[k].y;
540                    } else {
541                        ws_st[k * 3 * NW * S] = pre[k];
542                    }
543                }
544        }
545    };
546    auto load_a = [&](const int st, const int trow0, const int nt) {
547        const int kb = (st * SB) >> 2, b0 = (st * SB) & 3;
548#pragma unroll
549        for (int i = 0; i < AI; ++i) {
550            const int idx = threadIdx.x + i * NT;
551            if (idx < nt * AW) {
552                const int t = idx / AW, wd = idx - t * AW;
553                const int* blk = (const int*) (xq + (size_t) kb * total_rows + trow0 + t);
554                apre[i] = __ldg(blk + (wd < SB ? b0 + wd : 4 + 8 * b0 + (wd - SB)));
555            }
556        }
557    };
558    auto store_a = [&](const int nt) {
559#pragma unroll
560        for (int i = 0; i < AI; ++i) {
561            const int idx = threadIdx.x + i * NT;
562            if (idx < nt * AW) {
563                const int t = idx / AW, wd = idx - t * AW;
564                if (wd < SB) {
565                    dy_s[wd * TPP + t] = __int_as_float(apre[i]);
566                } else {
567                    const int m = wd - SB, bb = m >> 3, mm = m & 7;
568                    int lo, hi;
569                    split01(apre[i], lo, hi);
570                    *(int2*) &act_s[t][bb][2 * mm] = make_int2(lo, hi);
571                }
572            }
573        }
574    };
575    load_w(0);
576    load_a(0, c.row0, min(TPP, c.rows));
577    const int* cw = wsm + threadIdx.x * S;
578    for (int p0 = 0; p0 < c.rows; p0 += TPP) {
579        const int nt = min(TPP, c.rows - p0);
580        const int trow0 = c.row0 + p0;
581        float acc[TPP];
582#pragma unroll
583        for (int t = 0; t < TPP; ++t) acc[t] = 0.0f;
584#pragma unroll 1
585        for (int st = 0; st < NSTEP; ++st) {
586            __syncthreads();
587            store_w();
588            store_a(nt);
589            __syncthreads();
590            if (st + 1 < NSTEP) {
591                load_w(st + 1);
592                load_a(st + 1, trow0, nt);
593            } else if (p0 + TPP < c.rows) {
594                load_w(0);
595                load_a(0, trow0 + TPP, min(TPP, c.rows - p0 - TPP));
596            }
597#pragma unroll 1
598            for (int p = 0; p < SB / 2; ++p) {
599                blk_compute_fast<NT, TPP, SB, G, 0>(cw, p, tab, act_s, dy_s, nt, acc);
600                blk_compute_fast<NT, TPP, SB, G, 1>(cw, p, tab, act_s, dy_s, nt, acc);
601            }
602        }
603#pragma unroll
604        for (int t = 0; t < TPP; ++t)
605            if (t < nt) dst[(size_t) (trow0 + t) * DN_ROWS + r0 + threadIdx.x] = acc[t];
606    }
607}
608}  // namespace nl4
609
610}  // namespace
611
612// Q2_0: 8 tokens per pass below 5 rows per expert, then 16 (equal at 5)
613void dn_q2_0(const Layer& L, double u, cudaStream_t s) {
614    if (L.nchunks <= 0) return;
615    const unsigned grid = (unsigned) (L.nchunks * q20::PIECES);
616    if (u < 5.0) q20::dn_kernel<8><<<grid, q20::NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq,
617                                                            (int) L.rows, L.dm);
618    else q20::dn_kernel<16><<<grid, q20::NT, 0, s>>>(L.chunks, (const char*) L.w, L.xoff, L.down_off, (const char*) L.hq,
619                                                     (int) L.rows, L.dm);
620    ck(cudaGetLastError(), "down Q2_0");
621}
622
623// IQ4_NL: 128 rows x 8 tokens (4-block steps) below 5 rows per expert, 256 x 16 below 20, then 256 x 32 (2-block steps);
624// `fast` (STRATA_WS_FAST=1): the 256 x 32 tier runs dn_kernel_fast instead - the same Dm rows
625void dn_iq4_nl(const Layer& L, double u, cudaStream_t s, bool fast) {
626    if (L.nchunks <= 0) return;
627    const char* w = (const char*) L.w;
628    const block_q8_1_mmq* x = (const block_q8_1_mmq*) L.hq;
629    if (u < 5.0)
630        nl4::dn_kernel<128, 8, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 128)), 128, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x,
631                                                                                           (int) L.rows, L.dm);
632    else if (u < 20.0)
633        nl4::dn_kernel<256, 16, 4, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x,
634                                                                                             (int) L.rows, L.dm);
635    else if (fast)
636        nl4::dn_kernel_fast<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff,
637                                                                                                  L.down_off, x,
638                                                                                                  (int) L.rows, L.dm);
639    else
640        nl4::dn_kernel<256, 32, 2, 2><<<(unsigned) (L.nchunks * (DN_ROWS / 256)), 256, 0, s>>>(L.chunks, w, L.xoff, L.down_off, x,
641                                                                                             (int) L.rows, L.dm);
642    ck(cudaGetLastError(), "down IQ4_NL");
643}
644
645}  // namespace strata::prefill::ws::detail