okami.mom/strata

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

Niko1221moe_iq4_w4a8: the device side compiles for sm_60..75 targets (a trap there, as moe_fused_iq.cu does; arch_ok() already declines those cards, so no behaviour changes): the CUDA 12 and CUDA 13 release engines build again8a42a9457

main
23.2 KiB495 linesraw
1// src/prefill/moe_iq4_w4a8.cu - see include/strata/prefill/moe_iq4_w4a8.hpp.
2//
3// llama.cpp's MMQ runs these products at 1 CTA of 8 warps per SM with every load synchronous (load the 256-value
4// tile, convert it to int8 in shared memory, sync, MMA, sync): ~28 % (gate/up) and ~19 % (down) of the int8 peak on a
5// 3090.  This kernel computes the same sums with a different schedule:
6//   - CTA = 128 weight rows x up to BN tokens of one expert; warp w owns rows 16w..16w+15 and all of the tile's
7//     tokens, so its A fragments (the weights) are converted once per K step and used for every token tile, in
8//     registers;
9//   - 128-value K steps through a cp.async pipeline (raw IQ4 rows + the q8_1 activation rows), one barrier per step;
10//     the weights are read where they lie (pointer table) and never copied to an int8 tile;
11//   - the token tiles of the last, partial tile are skipped (one instantiation per count of 8-token tiles).
12// The arithmetic is MMQ's, step for step: per 32-value block the exact int32 dot (mma.m16n8k32), then
13// sum += (float) dot * d_w * d_y with d_w = f16 d * (ls - 32) (IQ4_XS) or f16 d (IQ4_NL), blocks in K order, one
14// accumulator per output from K = 0 - as mul_mat_q_process_tile + vec_dot_q8_0_q8_1_mma (Turing+ path) do when the
15// launch tiles (no stream-k split).  EPI 0 does it as MMQ's SASS does (I2FP, FMUL, FFMA).  EPI 1 needs two FFMAs: the
16// MMA's C starts at the bits of M = 1.5 * 2^23, so the result read as a float is x = M + dot exactly (|dot| <=
17// 32 * 127 * 127 < 2^22), and fma(x, d_w, -M * d_w) = round(x * d_w - M * d_w) = round(dot * d_w) - the FMUL's value -
18// because -M * d_w is exact: d_w = f16 d * (ls - 32) has at most 11 + 6 significant bits (IQ4_NL: 11), so 3 * 2^22 *
19// d_w fits a float's 24.  Then sum += t * d_y as before.  The int8 lookup is llama.cpp's get_int_from_table_16 (MIT).
20#include "strata/prefill/moe_iq4_w4a8.hpp"
21
22#if defined(GGML_USE_HIP)
23// The gfx906 HIP build compiles every CUDA source of the tree as HIP: this kernel is NVIDIA PTX (mma.sync, cp.async),
24// so there it declines every product and the MMQ path runs as before.
25namespace strata::prefill::mmq {
26int iq4_w4a8_mode() { return 0; }
27bool run_iq4_w4a8(const Product&, void*) { return false; }
28}  // namespace strata::prefill::mmq
29#else
30
31#include "ggml.h"
32
33#include <cuda_fp16.h>
34#include <cuda_runtime.h>
35
36#include <climits>
37#include <cstdint>
38#include <cstdio>
39#include <cstdlib>
40#include <cstring>
41#include <atomic>
42#include <mutex>
43
44namespace strata::prefill::mmq {
45namespace {
46
47constexpr int kThreads = 256;           // 8 warps x 16 weight rows
48constexpr int kBM = 128;                // weight rows per CTA
49constexpr int kYRow = 144;              // one block_q8_1_mmq row: 4 f32 scales + 128 int8
50
51// WROW: shared bytes per weight row and K step (72 of data; 80 = conflict-free A reads, 72 = 2-way on 2 lanes but
52// the cp.async writes 2-way instead of 4-way); LOOP 0: per token tile 4 MMAs then their epilogue, LOOP 1: one flat
53// software-pipelined sequence - MMA s, then the epilogue of MMA s - 2, the next tile's B two MMAs ahead
54template <int BN_, int STAGES_, int MINB_, int EPI_, int WROW_, int LOOP_>
55struct Cfg {
56    static constexpr int BN = BN_, STAGES = STAGES_, MINB = MINB_, EPI = EPI_, WROW = WROW_, LOOP = LOOP_;
57    static constexpr int WStage = kBM * WROW;
58    static constexpr int YStage = BN * kYRow;
59    static constexpr int Stage = WStage + YStage;
60    static constexpr int Smem = STAGES * Stage;
61};
62
63struct Tab16 {
64    const char* p[kGatherGroupMax];
65};
66
67// cp.async, ldmatrix and mma.sync s8 need sm_80: below it (the sm_60..75 targets of the CUDA 12 and CUDA 13 release engines) the
68// device side is a trap, never launched because arch_ok() declines those cards on the host
69__device__ __forceinline__ void cp8(uint32_t dst, const void* src) {
70#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
71    __trap();   // never launched below sm_80: arch_ok() declines those cards
72#else
73    asm volatile("cp.async.ca.shared.global [%0], [%1], 8;\n" ::"r"(dst), "l"(src));
74#endif
75}
76__device__ __forceinline__ void cp16(uint32_t dst, const void* src) {
77#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
78    __trap();   // never launched below sm_80: arch_ok() declines those cards
79#else
80    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(dst), "l"(src));
81#endif
82}
83__device__ __forceinline__ void cp_commit() {
84#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
85    __trap();   // never launched below sm_80: arch_ok() declines those cards
86#else
87    asm volatile("cp.async.commit_group;\n" ::);
88#endif
89}
90template <int N>
91__device__ __forceinline__ void cp_wait() {
92#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
93    __trap();   // never launched below sm_80: arch_ok() declines those cards
94#else
95    asm volatile("cp.async.wait_group %0;\n" ::"n"(N) : "memory");
96#endif
97}
98__device__ __forceinline__ void ldsm4(uint32_t& r0, uint32_t& r1, uint32_t& r2, uint32_t& r3, uint32_t addr) {
99#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
100    r0 = r1 = r2 = r3 = 0;
101    __trap();   // never launched below sm_80: arch_ok() declines those cards
102#else
103    asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n"
104                 : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3)
105                 : "r"(addr));
106#endif
107}
108__device__ __forceinline__ void lds128(float4& v, uint32_t addr) {
109    asm volatile("ld.shared.v4.f32 {%0, %1, %2, %3}, [%4];\n" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "r"(addr));
110}
111template <uint32_t C0>
112__device__ __forceinline__ void mma_s8(int (&c)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
113#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
114    c[0] = c[1] = c[2] = c[3] = 0;
115    __trap();   // never launched below sm_80: arch_ok() declines those cards
116#else
117    asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, "
118        "{%10, %10, %10, %10};\n"
119        : "=r"(c[0]), "=r"(c[1]), "=r"(c[2]), "=r"(c[3])
120        : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(C0));
121#endif
122}
123
124constexpr uint32_t kMagicBits = 0x4B400000u;   // 1.5 * 2^23
125constexpr float kMagic = 12582912.0f;
126
127
128// kvalues_iq4nl {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113} as 4 little-endian words
129constexpr uint32_t kT0 = 0xBFAD9881u, kT1 = 0xF6EADDCFu, kT2 = 0x26190D01u, kT3 = 0x71594535u;
130
131// 8 packed nibbles (byte i = value i low, value i + 16 high) -> lo: the 4 low nibbles' int8, hi: the 4 high ones'
132// (llama.cpp get_int_from_table_16, MIT)
133__device__ __forceinline__ void lut16(uint32_t q, uint32_t& lo, uint32_t& hi) {
134    const uint32_t sel = 0x32103210u | ((q & 0x88888888u) >> 1);
135    const uint32_t l0 = __byte_perm(kT0, kT1, q), h0 = __byte_perm(kT2, kT3, q);
136    const uint32_t l1 = __byte_perm(kT0, kT1, q >> 16), h1 = __byte_perm(kT2, kT3, q >> 16);
137    const uint32_t m0 = __byte_perm(l0, h0, sel), m1 = __byte_perm(l1, h1, sel >> 16);
138    lo = __byte_perm(m0, m1, 0x6420);
139    hi = __byte_perm(m0, m1, 0x7531);
140}
141
142__device__ __forceinline__ float sel4(const float4& v, int i) {
143    return i == 0 ? v.x : i == 1 ? v.y : i == 2 ? v.z : v.w;
144}
145
146// one CTA tile: weight rows row0..row0+127 of expert matrix w, the tile's tokens = activation rows yrow0..yrow0+nv-1
147template <bool XS, class C, int NT>
148__device__ __forceinline__ void tile(const char* __restrict__ w, const char* __restrict__ y,
149                                     const int32_t* __restrict__ ids, float* __restrict__ dst, int64_t ld_dst,
150                                     int row0, int nk, int64_t row_bytes, int64_t ncols_y, int yrow0, int nv,
151                                     unsigned char* smem) {
152    const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, t = lane & 3;
153    const uint32_t s0 = (uint32_t) __cvta_generic_to_shared(smem);
154    const int my_r = tid & (kBM - 1), my_p0 = tid >> 7;
155    const char* my_row = w + (int64_t) (row0 + my_r) * row_bytes;
156
157    auto issue = [&](int kb, int st) {
158        const uint32_t sw = s0 + st * C::Stage, sy = sw + C::WStage;
159        // weights: 128 rows x 9 pieces of 8 bytes (IQ4_XS: the super-block's 8-byte header + this half's 64 qs
160        // bytes; IQ4_NL: 4 blocks of 18 bytes)
161        // (thread tid copies pieces tid/128, +2, +4, ... of row tid % 128)
162        const uint32_t dw = sw + my_r * C::WROW;
163        const char* rk = XS ? my_row + (int64_t) (kb >> 1) * 136 : my_row + (int64_t) kb * 72;
164#pragma unroll
165        for (int p = my_p0; p < 9; p += 2) {
166            const char* src;
167            if constexpr (XS) src = p == 0 ? rk : rk + 8 + (kb & 1) * 64 + (p - 1) * 8;
168            else src = rk + p * 8;
169            cp8(dw + p * 8, src);
170        }
171        // activations: the tile's rows are consecutive in each 128-value block of the q8_1 array
172        const char* yk = y + ((int64_t) kb * ncols_y + yrow0) * kYRow;
173#pragma unroll
174        for (int i = tid; i < NT * 8 * 9; i += kThreads) cp16(sy + i * 16, yk + (int64_t) i * 16);
175    };
176
177    float acc[NT][4];
178#pragma unroll
179    for (int n = 0; n < NT; ++n) acc[n][0] = acc[n][1] = acc[n][2] = acc[n][3] = 0.0f;
180
181#pragma unroll
182    for (int s = 0; s < C::STAGES - 1; ++s) {
183        if (s < nk) issue(s, s);
184        cp_commit();
185    }
186
187    for (int kb = 0; kb < nk; ++kb) {
188        cp_wait<C::STAGES - 2>();
189        __syncthreads();
190        {
191            const int kn = kb + C::STAGES - 1;
192            if (kn < nk) issue(kn, kn % C::STAGES);
193            cp_commit();
194        }
195        const int st = kb % C::STAGES;
196        const unsigned char* W = smem + st * C::Stage + warp * 16 * C::WROW;
197        const unsigned char* Wg = W + g * C::WROW;
198        const unsigned char* Wg8 = W + (g + 8) * C::WROW;
199        const uint32_t sy = s0 + st * C::Stage + C::WStage;
200
201        // this warp's A fragments and weight scales for the step's 4 blocks
202        uint32_t a[4][4];
203        float da[4][2], nm[4][2];
204        if constexpr (XS) {
205            const int h = kb & 1;
206            const float d0 = __half2float(*(const __half*) Wg), d1 = __half2float(*(const __half*) Wg8);
207            const uint32_t sh0 = *(const uint16_t*) (Wg + 2), sh1 = *(const uint16_t*) (Wg8 + 2);
208            const uint32_t sl0 = *(const uint32_t*) (Wg + 4), sl1 = *(const uint32_t*) (Wg8 + 4);
209#pragma unroll
210            for (int b = 0; b < 4; ++b) {
211                const int ib = 4 * h + b;   // the block in its super-block
212                const int ls0 = ((sl0 >> (4 * ib)) & 0x0F) | (((sh0 >> (2 * ib)) & 0x03) << 4);
213                const int ls1 = ((sl1 >> (4 * ib)) & 0x0F) | (((sh1 >> (2 * ib)) & 0x03) << 4);
214                da[b][0] = d0 * (ls0 - 32);
215                da[b][1] = d1 * (ls1 - 32);
216                const uint32_t q0 = *(const uint32_t*) (Wg + 8 + 16 * b + 4 * t);
217                const uint32_t q1 = *(const uint32_t*) (Wg8 + 8 + 16 * b + 4 * t);
218                lut16(q0, a[b][0], a[b][2]);
219                lut16(q1, a[b][1], a[b][3]);
220            }
221        } else {
222#pragma unroll
223            for (int b = 0; b < 4; ++b) {
224                da[b][0] = __half2float(*(const __half*) (Wg + 18 * b));
225                da[b][1] = __half2float(*(const __half*) (Wg8 + 18 * b));
226                const int o = 18 * b + 2 + 4 * t;   // 2-byte aligned for even b
227                uint32_t q0, q1;
228                if (b & 1) {
229                    q0 = *(const uint32_t*) (Wg + o);
230                    q1 = *(const uint32_t*) (Wg8 + o);
231                } else {
232                    q0 = (uint32_t) *(const uint16_t*) (Wg + o) | ((uint32_t) *(const uint16_t*) (Wg + o + 2) << 16);
233                    q1 = (uint32_t) *(const uint16_t*) (Wg8 + o) | ((uint32_t) *(const uint16_t*) (Wg8 + o + 2) << 16);
234                }
235                lut16(q0, a[b][0], a[b][2]);
236                lut16(q1, a[b][1], a[b][3]);
237            }
238        }
239        if constexpr (C::EPI == 1) {
240#pragma unroll
241            for (int b = 0; b < 4; ++b) {
242                nm[b][0] = -kMagic * da[b][0];
243                nm[b][1] = -kMagic * da[b][1];
244            }
245        }
246
247        if constexpr (C::LOOP == 1) {
248            uint32_t bq[2][4][2];
249            float4 dq[2][2];
250            auto load_b = [&](int n, int buf) {
251                lds128(dq[buf][0], sy + (n * 8 + 2 * t) * kYRow);
252                lds128(dq[buf][1], sy + (n * 8 + 2 * t + 1) * kYRow);
253                const uint32_t ra = sy + (n * 8 + (lane & 7)) * kYRow + 16 + 32 * (lane >> 4) + 16 * ((lane >> 3) & 1);
254                ldsm4(bq[buf][0][0], bq[buf][0][1], bq[buf][1][0], bq[buf][1][1], ra);
255                ldsm4(bq[buf][2][0], bq[buf][2][1], bq[buf][3][0], bq[buf][3][1], ra + 64);
256            };
257            int cr[3][4];
258            load_b(0, 0);
259#pragma unroll
260            for (int s = 0; s < NT * 4 + 2; ++s) {
261                if (s < NT * 4) {
262                    const int n = s >> 2, k = s & 3;
263                    // tile n + 1's B into the buffer tile n - 1 used: its last MMA was s - 3, its last epilogue s - 1
264                    if (k == 2 && n + 1 < NT) load_b(n + 1, (n + 1) & 1);
265                    mma_s8<C::EPI == 1 ? kMagicBits : 0u>(cr[s % 3], a[k], bq[n & 1][k][0], bq[n & 1][k][1]);
266                }
267                if (s >= 2) {
268                    const int e = s - 2, n = e >> 2, k = e & 3;
269                    const int* c = cr[e % 3];
270                    const float y0 = sel4(dq[n & 1][0], k), y1 = sel4(dq[n & 1][1], k);
271                    if constexpr (C::EPI == 1) {
272                        const float t0 = __fmaf_rn(__int_as_float(c[0]), da[k][0], nm[k][0]);
273                        const float t1 = __fmaf_rn(__int_as_float(c[1]), da[k][0], nm[k][0]);
274                        const float t2 = __fmaf_rn(__int_as_float(c[2]), da[k][1], nm[k][1]);
275                        const float t3 = __fmaf_rn(__int_as_float(c[3]), da[k][1], nm[k][1]);
276                        acc[n][0] += t0 * y0;
277                        acc[n][1] += t1 * y1;
278                        acc[n][2] += t2 * y0;
279                        acc[n][3] += t3 * y1;
280                    } else {
281                        acc[n][0] += c[0] * da[k][0] * y0;
282                        acc[n][1] += c[1] * da[k][0] * y1;
283                        acc[n][2] += c[2] * da[k][1] * y0;
284                        acc[n][3] += c[3] * da[k][1] * y1;
285                    }
286                }
287            }
288        } else {
289#pragma unroll
290        for (int n = 0; n < NT; ++n) {
291            float4 db0, db1;
292            lds128(db0, sy + (n * 8 + 2 * t) * kYRow);
293            lds128(db1, sy + (n * 8 + 2 * t + 1) * kYRow);
294            uint32_t b[4][2];
295            const uint32_t ra = sy + (n * 8 + (lane & 7)) * kYRow + 16 + 32 * (lane >> 4) + 16 * ((lane >> 3) & 1);
296            ldsm4(b[0][0], b[0][1], b[1][0], b[1][1], ra);
297            ldsm4(b[2][0], b[2][1], b[3][0], b[3][1], ra + 64);
298            int c[4][4];
299#pragma unroll
300            for (int k = 0; k < 4; ++k) mma_s8<C::EPI == 1 ? kMagicBits : 0u>(c[k], a[k], b[k][0], b[k][1]);
301#pragma unroll
302            for (int k = 0; k < 4; ++k) {
303                const float y0 = sel4(db0, k), y1 = sel4(db1, k);
304                if constexpr (C::EPI == 1) {
305                    const float t0 = __fmaf_rn(__int_as_float(c[k][0]), da[k][0], nm[k][0]);
306                    const float t1 = __fmaf_rn(__int_as_float(c[k][1]), da[k][0], nm[k][0]);
307                    const float t2 = __fmaf_rn(__int_as_float(c[k][2]), da[k][1], nm[k][1]);
308                    const float t3 = __fmaf_rn(__int_as_float(c[k][3]), da[k][1], nm[k][1]);
309                    acc[n][0] += t0 * y0;
310                    acc[n][1] += t1 * y1;
311                    acc[n][2] += t2 * y0;
312                    acc[n][3] += t3 * y1;
313                } else {
314                    acc[n][0] += c[k][0] * da[k][0] * y0;
315                    acc[n][1] += c[k][1] * da[k][0] * y1;
316                    acc[n][2] += c[k][2] * da[k][1] * y0;
317                    acc[n][3] += c[k][3] * da[k][1] * y1;
318                }
319            }
320        }
321        }
322    }
323    cp_wait<0>();
324
325    const int r = row0 + warp * 16 + g;
326#pragma unroll
327    for (int n = 0; n < NT; ++n) {
328        const int j = n * 8 + 2 * t;
329        if (j < nv) {
330            float* o = dst + (int64_t) ids[yrow0 + j] * ld_dst + r;
331            o[0] = acc[n][0];
332            o[8] = acc[n][2];
333        }
334        if (j + 1 < nv) {
335            float* o = dst + (int64_t) ids[yrow0 + j + 1] * ld_dst + r;
336            o[0] = acc[n][1];
337            o[8] = acc[n][3];
338        }
339    }
340}
341
342// grid: (row tile, token tile, expert) with the row tile fastest; tiles past an expert's rows return at once
343template <bool XS, class C>
344__global__ void __launch_bounds__(kThreads, C::MINB)
345    iq4_w4a8_kernel(Tab16 tab, const char* __restrict__ y, const int32_t* __restrict__ ids,
346                    const int32_t* __restrict__ bounds, float* __restrict__ dst, int64_t ld_dst, int nk,
347                    int64_t row_bytes, int64_t ncols_y, int nty, int ntx) {
348#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800
349    __trap();   // never launched below sm_80: arch_ok() declines those cards
350#else
351    extern __shared__ __align__(16) unsigned char smem[];
352    const int it = blockIdx.x % nty, rest = blockIdx.x / nty;
353    const int jt = rest % ntx, z = rest / ntx;
354    const int lo = bounds[z], cnt = bounds[z + 1] - lo;
355    const int j0 = jt * C::BN;
356    if (j0 >= cnt) return;
357    const int nv = min(C::BN, cnt - j0);
358    const char* w = tab.p[0];
359#pragma unroll
360    for (int i = 1; i < kGatherGroupMax; ++i)
361        if (i == z) w = tab.p[i];
362    const int row0 = it * kBM, yrow0 = lo + j0;
363    const int nt = (nv + 7) >> 3;
364#define STRATA_W4A8_NT(n) \
365    if constexpr (n * 8 <= C::BN) { \
366        if (nt == n) { tile<XS, C, n>(w, y, ids, dst, ld_dst, row0, nk, row_bytes, ncols_y, yrow0, nv, smem); return; } \
367    }
368    STRATA_W4A8_NT(1) STRATA_W4A8_NT(2) STRATA_W4A8_NT(3) STRATA_W4A8_NT(4)
369    STRATA_W4A8_NT(5) STRATA_W4A8_NT(6) STRATA_W4A8_NT(7) STRATA_W4A8_NT(8)
370    STRATA_W4A8_NT(9) STRATA_W4A8_NT(10) STRATA_W4A8_NT(11) STRATA_W4A8_NT(12)
371    STRATA_W4A8_NT(13) STRATA_W4A8_NT(14) STRATA_W4A8_NT(15) STRATA_W4A8_NT(16)
372#undef STRATA_W4A8_NT
373#endif
374}
375
376// configurations (STRATA_W4A8_CFG): 1 CTA/SM, 2 stages, two FFMAs (EPI 1), rows of 72 bytes, the pipelined loop;
377// tokens per CTA 0 = 128, 1 = 104, 2 = 112, 3 = 96
378using Cfg0 = Cfg<128, 2, 1, 1, 72, 1>;
379using Cfg1 = Cfg<104, 2, 1, 1, 72, 1>;
380using Cfg2 = Cfg<112, 2, 1, 1, 72, 1>;
381using Cfg3 = Cfg<96, 2, 1, 1, 72, 1>;
382
383int cfg_index() {
384    static const int c = [] {
385        const char* v = std::getenv("STRATA_W4A8_CFG");
386        const int i = v != nullptr ? std::atoi(v) : 0;
387        return i >= 0 && i <= 3 ? i : 0;
388    }();
389    return c;
390}
391
392template <class C>
393void set_smem() {
394    cudaFuncSetAttribute(iq4_w4a8_kernel<true, C>, cudaFuncAttributeMaxDynamicSharedMemorySize, C::Smem);
395    cudaFuncSetAttribute(iq4_w4a8_kernel<false, C>, cudaFuncAttributeMaxDynamicSharedMemorySize, C::Smem);
396}
397
398// per device, once: SM count, compute capability, the configs' shared-memory opt-in (the engine drives both GPUs)
399int device_info(int& nsm) {
400    constexpr int kMaxDev = 16;
401    static std::once_flag once[kMaxDev];
402    static int nsm_d[kMaxDev], cc_d[kMaxDev];
403    int dev = 0;
404    cudaGetDevice(&dev);
405    if (dev < 0 || dev >= kMaxDev) return 0;
406    std::call_once(once[dev], [dev] {
407        cudaDeviceProp prop{};
408        cudaGetDeviceProperties(&prop, dev);
409        nsm_d[dev] = prop.multiProcessorCount;
410        cc_d[dev] = prop.major * 10 + prop.minor;
411        set_smem<Cfg0>();
412        set_smem<Cfg1>();
413        set_smem<Cfg2>();
414        set_smem<Cfg3>();
415    });
416    nsm = nsm_d[dev];
417    return cc_d[dev];
418}
419
420template <class C>
421void launch(bool xs, const Tab16& tab, const Product& p, int64_t row_bytes, cudaStream_t s) {
422    const int nty = (int) (p.w_rows / kBM), ntx = (int) ((p.max_rows + C::BN - 1) / C::BN);
423    const dim3 grid((unsigned) (nty * ntx * p.n));
424    const int nk = (int) (p.w_cols / 128);
425    if (xs)
426        iq4_w4a8_kernel<true, C><<<grid, kThreads, C::Smem, s>>>(tab, (const char*) p.xq, p.ids, p.bounds, p.dst,
427                                                                 p.ld_dst, nk, row_bytes, p.total_rows, nty, ntx);
428    else
429        iq4_w4a8_kernel<false, C><<<grid, kThreads, C::Smem, s>>>(tab, (const char*) p.xq, p.ids, p.bounds, p.dst,
430                                                                  p.ld_dst, nk, row_bytes, p.total_rows, nty, ntx);
431}
432
433}  // namespace
434
435// the compute capabilities the kernel's bits were checked against MMQ's on (prefill_iq4_w4a8_test): Ampere (8.0-8.8) and
436// Blackwell 12.0; Ada (8.9) has no card to test on, so it keeps MMQ
437static bool arch_ok(int cc) { return (cc >= 80 && cc < 89) || cc == 120; }
438
439void report_counts();
440int iq4_w4a8_mode() {
441    static const int m = [] {
442        const char* v = std::getenv("STRATA_IQ4_W4A8");
443        const int r = v != nullptr ? std::atoi(v) : 0;
444        if (r == 1 || r == 2)
445            std::fprintf(stderr, "strata: prompt experts: the IQ4 W4A8 kernel runs %s (STRATA_IQ4_W4A8=%d, config %d; "
446                                 "MMQ's bits)\n", r == 1 ? "the IQ4_XS and IQ4_NL products" : "the IQ4_NL (down) products",
447                         r, cfg_index());
448        if (r == 1 || r == 2) std::atexit(report_counts);
449        return r == 1 || r == 2 ? r : 0;
450    }();
451    return m;
452}
453
454// dispatch counters (the path ran / why it declined), printed once at exit when the kernel is on
455std::atomic<long long> g_ran[2], g_declined[6];   // ran: [IQ4_XS, IQ4_NL]; declined: shape, scales, arch, splits-K, alignment, type
456const char* const kWhy[6] = {"shape", "NVFP4 scales", "architecture", "MMQ would split K", "alignment", "other type"};
457void report_counts() {
458    std::fprintf(stderr, "strata: IQ4 W4A8 kernel: ran %lld IQ4_XS and %lld IQ4_NL products; declined", g_ran[0].load(), g_ran[1].load());
459    for (int i = 0; i < 6; ++i) std::fprintf(stderr, " %s %lld%s", kWhy[i], g_declined[i].load(), i < 5 ? "," : "");
460    std::fprintf(stderr, " (MMQ ran those)\n");
461}
462bool decline(int why) { g_declined[why].fetch_add(1, std::memory_order_relaxed); return false; }
463
464bool run_iq4_w4a8(const Product& p, void* stream) {
465    const bool xs = p.type == GGML_TYPE_IQ4_XS;
466    if (!xs && p.type != GGML_TYPE_IQ4_NL) return decline(5);
467    if (p.n <= 0 || p.n > kGatherGroupMax || p.max_rows <= 0) return decline(0);
468    if (p.w_rows % kBM != 0 || p.w_cols % (xs ? 256 : 128) != 0) return decline(0);
469    if (p.y_scale != nullptr) return decline(1);   // (NVFP4 w4a4 scales: not an IQ4 product)
470    int nsm = 0;
471    const int cc = device_info(nsm);
472    if (!arch_ok(cc)) return decline(2);
473    if (launch_splits_k(p.type, p.w_rows, p.max_rows, p.n)) return decline(3);   // MMQ's stream-k fixup adds the sums in another order
474    const int64_t row_bytes = p.w_cols / (xs ? 256 : 32) * (xs ? 136 : 18);
475    Tab16 tab{};
476    for (int z = 0; z < p.n; ++z) {
477        tab.p[z] = p.tab ? (const char*) p.tab->p[z] : (const char*) p.w + (size_t) z * p.expert_bytes;
478        if (((uintptr_t) tab.p[z] & 7) != 0) return decline(4);   // 8-byte cp.async pieces
479    }
480    for (int z = p.n; z < kGatherGroupMax; ++z) tab.p[z] = tab.p[0];
481    if ((((uintptr_t) p.xq) & 15) != 0) return decline(4);
482    const cudaStream_t s = (cudaStream_t) stream;
483    switch (cfg_index()) {
484        case 1: launch<Cfg1>(xs, tab, p, row_bytes, s); break;
485        case 2: launch<Cfg2>(xs, tab, p, row_bytes, s); break;
486        case 3: launch<Cfg3>(xs, tab, p, row_bytes, s); break;
487        default: launch<Cfg0>(xs, tab, p, row_bytes, s); break;
488    }
489    g_ran[xs ? 0 : 1].fetch_add(1, std::memory_order_relaxed);
490    return true;
491}
492
493}  // namespace strata::prefill::mmq
494
495#endif  // GGML_USE_HIP