okami.mom/strata

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

Niko1221Merge f-145-havok (#2364 multi-user series, opt-in)df44bcb71

main
24.9 KiB552 linesraw
1// src/prefill/moe_mmq_tab.cuh - STRATA_MMQ_DIRECT: llama.cpp's MMQ outer scheduler (ggml-cuda mmq.cuh, MIT) with a
2// per-expert pointer table, so the prompt path's MMQ reads resident experts in their expert-cache slots instead of
3// a gathered copy.  Included only by the per-type instance TUs (CMake: mmq_tab_instance.cu.in); moe_mmq.cu sees
4// the declarations in moe_mmq_tab.hpp.
5//
6// Mirrored from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d (the fetched pin; the vendored third_party tree's
7// mmq.cuh is byte-identical to it), ggml/src/ggml-cuda/mmq.cuh:
8//   mul_mat_q          lines  953-1238  -> mul_mat_q_tab
9//   launch_mul_mat_q   lines 1395-1475  -> launch_mul_mat_q_tab
10//   mul_mat_q_switch_J lines 1477-1558  -> mul_mat_q_tab_switch_J
11// fallback = false only (mul_mat_q_tab_case refuses rows % 128 != 0).  Everything else is the upstream text, and
12// mul_mat_q_process_tile, the tile loaders, vec_dot, write_back and mul_mat_q_stream_k_fixup are upstream's own
13// templates from the same mmq.cuh, compiled in the same target with the same flags.  Deliberate deviations:
14//   1. upstream's `const char * __restrict__ x` parameter becomes 16 such parameters x0..x15 (the table, see
15//      STRATA_MMQ_TAB_PARAMS); at the three offset_x sites the expert's base is the one picked by
16//      fastdiv(zt, channel_ratio), and the fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x
17//      (stride_channel_x is still passed, unused);
18//   2. the launcher raises the shared-memory limit of mul_mat_q_tab<type, J> only - upstream's line for
19//      mul_mat_q<type, J, true> is dropped, so no fallback=true kernel is instantiated.
20// The launch geometry (J, tiles, the stream-k grid and k split, the fixup) is computed from the same mmq_args as
21// upstream's, so every output tile is summed in the same order: the results are bitwise the same as gathering the
22// experts `stride_channel_x` apart (tests/cuda/prefill_mmq_tab_test.cu checks it per type and J).
23// CMake turns STRATA_MMQ_TAB off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through
24// mul_mat_q_case, which includes struct mmq_args) is one this copy was verified against; when the llama.cpp pin
25// moves, re-sync this file, re-run the test and record the new hash in CMakeLists.txt (_strata_mmq_tab_known).
26//
27// MIT License
28// Copyright (c) 2023-2026 The ggml authors
29//
30// Permission is hereby granted, free of charge, to any person obtaining a copy
31// of this software and associated documentation files (the "Software"), to deal
32// in the Software without restriction, including without limitation the rights
33// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
34// copies of the Software, and to permit persons to whom the Software is
35// furnished to do so, subject to the following conditions:
36//
37// The above copyright notice and this permission notice shall be included in all
38// copies or substantial portions of the Software.
39//
40// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
46// SOFTWARE.
47#pragma once
48
49#include "mmq.cuh"
50#include "moe_mmq_tab.hpp"
51
52#include <type_traits>
53
54namespace strata::prefill::mmq {
55
56// A second net behind the configure fingerprint: the upstream templates this copy calls keep their signatures.
57static_assert(std::is_same<decltype(&mul_mat_q_process_tile<GGML_TYPE_Q8_0, 8, false, false>),
58                           void (*)(const char*, int, const int*, const int*, float*, float*, const float*, int, int, int,
59                                    int, int, int, int)>::value,
60              "mmq.cuh: mul_mat_q_process_tile changed - re-sync src/prefill/moe_mmq_tab.cuh");
61static_assert(std::is_same<decltype(&mul_mat_q_stream_k_fixup<GGML_TYPE_Q8_0, 8, false>),
62                           void (*)(const int32_t*, const int32_t*, float*, float*, uint3, int, int, int, uint3, int,
63                                    uint3, int, uint3)>::value,
64              "mmq.cuh: mul_mat_q_stream_k_fixup changed - re-sync src/prefill/moe_mmq_tab.cuh");
65
66// The table reaches the kernel as 16 separate `const char * __restrict__` parameters, like upstream's `x`, and an
67// expert's entry is picked with a select chain: a pointer picked from read-only kernel parameters keeps upstream's
68// non-coherent global loads (LDG.CONSTANT) of the weights; a dynamically indexed array parameter would be copied to
69// local memory and its pointers read through generic loads (measured ~1.2-2.5x slower products).
70#define STRATA_MMQ_TAB_PARAMS                                                                                     \
71    const char * __restrict__ x0, const char * __restrict__ x1, const char * __restrict__ x2,                  \
72    const char * __restrict__ x3, const char * __restrict__ x4, const char * __restrict__ x5,                  \
73    const char * __restrict__ x6, const char * __restrict__ x7, const char * __restrict__ x8,                  \
74    const char * __restrict__ x9, const char * __restrict__ x10, const char * __restrict__ x11,                \
75    const char * __restrict__ x12, const char * __restrict__ x13, const char * __restrict__ x14,               \
76    const char * __restrict__ x15
77#define STRATA_MMQ_TAB_PICK(z)                                                                                    \
78    ((z) == 0 ? x0 : (z) == 1 ? x1 : (z) == 2 ? x2 : (z) == 3 ? x3 : (z) == 4 ? x4 : (z) == 5 ? x5 :            \
79     (z) == 6 ? x6 : (z) == 7 ? x7 : (z) == 8 ? x8 : (z) == 9 ? x9 : (z) == 10 ? x10 : (z) == 11 ? x11 :        \
80     (z) == 12 ? x12 : (z) == 13 ? x13 : (z) == 14 ? x14 : x15)
81#define STRATA_MMQ_TAB_ARGS(t)                                                                                    \
82    (t).p[0], (t).p[1], (t).p[2], (t).p[3], (t).p[4], (t).p[5], (t).p[6], (t).p[7], (t).p[8], (t).p[9],        \
83    (t).p[10], (t).p[11], (t).p[12], (t).p[13], (t).p[14], (t).p[15]
84
85// ---- mirrored: mul_mat_q (fallback = false, per-expert base from `tab`) ----
86template <ggml_type type, int J>
87__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, false), ggml_cuda_mmq_get_occupancy(type, J, false))
88static __global__ void mul_mat_q_tab(
89        STRATA_MMQ_TAB_PARAMS, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
90        const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
91        const float * __restrict__ y_scale,
92        const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst,
93        const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
94        const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
95        const uint3 ntx) {
96    constexpr bool fallback = false;  // STRATA: the tab copy has no fallback (rows % 128 == 0) instantiation
97
98    // Skip unused template specializations for faster compilation:
99    if (ggml_cuda_mmq_get_config(type, J, fallback).type == GGML_TYPE_COUNT) {
100        NO_DEVICE_CODE;
101        return;
102    }
103
104    constexpr int warp_size = ggml_cuda_get_physical_warp_size();
105    constexpr int nwarps    = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size;
106    constexpr int qk        = ggml_cuda_type_traits<type>::qk;
107    constexpr int I         = ggml_cuda_mmq_get_I(type, J, fallback);
108
109    const uint32_t nty = (nrows_x + I - 1) / I; // Number of tiles y
110
111    // Initialize the ids for writing back data with just the index.
112    // For regular matrix multiplications this is never changed.
113    // For MoE the correct indices are loaded from ids_dst.
114    extern __shared__ int ids_dst_shared[]; // Stored at beginning of shared memory.
115#pragma unroll
116    for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
117        const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
118
119        if (j0 + nwarps*warp_size > J && j >= J) {
120            break;
121        }
122
123        ids_dst_shared[j] = j;
124    }
125    __syncthreads();
126
127    if constexpr (!ggml_cuda_mmq_get_stream_k(type, J, fallback)) {
128        const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y);
129        const int wt = tmp2.x;
130        const int zt = tmp2.y;
131        const int jt = blockIdx.y;
132        const int it = blockIdx.x;
133
134        // Defaults for regular matrix multiplication:
135        int col_low    = 0;
136        int col_high   = ncols_dst;
137        int col_diff   = ncols_dst;
138        int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
139        int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
140        int offset_y_scale;
141        if constexpr (type == GGML_TYPE_NVFP4) {
142            offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
143        } else {
144            GGML_UNUSED(offset_y_scale);
145        }
146
147        if (ids_dst) {
148            col_low  = expert_bounds[zt + 0];
149            col_high = expert_bounds[zt + 1];
150            col_diff = col_high - col_low;
151
152            offset_y   = 0;
153            offset_dst = 0;
154            if constexpr (type == GGML_TYPE_NVFP4) {
155                offset_y_scale = 0;
156            }
157
158            if (jt*J >= col_diff) {
159                return;
160            }
161
162            // __syncthreads(); // There is no previous tile that could cause a race condition.
163#pragma unroll
164            for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
165                const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
166
167                if (j0 + nwarps*warp_size > J && j >= J) {
168                    break;
169                }
170
171                ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
172            }
173            __syncthreads();
174        }
175
176        offset_y   += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int));
177        offset_dst += it*I;
178        const float * y_scale_tile = nullptr;
179        if constexpr (type == GGML_TYPE_NVFP4) {
180            offset_y_scale += col_low + jt*J;
181            y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
182        }
183
184        const int tile_x_max_i = nrows_x  - it*I - 1;
185        const int tile_y_max_j = col_diff - jt*J - 1;
186
187        const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio));  // STRATA: per-expert base
188        const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
189
190        constexpr bool fixup = false;
191        mul_mat_q_process_tile<type, J, fallback, fixup>
192            (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
193             stride_row_x, ncols_y, stride_col_dst,
194             tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z);
195        return;
196    }
197
198    constexpr int ITER_K          = ggml_cuda_mmq_get_K_vram(type, J, fallback);
199    constexpr int blocks_per_iter = ITER_K / qk;
200
201    // kbc == k block continuous, current index in continuous ijk space.
202    int kbc      = int64_t(blockIdx.x)    *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
203    int kbc_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
204
205    kbc      -= fastmodulo(kbc,      blocks_per_ne00) % blocks_per_iter;
206    kbc_stop -= fastmodulo(kbc_stop, blocks_per_ne00) % blocks_per_iter;
207
208    // kb0 == k index when doing the matrix multiplication for an output tile.
209    int kb0_start = fastmodulo(kbc, blocks_per_ne00);
210    int kb0_stop  = min(blocks_per_ne00.z, uint32_t(kb0_start + kbc_stop - kbc));
211    while (kbc < kbc_stop && kb0_stop == int(blocks_per_ne00.z)) {
212        int tmp = fastdiv(kbc, blocks_per_ne00);
213        uint2 tmp2 = fast_div_modulo(tmp, ntx);
214        const int jt = tmp2.y;
215        tmp = tmp2.x;
216        tmp2 = fast_div_modulo(tmp, nchannels_y);
217        const int zt = tmp2.y;
218        tmp = tmp2.x;
219        tmp2 = fast_div_modulo(tmp, nsamples_y);
220        const int wt = tmp2.y;
221        const int it = tmp2.x;
222
223        // Defaults for regular matrix multiplication:
224        int col_low    = 0;
225        int col_high   = ncols_dst;
226        int col_diff   = ncols_dst;
227        int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
228        int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
229        int offset_y_scale;
230        if constexpr (type == GGML_TYPE_NVFP4) {
231            offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
232        } else {
233            GGML_UNUSED(offset_y_scale);
234        }
235
236        if (ids_dst) {
237            col_low  = expert_bounds[zt + 0];
238            col_high = expert_bounds[zt + 1];
239            col_diff = col_high - col_low;
240
241            offset_y   = 0;
242            offset_dst = 0;
243            if constexpr (type == GGML_TYPE_NVFP4) {
244                offset_y_scale = 0;
245            }
246
247            if (jt*J >= col_diff) {
248                kbc += blocks_per_ne00.z;
249                kbc -= fastmodulo(kbc, blocks_per_ne00);
250
251                kb0_start = 0;
252                kb0_stop  = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
253
254                continue;
255            }
256
257            __syncthreads();
258#pragma unroll
259            for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
260                const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
261
262                if (j0 + nwarps*warp_size > J && j >= J) {
263                    break;
264                }
265
266                ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
267            }
268            __syncthreads();
269        }
270
271        offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
272        offset_dst += it*I;
273        const float * y_scale_tile = nullptr;
274        if constexpr (type == GGML_TYPE_NVFP4) {
275            offset_y_scale += col_low + jt * J;
276            y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
277        }
278
279        const int tile_x_max_i = nrows_x  - it*I - 1;
280        const int tile_y_max_j = col_diff - jt*J - 1;
281
282        const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio));  // STRATA: per-expert base
283        const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
284
285        constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
286        mul_mat_q_process_tile<type, J, fallback, fixup>
287            (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
288             stride_row_x, ncols_y, stride_col_dst,
289             tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
290
291        kbc += blocks_per_ne00.z;
292        kbc -= fastmodulo(kbc, blocks_per_ne00);
293
294        kb0_start = 0;
295        kb0_stop  = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
296    }
297
298    if (kbc >= kbc_stop) {
299        return;
300    }
301
302    int tmp = fastdiv(kbc, blocks_per_ne00);
303    uint2 tmp2 = fast_div_modulo(tmp, ntx);
304    const int jt = tmp2.y;
305    tmp = tmp2.x;
306    tmp2 = fast_div_modulo(tmp, nchannels_y);
307    const int zt = tmp2.y;
308    tmp = tmp2.x;
309    tmp2 = fast_div_modulo(tmp, nsamples_y);
310    const int wt = tmp2.y;
311    const int it = tmp2.x;
312
313    // Defaults for regular matrix multiplication:
314    int col_low    = 0;
315    int col_high   = ncols_dst;
316    int col_diff   = ncols_dst;
317    int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
318    int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
319    int offset_y_scale;
320    if constexpr (type == GGML_TYPE_NVFP4) {
321        offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
322    } else {
323        GGML_UNUSED(offset_y_scale);
324    }
325
326    if (ids_dst) {
327        col_low  = expert_bounds[zt + 0];
328        col_high = expert_bounds[zt + 1];
329        col_diff = col_high - col_low;
330
331        offset_y   = 0;
332        offset_dst = 0;
333        if constexpr (type == GGML_TYPE_NVFP4) {
334            offset_y_scale = 0;
335        }
336
337        if (jt*J >= col_diff) {
338            return;
339        }
340
341        // The memory layout for the fixup buffer is always contiguous, therefore reset ids:
342        __syncthreads();
343#pragma unroll
344        for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
345            const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
346
347            if (j0 + nwarps*warp_size > J && j >= J) {
348                break;
349            }
350
351            ids_dst_shared[j] = j;
352        }
353        __syncthreads();
354    }
355
356    offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
357    offset_dst += it*I;
358    const float * y_scale_tile = nullptr;
359    if constexpr (type == GGML_TYPE_NVFP4) {
360        offset_y_scale += col_low + jt * J;
361        y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
362    }
363
364    const int tile_x_max_i = nrows_x  - it*I - 1;
365    const int tile_y_max_j = col_diff - jt*J - 1;
366
367    const char * xz = STRATA_MMQ_TAB_PICK(fastdiv(zt, channel_ratio));  // STRATA: per-expert base
368    const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x;
369
370    constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
371    mul_mat_q_process_tile<type, J, fallback, fixup>
372        (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
373         stride_row_x, ncols_y, stride_col_dst,
374         tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
375}
376
377// ---- mirrored: launch_mul_mat_q (fallback = false) ----
378template <ggml_type type, int J>
379static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) {
380    constexpr bool fallback = false;
381    const int id = ggml_cuda_get_device();
382    const int cc = ggml_cuda_info().devices[id].cc;
383    const int nsm = ggml_cuda_info().devices[id].nsm;
384    const int warp_size = ggml_cuda_info().devices[id].warp_size;
385
386    const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
387    GGML_ASSERT(config.nthreads % warp_size == 0);
388    const int nwarps = config.nthreads / warp_size;
389    const int nbytes_shared = mmq_get_nbytes_shared(config, cc);
390
391    const dim3 block_dims(warp_size, nwarps, 1);
392
393    CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_tab<type, J>), nbytes_shared);  // STRATA: no fallback=true line
394
395    const int nty  = (args.nrows_x   + config.I - 1) / config.I;
396    const int ntx  = (args.ncols_max + config.J - 1) / config.J;
397    const int ntzw = args.nchannels_y * args.nsamples_y;
398    const dim3 block_nums_xy_tiling(nty, ntx, ntzw);
399
400    GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0);
401    GGML_ASSERT(args.nsamples_y  % args.nsamples_x  == 0);
402    const int channel_ratio = args.nchannels_y / args.nchannels_x;
403    const int sample_ratio  = args.nsamples_y  / args.nsamples_x;
404
405    const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits<type>::qk);
406    const uint3 ntx_fd             = init_fastdiv_values(ntx);
407    const uint3 nchannels_y_fd     = init_fastdiv_values(args.nchannels_y);
408    const uint3 nsamples_y_fd      = init_fastdiv_values(args.nsamples_y);
409    const uint3 channel_ratio_fd   = init_fastdiv_values(channel_ratio);
410    const uint3 sample_ratio_fd    = init_fastdiv_values(sample_ratio);
411
412    if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) {
413        mul_mat_q_tab<type, J><<<block_nums_xy_tiling, block_dims, nbytes_shared, stream>>>
414            (STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale,
415             blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
416             channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
417             sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
418             ntx_fd);
419        return;
420    }
421
422    // For the stream-k kernel it is possible to run it with tiling by setting the number of CUDA blocks equal to the number of tiles.
423    // This is worthwhile if the efficiency of tiling is high and skipping the fixup kernel is more important.
424    const int ntiles_dst = ntx * nty * ntzw;
425    const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm;
426    const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves);
427    const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1);
428
429    GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow.
430
431    const bool fixup_needed = ntiles_dst % block_nums_stream_k.x != 0;
432
433    ggml_cuda_pool & pool = ctx.pool(id);
434    ggml_cuda_pool_alloc<float> tmp_fixup(pool);
435    if (fixup_needed) {
436        tmp_fixup.alloc(block_nums_stream_k.x * config.J*config.I);
437    }
438
439    const dim3 block_nums_fixup(block_nums_stream_k.x, config.I/warp_size, 1);
440    const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z);
441
442    mul_mat_q_tab<type, J><<<block_nums_stream_k, block_dims, nbytes_shared, stream>>>
443        (STRATA_MMQ_TAB_ARGS(tab), args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale,
444         blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
445         channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
446         sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
447         ntx_fd);
448
449    if (!fixup_needed) {
450        return;
451    }
452
453    CUDA_CHECK(cudaGetLastError());
454    mul_mat_q_stream_k_fixup<type, J, fallback><<<block_nums_fixup, block_dims_fixup, 0, stream>>>
455        (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
456         args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst,
457         ntx_fd);
458}
459
460// ---- mirrored: mul_mat_q_switch_J (fallback = false) ----
461template <ggml_type type>
462static void mul_mat_q_tab_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) {
463    constexpr bool fallback = false;
464    const int    id    = ggml_cuda_get_device();
465    const int    cc    = ggml_cuda_info().devices[id].cc;
466    const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
467
468    int J_best        = 0;
469    int ntiles_J_best = INT_MAX;
470
471    for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) {
472        const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
473        if (config.type == GGML_TYPE_COUNT) {
474            continue;
475        }
476
477        if (mmq_get_nbytes_shared(config, cc) > smpbo) {
478            continue;
479        }
480
481        const int ntiles_x = (args.ncols_opt + config.J - 1) / config.J;
482
483        if (ntiles_x < ntiles_J_best) {
484            J_best = J;
485            ntiles_J_best = ntiles_x;
486        }
487    }
488
489    switch (J_best) {
490        case   8:
491            launch_mul_mat_q_tab<type, 8>(ctx, args, tab, stream);
492            break;
493        case  16:
494            launch_mul_mat_q_tab<type, 16>(ctx, args, tab, stream);
495            break;
496        case  24:
497            launch_mul_mat_q_tab<type, 24>(ctx, args, tab, stream);
498            break;
499        case  32:
500            launch_mul_mat_q_tab<type, 32>(ctx, args, tab, stream);
501            break;
502        case  40:
503            launch_mul_mat_q_tab<type, 40>(ctx, args, tab, stream);
504            break;
505        case  48:
506            launch_mul_mat_q_tab<type, 48>(ctx, args, tab, stream);
507            break;
508        case  56:
509            launch_mul_mat_q_tab<type, 56>(ctx, args, tab, stream);
510            break;
511        case  64:
512            launch_mul_mat_q_tab<type, 64>(ctx, args, tab, stream);
513            break;
514        case  72:
515            launch_mul_mat_q_tab<type, 72>(ctx, args, tab, stream);
516            break;
517        case  80:
518            launch_mul_mat_q_tab<type, 80>(ctx, args, tab, stream);
519            break;
520        case  88:
521            launch_mul_mat_q_tab<type, 88>(ctx, args, tab, stream);
522            break;
523        case  96:
524            launch_mul_mat_q_tab<type, 96>(ctx, args, tab, stream);
525            break;
526        case 104:
527            launch_mul_mat_q_tab<type, 104>(ctx, args, tab, stream);
528            break;
529        case 112:
530            launch_mul_mat_q_tab<type, 112>(ctx, args, tab, stream);
531            break;
532        case 120:
533            launch_mul_mat_q_tab<type, 120>(ctx, args, tab, stream);
534            break;
535        case 128:
536            launch_mul_mat_q_tab<type, 128>(ctx, args, tab, stream);
537            break;
538        default:
539            fprintf(stderr, "J_best=%d\n", J_best);
540            GGML_ABORT("fatal error");
541            break;
542    }
543}
544
545template <ggml_type T>
546bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s) {
547    if (a.nrows_x % 128 != 0) return false;   // upstream would take the fallback configs: not mirrored
548    mul_mat_q_tab_switch_J<T>(ctx, a, tab, s);
549    return true;
550}
551
552}  // namespace strata::prefill::mmq