okami.mom/strata

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

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

main
29.2 KiB633 linesraw
1// src/prefill/moe_mmq.cu - see include/strata/prefill/moe_mmq.hpp.  llama.cpp's MMQ (ggml-cuda, MIT) is compiled
2// from the pinned llama.cpp checkout the build already takes ggml from; src/prefill/ggml_cuda_host.cu supplies the
3// few host symbols of ggml-cuda.cu it references.
4#include "strata/prefill/moe_mmq.hpp"
5
6#include "common.cuh"
7#include "mmq.cuh"
8#include "quantize.cuh"
9#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
10#include "moe_mmq_tab.hpp"   // declarations only: the tab kernels live in the per-type mmq-tab-*.cu TUs
11#endif
12#include "strata/prefill/moe_fused.hpp"   // kMoeEmbd, kMoeFF: the compiled geometry's widths
13#include "strata/prefill/moe_iq4_w4a8.hpp"
14
15#include "strata/prefill/mmq_kq_abi.hpp"
16
17#include <algorithm>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21
22namespace strata::prefill::mmq {
23namespace {
24// The Gyro trellis types (ids 144-146) are outside the type table of an upstream ggml (indexed by the id): their block
25// geometry is known here (128 weights; 34 / 26 / 30 bytes), everything else asks ggml.
26inline bool is_tq(int t) { return t >= 144 && t <= 149; }   // 144-146 TQ/TQK, 147-149 the pair trellis (Gyro-L)
27inline int64_t type_blck(int t) { return is_tq(t) ? 128 : (int64_t) ggml_blck_size((ggml_type) t); }
28inline size_t type_bytes(int t) {
29    return t == 144 ? 34 : t == 145 ? 26 : t == 146 ? 30 : t == 147 ? 42 : t == 148 ? 50 : t == 149 ? 58
30                                                                                     : ggml_type_size((ggml_type) t);
31}
32inline const char* type_label(int t) {
33    return t == 144 ? "tq2_t" : t == 145 ? "tqk6" : t == 146 ? "tqk7"
34         : t == 147 ? "tqp5" : t == 148 ? "tqp6" : t == 149 ? "tqp7" : ggml_type_name((ggml_type) t);
35}
36}  // namespace
37#if defined(STRATA_KQ_DSO)
38namespace kq {
39int abi_args_size() { return (int) sizeof(mmq_args); }
40}  // namespace kq
41#endif
42namespace {
43#if defined(STRATA_MMQ_KQUANTS)
44// MODEL-UPDATE Phase 1: the K-quant products through MMQ are opt-in at run time (STRATA_MMQ_KQ=1); on CUDA their
45// kernels are the strata_kq library (mmq_kq_loader.cpp), opened only then
46bool kq_ok() {
47#if defined(STRATA_KQ_DSO)
48    return kq::available();
49#else
50    static const bool on = [] {
51        const char* v = std::getenv("STRATA_MMQ_KQ");
52        return v != nullptr && v[0] == '1';
53    }();
54    return on;
55#endif
56}
57#endif
58
59void ck(cudaError_t e, const char* what) {
60    if (e != cudaSuccess) {
61        std::fprintf(stderr, "prefill mmq: %s: %s\n", what, cudaGetErrorString(e));
62        std::exit(1);
63    }
64}
65
66int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; }
67
68#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
69// swiglu_kernel (n_ff 640), then quantize_mmq_q8_1<D4>'s rows of its output, in one pass: a block per row (128
70// threads, 4 values each, blockIdx.y the row's 512-value half), H never stored.  Each value is swiglu_kernel's
71// expression and each 32-value block quantize_mmq_q8_1's (the same unit and flags: the same bits).
72template <bool IL>
73__global__ void __launch_bounds__(128) swiglu_quant_kernel(const float* __restrict__ gu, block_q8_1_mmq* __restrict__ y,
74                                                           int64_t rows) {
75    constexpr int64_t n_ff = 640, ne0 = 1024;   // the padded row: pad512(640)
76    const int64_t i0 = ((int64_t) blockDim.x * blockIdx.y + threadIdx.x) * 4;
77    if (i0 >= ne0) return;
78    const int64_t r = blockIdx.x;
79    float4 xi = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
80    if (i0 < n_ff) {
81        const float* row = gu + r * 2 * n_ff;
82        float4 g4, u4;
83        if constexpr (IL) {   // gate 2k, up 2k + 1
84            const float4 a = *reinterpret_cast<const float4*>(row + 2 * i0), b = *reinterpret_cast<const float4*>(row + 2 * i0 + 4);
85            g4 = make_float4(a.x, a.z, b.x, b.z);
86            u4 = make_float4(a.y, a.w, b.y, b.w);
87        } else {
88            g4 = *reinterpret_cast<const float4*>(row + i0);
89            u4 = *reinterpret_cast<const float4*>(row + n_ff + i0);
90        }
91        xi.x = g4.x / (1.0f + __expf(-g4.x)) * u4.x;
92        xi.y = g4.y / (1.0f + __expf(-g4.y)) * u4.y;
93        xi.z = g4.z / (1.0f + __expf(-g4.z)) * u4.z;
94        xi.w = g4.w / (1.0f + __expf(-g4.w)) * u4.w;
95    }
96    float amax = fabsf(xi.x);
97    amax = fmaxf(amax, fabsf(xi.y));
98    amax = fmaxf(amax, fabsf(xi.z));
99    amax = fmaxf(amax, fabsf(xi.w));
100#pragma unroll
101    for (int offset = 32 / 8; offset > 0; offset >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE));
102    const float d_inv = 127.0f / amax;
103    char4 c;
104    c.x = roundf(xi.x * d_inv);
105    c.y = roundf(xi.y * d_inv);
106    c.z = roundf(xi.z * d_inv);
107    c.w = roundf(xi.w * d_inv);
108    const float d = 1.0f / d_inv;
109    const int64_t k_block = i0 / QK8_1_MMQ, iqs = i0 % QK8_1_MMQ;
110    block_q8_1_mmq* yb = y + k_block * rows + r;
111    reinterpret_cast<char4*>(yb->qs)[iqs / 4] = c;
112    if (iqs % 32 == 0) yb->d4[iqs / 32] = d;
113}
114#endif
115
116#if defined(__HIPCC__)   // #820: only the HIP dense-MMQ path (Gemm::native_mmq) uses these two
117__global__ void f16_to_f32_kernel(const uint16_t* __restrict__ x, float* __restrict__ y, int64_t n) {
118    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
119    if (i < n) y[i] = __half2float(__ushort_as_half(x[i]));
120}
121
122__global__ void set_bounds_kernel(int32_t* d, int32_t rows) {
123    d[0] = 0;
124    d[1] = rows;
125}
126
127#endif
128
129unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
130
131#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
132// STRATA_MMQ_DIRECT: a group's guards (y < g.n, byte stores) and its two zero tails (y == g.n: gate/up, y == g.n + 1:
133// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned).  Only in a
134// STRATA_MMQ_TAB build: the engine loads every kernel at start (EAGER), so a build without it keeps today's image.
135__global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, uint8_t* tail_d, int64_t tail, bool tail16) {
136    const int y = (int) blockIdx.y;
137    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
138    if (y < g.n) {
139        if (i < guard) g.p[y][i] = 0;
140        return;
141    }
142    uint8_t* t = y == g.n ? tail_gu : tail_d;
143    if (t == nullptr) return;
144    if (tail16) {
145        if (i < tail / 16) ((uint4*) t)[i] = make_uint4(0, 0, 0, 0);
146    } else if (i < tail) {
147        t[i] = 0;
148    }
149}
150
151// the pointer-table MMQ per type: the native packs' nine types (CMake's _strata_mmq_tab_types, all of them checked
152// bit for bit by prefill_mmq_tab_test).  false: no instance - the optional Q5_0 and K-quant experts keep the gather
153bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* tab, cudaStream_t s) {
154    const ggml_type t = a ? a->type_x : GGML_TYPE_COUNT;
155#define STRATA_TAB_CASE(T) case T: return ctx == nullptr || mul_mat_q_tab_case<T>(*ctx, *a, *tab, s)
156    switch (t) {
157        STRATA_TAB_CASE(GGML_TYPE_Q2_0);
158        STRATA_TAB_CASE(GGML_TYPE_IQ2_XXS);
159        STRATA_TAB_CASE(GGML_TYPE_IQ2_XS);
160        STRATA_TAB_CASE(GGML_TYPE_IQ2_S);
161        STRATA_TAB_CASE(GGML_TYPE_IQ3_XXS);
162        STRATA_TAB_CASE(GGML_TYPE_IQ3_S);
163        STRATA_TAB_CASE(GGML_TYPE_IQ4_NL);
164        STRATA_TAB_CASE(GGML_TYPE_IQ4_XS);
165        STRATA_TAB_CASE(GGML_TYPE_Q8_0);
166        default: return false;
167    }
168#undef STRATA_TAB_CASE
169}
170// whether run_tab has an instance for type t (no launch)
171bool tab_has_type(int t) {
172    mmq_args a{};
173    a.type_x = (ggml_type) t;
174    return run_tab(nullptr, &a, nullptr, nullptr);
175}
176#else
177bool run_tab(ggml_backend_cuda_context*, const mmq_args*, const void*, cudaStream_t) {
178    std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n");
179    std::exit(1);
180}
181bool tab_has_type(int) { return false; }
182#endif
183
184}  // namespace
185
186// mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden
187void run_nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
188// mmq_nvfp4_w4a4.cu (the one unit built for 12xa): FP4 x FP4 and its activation quantizer, if this card runs it
189bool w4a4_available();
190void run_nvfp4_w4a4(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s);
191void quantize_nvfp4_w4a4(const float* x, const int32_t* ids, void* xq, float* yscale, bool aligned, int64_t cols,
192                         int64_t ld, int64_t rows, int64_t padded, cudaStream_t s);
193
194// moe_helpers.cu's q8_bytes counts block_q8_1_mmq rows of 144 bytes for 4 x QK8_1 = 128 values
195static_assert(sizeof(block_q8_1_mmq) == 144 && QK8_1 == 32, "moe_helpers.cu: kQ8_1MmqBytes / kQK8_1");
196
197bool built() { return true; }
198
199Nvfp4Mode nvfp4_mode() {
200    static const Nvfp4Mode m = [] {
201        const char* e = std::getenv("STRATA_PREFILL_NVFP4");
202        if (e == nullptr || std::strcmp(e, "w4a8") == 0) return Nvfp4Mode::W4A8;
203        if (std::strcmp(e, "w4a4") == 0) return Nvfp4Mode::W4A4;
204        if (std::strcmp(e, "fp16") == 0) return Nvfp4Mode::FP16;
205        std::fprintf(stderr, "STRATA_PREFILL_NVFP4=%s: expected w4a8, w4a4 or fp16\n", e);
206        std::exit(1);
207    }();
208    return m;
209}
210
211bool supported(int t) {
212    switch ((ggml_type) t) {
213        case GGML_TYPE_Q2_0:
214        case GGML_TYPE_Q3_K:   // the v7l1280 q3k latent pack's gate/up
215#ifdef STRATA_ORCA_Q4KS_MMQ
216        case GGML_TYPE_Q5_0:   // #296 (Q4_K and Q5_1: STRATA_MMQ_KQUANTS)
217#endif
218        case GGML_TYPE_IQ2_XXS: case GGML_TYPE_IQ2_XS: case GGML_TYPE_IQ2_S:
219        case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ4_NL: case GGML_TYPE_IQ4_XS:
220        case GGML_TYPE_Q8_0:   // the draft layer's dense matrices (E-9)
221#ifdef STRATA_MMQ_TQ
222        case GGML_TYPE_TQ2_T: case GGML_TYPE_TQK6: case GGML_TYPE_TQK7:   // APR experts (agention fork's MMQ)
223#endif
224#ifdef STRATA_MMQ_TQP   // a ggml with the pair-trellis types (the overlay, or an agention tree that has their instances)
225        case GGML_TYPE_TQP5: case GGML_TYPE_TQP6: case GGML_TYPE_TQP7:     // Gyro-L pair trellis (types 147-149)
226#endif
227            return true;
228#ifdef STRATA_MMQ_KQUANTS
229        // Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF projections (STRATA_DENSE_MMQ)
230        case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q5_1: case GGML_TYPE_Q6_K:
231            return kq_ok();
232#endif
233#if !defined(GGML_USE_HIP)
234        case GGML_TYPE_NVFP4:
235            return nvfp4_mode() != Nvfp4Mode::FP16;
236#endif
237        default:
238            return false;
239    }
240}
241
242bool fits(int t, int64_t w_rows) {
243    if (!supported(t)) return false;
244    // mul_mat_q_case's choice: the "fallback" configs when the rows are not a multiple of 128; then
245    // mul_mat_q_switch_J's loop - a tile size whose config exists for this card and fits its shared memory
246    const bool fallback = w_rows % 128 != 0;
247    const ggml_cuda_device_info& info = ggml_cuda_info();
248    for (int id = 0; id < info.device_count; ++id) {
249        const int cc = info.devices[id].cc;
250        const size_t smpbo = info.devices[id].smpbo;
251        bool any = false;
252        for (int J = 8; J <= kMmqTileColsMax && !any; J += kMmqTileColsStep) {
253            const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, fallback, cc);
254            any = c.type != GGML_TYPE_COUNT && mmq_get_nbytes_shared(c, cc) <= smpbo;
255        }
256        if (!any) {
257            static bool said[GGML_TYPE_COUNT] = {};
258            if (t >= 0 && t < GGML_TYPE_COUNT && !said[t]) {
259                said[t] = true;
260                std::fprintf(stderr, "strata: prompt kernels: llama.cpp's MMQ has no tile for %s (%lld rows) on GPU %d "
261                                     "(cc %d, %zu bytes of shared memory per block): that product takes the non-MMQ path "
262                                     "(#420)\n", type_label((int) t), (long long) w_rows, id, cc, smpbo);
263            }
264            return false;
265        }
266    }
267    return true;
268}
269
270namespace {
271__global__ void scale_gu_rows_kernel(float* __restrict__ gu, int64_t ld, int64_t n_ff, const int32_t* __restrict__ bounds,
272                                     int n, const float* __restrict__ tails, int64_t row0) {
273    const int64_t r = row0 + blockIdx.x;
274    int q = 0;
275    while (q + 1 < n && r >= bounds[q + 1]) ++q;
276    const float sg = tails[4 * q], su = tails[4 * q + 1];
277    float* row = gu + r * ld;
278    for (int64_t k = threadIdx.x; k < 2 * n_ff; k += blockDim.x) row[k] *= k < n_ff ? sg : su;
279}
280__global__ void scale_down_rows_kernel(float* __restrict__ d, int64_t ld, const int32_t* __restrict__ bounds, int n,
281                                       const float* __restrict__ tails) {
282    const int64_t r = blockIdx.x;
283    int q = 0;
284    while (q + 1 < n && r >= bounds[q + 1]) ++q;
285    const float sd = tails[4 * q + 2];
286    float* row = d + r * ld;
287    for (int64_t k = threadIdx.x; k < ld; k += blockDim.x) row[k] *= sd;
288}
289}  // namespace
290
291bool fp4_activations(int t) {
292#if defined(GGML_USE_HIP)   // no NVFP4 MMQ on HIP (and no W4A4 unit)
293    (void) t;
294    return false;
295#else
296    if (t != GGML_TYPE_NVFP4 || nvfp4_mode() != Nvfp4Mode::W4A4) return false;
297    static const bool on = [] {
298        const bool ok = w4a4_available();
299        if (!ok) std::fprintf(stderr, "prefill mmq: STRATA_PREFILL_NVFP4=w4a4 needs an sm_12x card in a 12x build; W4A8\n");
300        return ok;
301    }();
302    return on;
303#endif
304}
305
306void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, int n, const float* tails,
307                   int64_t row0, int64_t nrows, void* stream) {
308    if (nrows <= 0 || n <= 0) return;
309    scale_gu_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(gu, ld, n_ff, bounds, n, tails, row0);
310    ck(cudaGetLastError(), "scale_gu_rows");
311}
312
313void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream) {
314    if (nrows <= 0 || n <= 0) return;
315    scale_down_rows_kernel<<<(unsigned) nrows, 256, 0, (cudaStream_t) stream>>>(d, ld, bounds, n, tails);
316    ck(cudaGetLastError(), "scale_down_rows");
317}
318
319void quantize(const float* x, const int32_t* ids, void* xq, int t, int64_t cols, int64_t ld, int64_t rows, void* stream,
320              float* yscale) {
321    if (rows <= 0) return;
322#if !defined(GGML_USE_HIP)
323    if (fp4_activations(t)) {
324        if (yscale == nullptr) { std::fprintf(stderr, "prefill mmq: NVFP4 activations need a scale buffer\n"); std::exit(1); }
325        const bool aligned = ((uintptr_t) x % 32 == 0) && ((size_t) ld * sizeof(float)) % 32 == 0;
326        quantize_nvfp4_w4a4(x, ids, xq, yscale, aligned, cols, ld, rows, pad512(cols), (cudaStream_t) stream);
327        ck(cudaGetLastError(), "quantize");
328        return;
329    }
330#endif
331    (void) yscale;
332    quantize_mmq_q8_1_cuda(x, ids, xq, (ggml_type) t, cols, ld, rows * ld, rows * ld, pad512(cols), rows, 1, 1,
333                           (cudaStream_t) stream);
334    ck(cudaGetLastError(), "quantize");
335}
336
337void quantize_scatter(const float* x, const int32_t* slot, const int32_t* src, void* xq, int t, int64_t cols, int64_t ld,
338                      int64_t tokens, int k_used, void* stream) {
339    if (tokens <= 0 || k_used <= 0) return;
340    static const bool gather = [] { const char* e = std::getenv("STRATA_QUANT_GATHER"); return e != nullptr && std::atoi(e) != 0; }();
341    if (gather) {
342        quantize(x, src, xq, t, cols, ld, tokens * k_used, stream);
343        return;
344    }
345    quantize_scatter_mmq_q8_1_cuda(x, slot, xq, (ggml_type) t, cols, ld, pad512(cols), tokens, tokens * k_used, k_used,
346                                   (cudaStream_t) stream);
347    ck(cudaGetLastError(), "quantize_scatter");
348}
349
350Context::Context() {
351    int dev = 0;
352    cudaGetDevice(&dev);
353    ctx_ = new ggml_backend_cuda_context(dev);
354}
355Context::~Context() { delete (ggml_backend_cuda_context*) ctx_; }
356
357void Context::run(const Product& p, void* stream) {
358    if (p.n <= 0 || p.max_rows <= 0) return;
359#if !defined(GGML_USE_HIP)
360    // STRATA_IQ4_W4A8=1 (opt-in; =2: the IQ4_NL down products only): IQ4_XS / IQ4_NL products through the pipelined int8
361    // kernel of moe_iq4_w4a8.cu where it gives MMQ's tiling-mode bits (sm_80..sm_88, no stream-k split); it declines
362    // every other product, and unset this function is unchanged
363    if (const int m = iq4_w4a8_mode(); m == 1 || (m == 2 && p.type == GGML_TYPE_IQ4_NL)) {
364        if (run_iq4_w4a8(p, stream)) {
365            ck(cudaGetLastError(), "iq4 w4a8");
366            return;
367        }
368    }
369#endif
370    const ggml_type t = (ggml_type) p.type;
371    const int64_t qk = type_blck((int) t), bpr = p.w_cols / qk;
372    const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale,
373                        p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst,
374                        p.n, p.n, p.tab ? 0 : (int64_t) (p.expert_bytes / type_bytes((int) t)), 0, 0,
375                        1, 1, 0, 0, 0,
376                        p.max_rows, p.max_rows};
377    {
378        static const bool dump = std::getenv("STRATA_MMQ_ARGS") != nullptr;
379        if (dump) {
380            std::fprintf(stderr, "mmqargs t=%d x=%p y=%p ids=%p b=%p dst=%p ys=%p | cx=%lld rx=%lld cd=%lld srx=%lld cy=%lld "
381                         "rd=%lld | nchx=%lld nchy=%lld scx=%lld scy=%lld scd=%lld | nsx=%lld nsy=%lld ssx=%lld ssy=%lld "
382                         "ssd=%lld | nmax=%lld nopt=%lld\n",
383                         (int) a.type_x, (const void*) a.x, (const void*) a.y, (const void*) a.ids_dst,
384                         (const void*) a.expert_bounds, (void*) a.dst, (const void*) a.y_scale, (long long) a.ncols_x,
385                         (long long) a.nrows_x, (long long) a.ncols_dst, (long long) a.stride_row_x,
386                         (long long) a.ncols_y, (long long) a.nrows_dst, (long long) a.nchannels_x,
387                         (long long) a.nchannels_y, (long long) a.stride_channel_x, (long long) a.stride_channel_y,
388                         (long long) a.stride_channel_dst, (long long) a.nsamples_x, (long long) a.nsamples_y,
389                         (long long) a.stride_sample_x, (long long) a.stride_sample_y,
390                         (long long) a.stride_sample_dst, (long long) a.ncols_max, (long long) a.ncols_opt);
391        }
392    }
393    auto& ctx = *(ggml_backend_cuda_context*) ctx_;
394    const cudaStream_t s = (cudaStream_t) stream;
395    if (p.tab) {
396        if (p.n > kGatherGroupMax) {
397            std::fprintf(stderr, "prefill mmq: a pointer table holds at most %d experts (got %d)\n", kGatherGroupMax, p.n);
398            std::exit(1);
399        }
400#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
401        mmq_x_tab tab{};
402        for (int z = 0; z < p.n; ++z) tab.p[z] = (const char*) p.tab->p[z];
403        if (!run_tab(&ctx, &a, &tab, s)) {
404            std::fprintf(stderr, "prefill mmq: no pointer-table MMQ for %s with %lld rows\n", type_label((int) t),
405                         (long long) p.w_rows);
406            std::exit(1);
407        }
408#else
409        run_tab(&ctx, &a, nullptr, s);
410#endif
411        ck(cudaGetLastError(), "mul_mat_q (pointer table)");
412        return;
413    }
414    switch (t) {
415#ifdef STRATA_ORCA_Q4KS_MMQ
416        case GGML_TYPE_Q5_0: mul_mat_q_case<GGML_TYPE_Q5_0>(ctx, a, s); break;
417#endif
418        case GGML_TYPE_Q2_0: mul_mat_q_case<GGML_TYPE_Q2_0>(ctx, a, s); break;
419        case GGML_TYPE_Q3_K: mul_mat_q_case<GGML_TYPE_Q3_K>(ctx, a, s); break;
420        case GGML_TYPE_IQ2_XXS: mul_mat_q_case<GGML_TYPE_IQ2_XXS>(ctx, a, s); break;
421        case GGML_TYPE_IQ2_XS: mul_mat_q_case<GGML_TYPE_IQ2_XS>(ctx, a, s); break;
422        case GGML_TYPE_IQ2_S: mul_mat_q_case<GGML_TYPE_IQ2_S>(ctx, a, s); break;
423        case GGML_TYPE_IQ3_XXS: mul_mat_q_case<GGML_TYPE_IQ3_XXS>(ctx, a, s); break;
424        case GGML_TYPE_IQ3_S: mul_mat_q_case<GGML_TYPE_IQ3_S>(ctx, a, s); break;
425        case GGML_TYPE_IQ4_NL: mul_mat_q_case<GGML_TYPE_IQ4_NL>(ctx, a, s); break;
426        case GGML_TYPE_IQ4_XS: mul_mat_q_case<GGML_TYPE_IQ4_XS>(ctx, a, s); break;
427        case GGML_TYPE_Q8_0: mul_mat_q_case<GGML_TYPE_Q8_0>(ctx, a, s); break;
428#ifdef STRATA_MMQ_TQ
429        case GGML_TYPE_TQ2_T: mul_mat_q_case<GGML_TYPE_TQ2_T>(ctx, a, s); break;
430        case GGML_TYPE_TQK6: mul_mat_q_case<GGML_TYPE_TQK6>(ctx, a, s); break;
431        case GGML_TYPE_TQK7: mul_mat_q_case<GGML_TYPE_TQK7>(ctx, a, s); break;
432#endif
433#ifdef STRATA_MMQ_TQP
434        case GGML_TYPE_TQP5: mul_mat_q_case<GGML_TYPE_TQP5>(ctx, a, s); break;
435        case GGML_TYPE_TQP6: mul_mat_q_case<GGML_TYPE_TQP6>(ctx, a, s); break;
436        case GGML_TYPE_TQP7: mul_mat_q_case<GGML_TYPE_TQP7>(ctx, a, s); break;
437#endif
438#if defined(STRATA_MMQ_KQUANTS) && defined(STRATA_KQ_DSO)
439        case GGML_TYPE_Q4_K: case GGML_TYPE_Q5_K: case GGML_TYPE_Q6_K: case GGML_TYPE_Q5_1: {
440            const int e = kq::run((int) t, &a, s);
441            if (e != 0) {
442                std::fprintf(stderr, "prefill mmq: the K-quant library failed on type %d (error %d)\n", (int) t, e);
443                std::exit(1);
444            }
445            break;
446        }
447#elif defined(STRATA_MMQ_KQUANTS)
448        case GGML_TYPE_Q4_K: mul_mat_q_case<GGML_TYPE_Q4_K>(ctx, a, s); break;
449        case GGML_TYPE_Q5_K: mul_mat_q_case<GGML_TYPE_Q5_K>(ctx, a, s); break;
450        case GGML_TYPE_Q6_K: mul_mat_q_case<GGML_TYPE_Q6_K>(ctx, a, s); break;
451        case GGML_TYPE_Q5_1: mul_mat_q_case<GGML_TYPE_Q5_1>(ctx, a, s); break;
452#endif
453#if !defined(GGML_USE_HIP)   // NVFP4: CUDA only (no HIP instance, no W4A8 unit)
454        case GGML_TYPE_NVFP4:
455            if (fp4_activations(t)) run_nvfp4_w4a4(ctx, a, s);
456            else run_nvfp4_w4a8(ctx, a, s);
457            break;
458#endif
459        default:
460            std::fprintf(stderr, "prefill mmq: type %d is not covered\n", (int) t);
461            std::exit(1);
462    }
463    ck(cudaGetLastError(), "mul_mat_q");
464}
465
466// ---- STRATA_MMQ_DIRECT ----
467bool tab_built() {
468#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__)
469    return true;
470#else
471    return false;
472#endif
473}
474
475bool tab_fits(int t, int64_t w_rows) {
476    return tab_built() && w_rows % 128 == 0 && tab_has_type(t) && fits(t, w_rows);
477}
478
479size_t overread_bytes(int t, int64_t cols) {
480    if (!supported(t)) return 0;
481    // the K tile's over-read for each (fallback=false) config on any visible GPU, the largest of them: the over-read
482    // is not monotonic in the tile length (20 blocks: 12 more with a 16-block tile, 4 with a 24-block one), so each
483    // config's own; MMQ_ITER_K's is the floor (it is the tile when no config is known)
484    const int64_t qk = type_blck((int) t), bpn = cols / qk;
485    auto over = [&](int64_t k_vram) -> int64_t {
486        const int64_t bpi = k_vram / qk;
487        return bpi > 0 ? (bpi - bpn % bpi) % bpi : 0;
488    };
489    int64_t blocks = over(MMQ_ITER_K);
490    const ggml_cuda_device_info& info = ggml_cuda_info();
491    for (int id = 0; id < info.device_count; ++id)
492        for (int J = 8; J <= kMmqTileColsMax; J += kMmqTileColsStep) {
493            const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, info.devices[id].cc);
494            if (c.type != GGML_TYPE_COUNT) blocks = std::max<int64_t>(blocks, over(c.K_vram));
495        }
496    return (size_t) blocks * type_bytes((int) t);
497}
498
499bool whole_tiles(int t, int64_t w_rows, int n_experts) {
500    if (!supported(t) || w_rows % 128 != 0 || n_experts <= 0) return false;
501    // launch_mul_mat_q's grid: without stream-k one block per tile; with it one block per tile when the tiles fill
502    // their waves to >= 90 % (NVIDIA), else nsm blocks that split tiles along K at boundaries set by the tile count.
503    // The tile count is nty * n_experts * ntx, ntx = any positive count of J-wide column tiles (max_rows decides),
504    // and ntiles >= 9 * nsm always fills its waves to >= 90 %: the ntx below that are checked one by one.
505    const ggml_cuda_device_info& info = ggml_cuda_info();
506    for (int id = 0; id < info.device_count; ++id) {
507        const int cc = info.devices[id].cc, nsm = info.devices[id].nsm;
508        const size_t smpbo = info.devices[id].smpbo;
509        bool any = false, stream_k = false;
510        ggml_cuda_mmq_config c0 = ggml_cuda_mmq_get_config((ggml_type) t, 8, false, cc);
511        for (int J = 8; J <= kMmqTileColsMax; J += kMmqTileColsStep) {
512            const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, cc);
513            if (c.type == GGML_TYPE_COUNT || mmq_get_nbytes_shared(c, cc) > smpbo) continue;
514            if (!any) c0 = c;
515            any = true;
516            // every tile width accumulates each output over the same K tiles in the same order
517            if (c.I != c0.I || c.K_vram != c0.K_vram || c.sram_layout != c0.sram_layout) return false;
518            stream_k = stream_k || c.stream_k;
519        }
520        if (!any) return false;
521        if (!stream_k) continue;
522        if (!GGML_CUDA_CC_IS_NVIDIA(cc) || nsm <= 0) return false;
523        const int64_t per_ntx = (w_rows / c0.I) * n_experts;
524        for (int64_t ntx = 1; per_ntx * ntx < 9 * (int64_t) nsm + per_ntx; ++ntx) {
525            const int64_t tiles = per_ntx * ntx, waves = (tiles + nsm - 1) / nsm;
526            if (100 * tiles / (nsm * waves) < 90) return false;
527        }
528    }
529    return true;
530}
531
532bool launch_splits_k(int t, int64_t w_rows, int64_t max_rows, int n_experts) {
533    if (!supported(t) || w_rows <= 0 || max_rows <= 0 || n_experts <= 0) return false;
534    const ggml_cuda_device_info& info = ggml_cuda_info();
535    int id = 0;
536    cudaGetDevice(&id);
537    if (id < 0 || id >= info.device_count) return true;
538    const int cc = info.devices[id].cc, nsm = info.devices[id].nsm;
539    const size_t smpbo = info.devices[id].smpbo;
540    // mul_mat_q_switch_J: the first tile width (8, 16, ...) with the fewest column tiles that fits the shared memory
541    int best_I = 0;
542    bool best_stream_k = false;
543    int64_t ntiles_best = INT64_MAX;
544    for (int J = 8; J <= 128 && ntiles_best > 1; J += 8) {
545        const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, cc);
546        if (c.type == GGML_TYPE_COUNT || mmq_get_nbytes_shared(c, cc) > smpbo) continue;
547        const int64_t ntx = (max_rows + c.J - 1) / c.J;
548        if (ntx < ntiles_best) { ntiles_best = ntx; best_I = c.I; best_stream_k = c.stream_k; }
549    }
550    if (ntiles_best == INT64_MAX) return true;   // no tile fits: not a launch to predict
551    if (!best_stream_k) return false;
552    if (!GGML_CUDA_CC_IS_NVIDIA(cc) || nsm <= 0) return true;
553    // launch_mul_mat_q: one block per tile when the tiles fill >= 90 % of their waves, else nsm blocks and a fixup
554    // whenever the tile count is not a multiple of them
555    const int64_t nty = (w_rows + best_I - 1) / best_I, ntiles = nty * ntiles_best * n_experts;
556    const int64_t waves = (ntiles + nsm - 1) / nsm;
557    return 100 * ntiles / (nsm * waves) < 90 && ntiles % nsm != 0;
558}
559
560int direct_mode() {
561    static const int mode = [] {
562        const char* v = std::getenv("STRATA_MMQ_DIRECT");
563        const int m = v ? std::atoi(v) : 0;
564        if (m != 1 && m != 2) return 0;
565        if (!tab_built()) {
566            std::fprintf(stderr, "strata: STRATA_MMQ_DIRECT=%d is ignored: this build has no pointer-table MMQ "
567                                 "(CUDA with STRATA_MMQ_TAB only)\n", m);
568            return 0;
569        }
570        return m;
571    }();
572    return mode;
573}
574
575size_t direct_slot_guard() { return direct_mode() != 0 ? kSlotGuard : 0; }
576
577void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream) {
578#if !defined(STRATA_MMQ_TAB) || defined(__HIPCC__)
579    // never reached: only a direct group calls it, and direct_mode() is 0 without the pointer-table MMQ
580    (void) g; (void) guard_bytes; (void) tail_gu; (void) tail_d; (void) tail_bytes; (void) stream;
581    std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n");
582    std::exit(1);
583#else
584    const int n = g.n > 0 ? std::min(g.n, kGatherGroupMax) : 0;
585    const size_t guard = n > 0 ? guard_bytes : 0;
586    const size_t tail = tail_gu || tail_d ? tail_bytes : 0;
587    if (guard == 0 && tail == 0) return;
588    GuardTab gt = g;
589    gt.n = guard > 0 ? n : 0;
590    const bool tail16 = ((uintptr_t) tail_gu | (uintptr_t) tail_d | tail_bytes) % 16 == 0;
591    const size_t span = std::max(guard, tail);
592    prep_group_kernel<<<dim3(blocks((int64_t) span), (unsigned) (gt.n + 2)), 256, 0, (cudaStream_t) stream>>>(
593        gt, (int64_t) guard, (uint8_t*) tail_gu, (uint8_t*) tail_d, (int64_t) tail, tail16);
594    ck(cudaGetLastError(), "prep_group");
595#endif
596}
597
598bool swiglu_quant_ok(int t) {
599#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
600    // the q8_1 D4 rows quantize() writes for a down product's H (K 640)
601    return supported(t) && !fp4_activations(t) && mmq_get_q8_1_ds_layout((ggml_type) t) == MMQ_Q8_1_DS_LAYOUT_D4;
602#else
603    (void) t;
604    return false;   // HIP: not checked against the HIP build's quantizer; outside the SM60 build: not built
605#endif
606}
607
608void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream) {
609#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
610    if (rows <= 0) return;
611    const dim3 grid((unsigned) rows, 2);
612    if (interleaved) swiglu_quant_kernel<true><<<grid, 128, 0, (cudaStream_t) stream>>>(gu, (block_q8_1_mmq*) hq, rows);
613    else swiglu_quant_kernel<false><<<grid, 128, 0, (cudaStream_t) stream>>>(gu, (block_q8_1_mmq*) hq, rows);
614    ck(cudaGetLastError(), "swiglu_quant");
615#else
616    (void) gu; (void) hq; (void) rows; (void) interleaved; (void) stream;
617#endif
618}
619
620#if defined(__HIPCC__)
621void f16_to_f32(const uint16_t* x, float* y, int64_t n, void* stream) {
622    if (n <= 0) return;
623    f16_to_f32_kernel<<<blocks(n), 256, 0, (cudaStream_t) stream>>>(x, y, n);
624    ck(cudaGetLastError(), "f16_to_f32");
625}
626
627void set_bounds(int32_t* dst, int32_t rows, void* stream) {
628    set_bounds_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(dst, rows);
629    ck(cudaGetLastError(), "set_bounds");
630}
631#endif
632
633}  // namespace strata::prefill::mmq