okami.mom/strata

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

Niko1221Merge f-own-1a (451f3e8a6): own-stack phase 1A and cleanup 5.4; the ggml/MMQ sources the engines build are vendored in third_party/strata-ggml (frozen at the pin, manifest and check), default engine builds need no llama.cpp download, the TQ overlay is plain files, CMakeLists.txt is split into cmake/backends/*; every engine unchanged (CUDA/HIP gfx1201/gfx1151/SYCL device code identical, SYCL 22/22 checksums, Metal 104/105 objects with only __TIME__ differing, CUDA tokens 26/26); release scripts still pass -DSTRATA_GGML_DIR (owner go 11-08)508e6999a

main
71.8 KiB1645 linesraw
1#pragma once
2
3#include "common.cuh"
4
5#include <climits>
6#include <cstdint>
7
8#define MMQ_DP4A_MAX_BATCH_SIZE 64 // Max. batch size to use for dp4a MMQ kernels when FP16 tensor cores are available.
9#define MMQ_ITER_K             256
10#define MMQ_ITER_K_FP4         512
11#define MMQ_NWARPS               8
12
13typedef void (*ggml_cuda_mmq_load_tiles_t)(const char * __restrict__ x, int * x_tile, const int kbx0, const int i_max, const int stride);
14typedef void (*ggml_cuda_mmq_vec_dot_t)(const int * __restrict__ x, const int * __restrict__ y, float * __restrict__ sum, const int k00);
15typedef void (*ggml_cuda_mmq_write_back_t)(const float * __restrict__ sum, const int32_t * __restrict__ get_rows_to_sorted,
16    float * __restrict__ dst, const float * __restrict__ y_scale, const int stride, const int i_max, const int j_max);
17
18enum mmq_q8_1_ds_layout {
19    MMQ_Q8_1_DS_LAYOUT_D4,
20    MMQ_Q8_1_DS_LAYOUT_DS4,
21    MMQ_Q8_1_DS_LAYOUT_D2S6,
22};
23
24static constexpr int QK8_1_MMQ  = 4*QK8_1;
25static constexpr int QK_FP4_MMQ = 2*QK8_1_MMQ;
26
27struct block_q8_1_mmq {
28    // The y float data is converted to a data layout that can simply be copied to shared memory as a contiguous block.
29    // The y float data is first grouped as blocks of 128 values.
30    // These blocks are then treated as individual data values and transposed.
31    //
32    // To avoid shared memory bank conflicts each block is padded with 16 bytes.
33    // This padding is also used to store block scales/partial sums.
34    // The scales multiplied with the quantized data are equal to the unquantized values.
35    // The partial sums are obtained by summing up a subgroup of the contained values (prior to quantization)
36    //     and are only needed for performance reasons.
37    //
38    // The exact data stored depends on the x data type.
39    union {
40        float d4[4];    // 1 32 bit scale per 32 values, stored as d0,d1,d2,d3
41        half2 ds4[4];   // 1 16 bit scale + 1 16 bit partial sum per 32 values, stored as d0,s0,d1,s1,d2,s2,d3,s3
42        half  d2s6[8];  // 1 16 bit scale per 64 values + 1 16 bit partial sum per 16 values for the first 96 values,
43                        //     stored as d0,d1,s1,s2,s3,s4,s5
44    };
45    int8_t qs[QK8_1_MMQ];
46};
47
48// this struct is used for fp4 data types (currently only used for Blackwell)
49// mxfp4 has block size 32, each int32 of d4 contains 2 e8m0 scales in the lower 16 bits
50// nvfp4 has block size 16, each int32 of d4 contains 4 ue4m3 scales
51struct block_fp4_mmq {
52    uint32_t d4[4];
53    int8_t   qs[QK_FP4_MMQ / 2];
54};
55
56static_assert(sizeof(block_q8_1_mmq) == QK8_1_MMQ + 4*sizeof(half2), "Unexpected block_q8_1_mmq size");
57static_assert(sizeof(block_q8_1_mmq) == 4*sizeof(block_q8_1),      "Unexpected block_q8_1_mmq size");
58static_assert(sizeof(block_fp4_mmq)  == sizeof(block_q8_1_mmq),    "Unexpected block_fp4_mmq size");
59
60static mmq_q8_1_ds_layout mmq_get_q8_1_ds_layout(const ggml_type type_x) {
61    switch (type_x) {
62        case GGML_TYPE_Q1_0:
63        case GGML_TYPE_Q2_0:
64            return MMQ_Q8_1_DS_LAYOUT_D4;
65        case GGML_TYPE_Q4_0:
66        case GGML_TYPE_Q4_1:
67            return MMQ_Q8_1_DS_LAYOUT_DS4;
68        case GGML_TYPE_Q5_0:
69            return MMQ_Q8_1_DS_LAYOUT_D4;
70        case GGML_TYPE_Q5_1:
71            return MMQ_Q8_1_DS_LAYOUT_DS4;
72        case GGML_TYPE_Q8_0:
73            return MMQ_Q8_1_DS_LAYOUT_D4;
74        case GGML_TYPE_MXFP4:
75            return MMQ_Q8_1_DS_LAYOUT_D4;
76        case GGML_TYPE_NVFP4:
77            return MMQ_Q8_1_DS_LAYOUT_D4;
78        case GGML_TYPE_Q2_K:
79            return MMQ_Q8_1_DS_LAYOUT_D2S6;
80        case GGML_TYPE_Q3_K:
81            return MMQ_Q8_1_DS_LAYOUT_D4;
82        case GGML_TYPE_Q4_K:
83        case GGML_TYPE_Q5_K:
84            return MMQ_Q8_1_DS_LAYOUT_DS4;
85        case GGML_TYPE_Q6_K:
86        case GGML_TYPE_IQ2_XXS:
87        case GGML_TYPE_IQ2_XS:
88        case GGML_TYPE_TQ2_T:
89        case GGML_TYPE_TQK6:
90        case GGML_TYPE_TQK7:
91        case GGML_TYPE_TQP5:
92        case GGML_TYPE_TQP6:
93        case GGML_TYPE_TQP7:
94        case GGML_TYPE_IQ2_S:
95        case GGML_TYPE_IQ3_XXS:
96        case GGML_TYPE_IQ3_S:
97            return MMQ_Q8_1_DS_LAYOUT_D4;
98        case GGML_TYPE_IQ1_S:
99            return MMQ_Q8_1_DS_LAYOUT_DS4;
100        case GGML_TYPE_IQ4_XS:
101        case GGML_TYPE_IQ4_NL:
102            return MMQ_Q8_1_DS_LAYOUT_D4;
103        default:
104            GGML_ABORT("fatal error");
105            break;
106    }
107}
108
109struct tile_x_sizes {
110    int qs;
111    int dm;
112    int sc;
113};
114
115// Decouple shared memory tile sizes from WARP_SIZE to allow for different warp sizes.
116// The K dimension of the tiles has either,
117// 1*MMQ_TILE_NE_K==32 (always for TILE_Y_K) or 2*MMQ_TILE_NE_K==64 (typically for TILE_X_K),
118// 32 bit elements for the quantized data (does not include scales).
119// In other words, the size of the quantized data in the K dimension is a multiple of MMQ_TILE_NE_K.
120// The final tile size in K direction is padded to avoid shared memory bank conflicts,
121// in terms of 32 bit elements that means K % 2 == 1 for dp4a or K % 8 == 4 for mma.
122#define MMQ_TILE_NE_K 32
123
124// block_q8_1_mmq has (128 8-bit ints == 32 32-bit ints + 4 32-bit scales)
125#define MMQ_TILE_Y_K     (MMQ_TILE_NE_K + MMQ_TILE_NE_K / QI8_1)
126#define MMQ_TILE_Y_FP4_K MMQ_TILE_Y_K
127
128enum ggml_cuda_mmq_sram_layout {
129    GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0,
130    GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1,
131    GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K,
132    GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K,
133    GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K,
134    GGML_CUDA_MMQ_SRAM_LAYOUT_FP4,   // MXFP4 and NVFP4 on Blackwell.
135    GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, // Generic NVFP4
136};
137
138static constexpr __host__ __device__ int ggml_cuda_mmq_get_sram_stride(ggml_cuda_mmq_sram_layout sram_layout) {
139    switch (sram_layout) {
140        case GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0:
141            return 2*MMQ_TILE_NE_K + 2*MMQ_TILE_NE_K/QI8_0 + 4;
142        case GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1:
143            return 2*MMQ_TILE_NE_K + 2*MMQ_TILE_NE_K/QI8_1 + 4;
144        case GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K:
145            return 2*MMQ_TILE_NE_K + MMQ_TILE_NE_K         + 4;
146        case GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K:
147            return 2*MMQ_TILE_NE_K + MMQ_TILE_NE_K/2       + 4;
148        case GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K:
149            return 2*MMQ_TILE_NE_K + MMQ_TILE_NE_K/QI6_K   + MMQ_TILE_NE_K/8 + 7;
150        case GGML_CUDA_MMQ_SRAM_LAYOUT_FP4:
151            return 2*MMQ_TILE_NE_K + 8                     + 4;
152        case GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4:
153            return 2*MMQ_TILE_NE_K + MMQ_TILE_NE_K/2       + 4;
154        default:
155            return -1;
156    }
157}
158
159static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0)  % 8 == 4, "Wrong padding.");
160static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1)  % 8 == 4, "Wrong padding.");
161static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K)  % 8 == 4, "Wrong padding.");
162static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K)  % 8 == 4, "Wrong padding.");
163static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K)  % 8 == 4, "Wrong padding.");
164static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_FP4)   % 8 == 4, "Wrong padding.");
165static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4) % 8 == 4, "Wrong padding.");
166
167static_assert(ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_FP4) == ggml_cuda_mmq_get_sram_stride(GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1), "Wrong tile size for MXFP4");
168
169// Config options for the MMQ kernel.
170// Should not affect results, only speed/register pressure/shared memory use.
171struct ggml_cuda_mmq_config {
172    ggml_type                 type;        // src0->type
173    int                       nthreads;    // Number of threads per CUDA block.
174    int                       occupancy;   // Targeted occupancy for the MMA kernel.
175    int                       I;           // SRAM tile width in src0->ne[1]/dst->ne[0] direction.
176    int                       J;           // SRAM tile width in src1->ne[1]/dst->ne[1] direction.
177    ggml_cuda_mmq_sram_layout sram_layout; // SRAM tile length in src0->ne[0]/src1->ne[0] direction (physical 32 bit elements).
178    int                       K_vram;      // VRAM tile length in src0->ne[0]/src1->ne[0] direction (logical elements).
179    bool                      stream_k;    // Whether or not to use stream-k decomposition.
180    bool                      fallback;    // Whether a fallback for out-of-bounds check in src0->ne[1] direction is needed.
181
182    constexpr __host__ __device__ ggml_cuda_mmq_config(
183            ggml_type type, int nthreads, int occupancy, int I, int J, ggml_cuda_mmq_sram_layout sram_layout, int K_vram, bool stream_k, bool fallback) :
184        type(type), nthreads(nthreads), occupancy(occupancy), I(I), J(J), sram_layout(sram_layout), K_vram(K_vram), stream_k(stream_k), fallback(fallback) {}
185
186    constexpr __device__ int rows_per_warp() const {
187#if defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE)
188        return 16;
189#else
190        return J >= 48 && J % 16 == 0 ? 32 : 16;
191#endif // defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE)
192    }
193
194    // TODO transition all combinations of GPUs and quantizations to the MMA data layout.
195    __host__ int use_mma_data_layout(const int cc) const {
196        if (amd_mfma_available(cc) || amd_wmma_available(cc) || turing_mma_available(cc)) {
197            return true;
198        }
199        return false;
200    }
201
202    constexpr __device__ bool use_mma_data_layout() const {
203#if defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE)
204        return true;
205#else
206        return false;
207#endif // defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE)
208    }
209
210};
211
212#define CASE(type_, nthreads_, occupancy_, I_, J_, sram_layout_, K_vram_, stream_k_, fallback_)                                           \
213    if (type == (type_) && J == (J_) && fallback == (fallback_)) {                                                                        \
214        static_assert((nthreads_) %  32 == 0 && (nthreads_)       <= 512, "bad nthreads");                                                \
215        static_assert(                          (occupancy_)      <=   8, "bad occupancy");                                               \
216        static_assert((I_)        %  32 == 0,                             "bad I");                                                       \
217        static_assert((J_)        %   8 == 0,                             "bad J");                                                       \
218        static_assert((K_vram_)   % 256 == 0,                             "bad K_vram");                                                  \
219        return ggml_cuda_mmq_config((type_), (nthreads_), (occupancy_), (I_), (J_), (sram_layout_), (K_vram_), (stream_k_), (fallback_)); \
220    }                                                                                                                                     \
221
222#include "mmq-config-pascal-older.cuh"
223#include "mmq-config-pascal-dp4a.cuh"
224#include "mmq-config-ampere.cuh"
225#include "mmq-config-blackwell.cuh"
226
227#include "mmq-config-gcn.cuh"
228#include "mmq-config-cdna.cuh"
229#include "mmq-config-rdna2.cuh"
230#include "mmq-config-rdna3.cuh"
231#include "mmq-config-rdna3-5.cuh"
232#include "mmq-config-rdna4.cuh"
233
234#undef CASE
235
236static __host__ ggml_cuda_mmq_config ggml_cuda_mmq_get_config(const ggml_type type, const int J, const bool fallback, const int cc) {
237    if (GGML_CUDA_CC_IS_AMD(cc)) {
238        if (GGML_CUDA_CC_IS_GCN(cc)) {
239            return ggml_cuda_mmq_get_config_gcn(type, J, fallback);
240        }
241        if (GGML_CUDA_CC_IS_CDNA(cc)) {
242            return ggml_cuda_mmq_get_config_cdna(type, J, fallback);
243        }
244        if (GGML_CUDA_CC_IS_RDNA4(cc)) {
245            return ggml_cuda_mmq_get_config_rdna4(type, J, fallback);
246        }
247        if (GGML_CUDA_CC_IS_RDNA3_5(cc)) {
248            return ggml_cuda_mmq_get_config_rdna3_5(type, J, fallback);
249        }
250        if (GGML_CUDA_CC_IS_RDNA3(cc)) {  // covers RDNA 3.0
251            return ggml_cuda_mmq_get_config_rdna3(type, J, fallback);
252        }
253        return ggml_cuda_mmq_get_config_rdna2(type, J, fallback);
254    }
255    if (blackwell_mma_available(cc)) {
256        return ggml_cuda_mmq_get_config_blackwell(type, J, fallback);
257    }
258    if (ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_VOLTA) {
259        return ggml_cuda_mmq_get_config_ampere(type, J, fallback);
260    }
261    if (ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_DP4A) {
262        return ggml_cuda_mmq_get_config_pascal_dp4a(type, J, fallback);
263    }
264    return ggml_cuda_mmq_get_config_pascal_older(type, J, fallback);
265}
266
267static constexpr __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_config(ggml_type type, int J, bool fallback) {
268#ifdef GGML_USE_HIP
269#ifdef GCN
270    return ggml_cuda_mmq_get_config_gcn(type, J, fallback);
271#elif defined(CDNA)
272    return ggml_cuda_mmq_get_config_cdna(type, J, fallback);
273#elif defined(RDNA4)
274    return ggml_cuda_mmq_get_config_rdna4(type, J, fallback);
275#elif defined(RDNA3_5)
276    return ggml_cuda_mmq_get_config_rdna3_5(type, J, fallback);
277#elif defined(RDNA3)
278    return ggml_cuda_mmq_get_config_rdna3(type, J, fallback);
279#else
280    return ggml_cuda_mmq_get_config_rdna2(type, J, fallback);
281#endif // CDNA
282#else
283#ifdef BLACKWELL_MMA_AVAILABLE
284    return ggml_cuda_mmq_get_config_blackwell(type, J, fallback);
285#elif __CUDA_ARCH__ >= GGML_CUDA_CC_VOLTA
286    return ggml_cuda_mmq_get_config_ampere(type, J, fallback);
287#elif __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A
288    return ggml_cuda_mmq_get_config_pascal_dp4a(type, J, fallback);
289#else
290    return ggml_cuda_mmq_get_config_pascal_older(type, J, fallback);
291#endif // BLACKWELL_MMA_AVAILABLE
292#endif // GGML_USE_HIP
293    GGML_UNUSED_VARS(type, J, fallback);
294}
295
296static __host__ int ggml_cuda_mmq_get_type(const ggml_type type, const int J, const bool fallback, const int cc) {
297    return ggml_cuda_mmq_get_config(type, J, fallback, cc).type;
298}
299
300static constexpr __device__ int ggml_cuda_mmq_get_type(ggml_type type, int J, bool fallback) {
301    return ggml_cuda_mmq_get_config(type, J, fallback).type;
302}
303
304static __host__ int ggml_cuda_mmq_get_nthreads(const ggml_type type, const int J, const bool fallback, const int cc) {
305    return ggml_cuda_mmq_get_config(type, J, fallback, cc).nthreads;
306}
307
308static constexpr __device__ int ggml_cuda_mmq_get_nthreads(ggml_type type, int J, bool fallback) {
309    return ggml_cuda_mmq_get_config(type, J, fallback).nthreads;
310}
311
312static __host__ int ggml_cuda_mmq_get_occupancy(const ggml_type type, const int J, const bool fallback, const int cc) {
313    return ggml_cuda_mmq_get_config(type, J, fallback, cc).occupancy;
314}
315
316static constexpr __device__ int ggml_cuda_mmq_get_occupancy(ggml_type type, int J, bool fallback) {
317    return ggml_cuda_mmq_get_config(type, J, fallback).occupancy;
318}
319
320static __host__ int ggml_cuda_mmq_get_I(const ggml_type type, const int J, const bool fallback, const int cc) {
321    return ggml_cuda_mmq_get_config(type, J, fallback, cc).I;
322}
323
324static constexpr __device__ int ggml_cuda_mmq_get_I(ggml_type type, int J, bool fallback) {
325    return ggml_cuda_mmq_get_config(type, J, fallback).I;
326}
327
328static __host__ int ggml_cuda_mmq_get_J(const ggml_type type, const int J, const bool fallback, const int cc) {
329    return ggml_cuda_mmq_get_config(type, J, fallback, cc).J;
330}
331
332static constexpr __device__ int ggml_cuda_mmq_get_J(ggml_type type, int J, bool fallback) {
333    return ggml_cuda_mmq_get_config(type, J, fallback).J;
334}
335
336static __host__ ggml_cuda_mmq_sram_layout ggml_cuda_mmq_get_sram_layout(const ggml_type type, const int J, const bool fallback, const int cc) {
337    return ggml_cuda_mmq_get_config(type, J, fallback, cc).sram_layout;
338}
339
340static constexpr __device__ ggml_cuda_mmq_sram_layout ggml_cuda_mmq_get_sram_layout(ggml_type type, int J, bool fallback) {
341    return ggml_cuda_mmq_get_config(type, J, fallback).sram_layout;
342}
343
344static __host__ int ggml_cuda_mmq_get_K_vram(const ggml_type type, const int J, const bool fallback, const int cc) {
345    return ggml_cuda_mmq_get_config(type, J, fallback, cc).K_vram;
346}
347
348static constexpr __device__ int ggml_cuda_mmq_get_K_vram(ggml_type type, int J, bool fallback) {
349    return ggml_cuda_mmq_get_config(type, J, fallback).K_vram;
350}
351
352static __host__ bool ggml_cuda_mmq_get_stream_k(const ggml_type type, const int J, const bool fallback, const int cc) {
353    return ggml_cuda_mmq_get_config(type, J, fallback, cc).stream_k;
354}
355
356static constexpr __device__ bool ggml_cuda_mmq_get_stream_k(ggml_type type, int J, bool fallback) {
357    return ggml_cuda_mmq_get_config(type, J, fallback).stream_k;
358}
359
360static __host__ int ggml_cuda_mmq_get_fallback(const ggml_type type, const int J, const bool fallback, const int cc) {
361    return ggml_cuda_mmq_get_config(type, J, fallback, cc).fallback;
362}
363
364static constexpr __device__ int ggml_cuda_mmq_get_fallback(ggml_type type, int J, bool fallback) {
365    return ggml_cuda_mmq_get_config(type, J, fallback).fallback;
366}
367
368// ---------------------------------------------------------------------------------------------
369
370static __host__ int ggml_cuda_mmq_get_sram_stride(const ggml_type type, const int J, const bool fallback, const int cc) {
371    return ggml_cuda_mmq_get_sram_stride(ggml_cuda_mmq_get_sram_layout(type, J, fallback, cc));
372}
373
374static constexpr __device__ int ggml_cuda_mmq_get_sram_stride(ggml_type type, int J, bool fallback) {
375    return ggml_cuda_mmq_get_sram_stride(ggml_cuda_mmq_get_sram_layout(type, J, fallback));
376}
377
378static __host__ int ggml_cuda_mmq_get_J_max(const ggml_type type, const bool fallback, const int cc, const int64_t ne11) {
379    int ret = std::min(ne11, int64_t(512));
380    ret -= ret % 8;
381    for (;ret > 0; ret -= 8) {
382        if (ggml_cuda_mmq_get_config(type, ret, fallback, cc).type != GGML_TYPE_COUNT) {
383            return ret;
384        }
385    }
386    return ret;
387}
388
389static constexpr __device__ int ggml_cuda_mmq_get_rows_per_warp(ggml_type type, int J, bool fallback) {
390    return ggml_cuda_mmq_get_config(type, J, fallback).rows_per_warp();
391}
392
393#define MMQ_DP4A_TXS_Q4_0    tile_x_sizes{I*MMQ_TILE_NE_K   + I, I*MMQ_TILE_NE_K/QI4_0   + I/QI4_0,     0}
394#define MMQ_DP4A_TXS_Q4_1    tile_x_sizes{I*MMQ_TILE_NE_K   + I, I*MMQ_TILE_NE_K/QI4_1   + I/QI4_1,     0}
395#define MMQ_DP4A_TXS_Q8_0    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K*2/QI8_0 + I/(QI8_0/2), 0}
396#define MMQ_DP4A_TXS_Q8_0_16 tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K*4/QI8_0 + I/(QI8_0/4), 0}
397#define MMQ_DP4A_TXS_Q8_1    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K*2/QI8_1 + I/(QI8_1/2), 0}
398#define MMQ_DP4A_TXS_Q2_K    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K         + I,           0}
399#define MMQ_DP4A_TXS_Q3_K    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I,                                     I*MMQ_TILE_NE_K/8 + I/8}
400#define MMQ_DP4A_TXS_Q4_K    tile_x_sizes{I*MMQ_TILE_NE_K   + I, I*MMQ_TILE_NE_K/QI4_K,                 I*MMQ_TILE_NE_K/8 + I/8}
401#define MMQ_DP4A_TXS_Q5_K    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K/QI5_K   + I/QI5_K,     I*MMQ_TILE_NE_K/8 + I/8}
402#define MMQ_DP4A_TXS_Q6_K    tile_x_sizes{I*MMQ_TILE_NE_K*2 + I, I*MMQ_TILE_NE_K/QI6_K   + I/QI6_K,     I*MMQ_TILE_NE_K/8 + I/8}
403
404static constexpr __host__ __device__ tile_x_sizes mmq_get_dp4a_tile_x_sizes(ggml_type type, int I) {
405    switch (type) {
406        case GGML_TYPE_Q1_0:    return MMQ_DP4A_TXS_Q8_0;
407        case GGML_TYPE_Q2_0:    return MMQ_DP4A_TXS_Q8_0;
408        case GGML_TYPE_Q4_0:    return MMQ_DP4A_TXS_Q4_0;
409        case GGML_TYPE_Q4_1:    return MMQ_DP4A_TXS_Q4_1;
410        case GGML_TYPE_Q5_0:    return MMQ_DP4A_TXS_Q8_0;
411        case GGML_TYPE_Q5_1:    return MMQ_DP4A_TXS_Q8_1;
412        case GGML_TYPE_Q8_0:    return MMQ_DP4A_TXS_Q8_0;
413        case GGML_TYPE_MXFP4:   return MMQ_DP4A_TXS_Q8_1;
414        case GGML_TYPE_NVFP4:   return MMQ_DP4A_TXS_Q8_0_16;
415        case GGML_TYPE_Q2_K:    return MMQ_DP4A_TXS_Q2_K;
416        case GGML_TYPE_Q3_K:    return MMQ_DP4A_TXS_Q3_K;
417        case GGML_TYPE_Q4_K:    return MMQ_DP4A_TXS_Q4_K;
418        case GGML_TYPE_Q5_K:    return MMQ_DP4A_TXS_Q5_K;
419        case GGML_TYPE_Q6_K:    return MMQ_DP4A_TXS_Q6_K;
420        case GGML_TYPE_IQ2_XXS: return MMQ_DP4A_TXS_Q8_0;
421        case GGML_TYPE_IQ2_XS:  return MMQ_DP4A_TXS_Q8_0_16;
422        case GGML_TYPE_TQ2_T:   return MMQ_DP4A_TXS_Q8_0_16;
423        case GGML_TYPE_TQK6:    return MMQ_DP4A_TXS_Q8_0_16;
424        case GGML_TYPE_TQK7:    return MMQ_DP4A_TXS_Q8_0_16;
425        case GGML_TYPE_TQP5:    return MMQ_DP4A_TXS_Q8_0_16;
426        case GGML_TYPE_TQP6:    return MMQ_DP4A_TXS_Q8_0_16;
427        case GGML_TYPE_TQP7:    return MMQ_DP4A_TXS_Q8_0_16;
428        case GGML_TYPE_IQ2_S:   return MMQ_DP4A_TXS_Q8_0_16;
429        case GGML_TYPE_IQ3_XXS: return MMQ_DP4A_TXS_Q8_0;
430        case GGML_TYPE_IQ3_S:   return MMQ_DP4A_TXS_Q8_0;
431        case GGML_TYPE_IQ1_S:   return MMQ_DP4A_TXS_Q8_0;
432        case GGML_TYPE_IQ4_XS:  return MMQ_DP4A_TXS_Q8_0;
433        case GGML_TYPE_IQ4_NL:  return MMQ_DP4A_TXS_Q8_0;
434        default:                return tile_x_sizes{0, 0, 0};
435    }
436}
437
438// FIXME temporary until all combinations of data types and GPUs can use the MMA data layout
439static __host__ int ggml_cuda_mmq_get_nbytes_shared_x(const ggml_cuda_mmq_config & config, const int cc) {
440    if (config.use_mma_data_layout(cc)) {
441        return config.I * ggml_cuda_mmq_get_sram_stride(config.sram_layout) * 4;
442    }
443    const tile_x_sizes txs = mmq_get_dp4a_tile_x_sizes(config.type, config.I);
444    return (txs.qs + txs.dm + txs.sc) * 4;
445}
446
447// ------------------------------------------------------------
448
449#include "mmq-load-tiles.cuh"
450#include "mmq-vec-dot.cuh"
451
452template <ggml_type type, int J, bool fallback> static __device__ __forceinline__ void ggml_cuda_mmq_write_back_dp4a(
453        const float * __restrict__ sum, const int32_t * __restrict__ ids_dst, float * __restrict__ dst,
454        const float * __restrict__ y_scale, const int stride, const int i_max, const int j_max) {
455    constexpr int warp_size = ggml_cuda_get_physical_warp_size();
456    constexpr int nwarps    = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size;
457    constexpr int I         = ggml_cuda_mmq_get_I(type, J, fallback);
458
459    const bool y_scale_used = y_scale != nullptr;
460
461#pragma unroll
462    for (int j0 = 0; j0 < J; j0 += nwarps) {
463        const int j = j0 + threadIdx.y;
464
465        if (j > j_max) {
466            return;
467        }
468
469#pragma unroll
470        for (int i0 = 0; i0 < I; i0 += warp_size) {
471            const int i = i0 + threadIdx.x;
472
473            if (fallback && i > i_max) {
474                continue;
475            }
476
477            if constexpr (type == GGML_TYPE_NVFP4) {
478                if (y_scale_used) {
479                    dst[ids_dst[j]*stride + i] = y_scale[j] * sum[(j0/nwarps) * (I/warp_size) + i0/warp_size];
480                } else {
481                    dst[ids_dst[j]*stride + i] = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size];
482                }
483            } else {
484                dst[ids_dst[j]*stride + i] = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size];
485                GGML_UNUSED(y_scale_used);
486            }
487        }
488    }
489}
490
491template<ggml_type type, int J, bool fallback>
492static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma(
493            const float * __restrict__ sum, const int * __restrict__ ids_dst, float * __restrict__ dst,
494            const float * __restrict__ y_scale, const int stride, const int i_max, const int j_max) {
495
496#if defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE)
497    typedef tile<16, 16, int, DATA_LAYOUT_J_MAJOR> tile_C;
498#else
499    typedef tile<16,  8, int> tile_C;
500#endif // defined(AMD_MFMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE)
501
502    constexpr int rows_per_warp = ggml_cuda_mmq_get_rows_per_warp(type, J, fallback);
503    constexpr int ntx           = rows_per_warp/tile_C::I; // Number of x minitiles per warp.
504
505    const int i0 = (threadIdx.y / ntx) * (ntx*tile_C::I);
506
507    const bool y_scale_used = y_scale != nullptr;
508
509#pragma unroll
510    for (int j0 = 0; j0 < J; j0 += ntx*tile_C::J) {
511#pragma unroll
512        for (int n = 0; n < ntx; ++n) {
513#pragma unroll
514            for (int l = 0; l < tile_C::ne; ++l) {
515                const int j = j0 + (threadIdx.y % ntx) * tile_C::J + tile_C::get_j(l);
516
517                if (j > j_max) {
518                    continue;
519                }
520
521                const int i = i0 + n*tile_C::I + tile_C::get_i(l);
522
523                if (fallback && i > i_max) {
524                    continue;
525                }
526
527                if constexpr (type == GGML_TYPE_NVFP4) {
528                    if (y_scale_used) {
529                        dst[ids_dst[j]*stride + i] = y_scale[j] * sum[(j0/tile_C::J + n)*tile_C::ne + l];
530                    } else {
531                        dst[ids_dst[j]*stride + i] = sum[(j0/tile_C::J + n)*tile_C::ne + l];
532                    }
533                } else {
534                    dst[ids_dst[j]*stride + i] = sum[(j0/tile_C::J + n)*tile_C::ne + l];
535                    GGML_UNUSED(y_scale_used);
536                }
537            }
538        }
539    }
540}
541
542// -------------------------------------------------------------------------------------------------------------------------------------
543
544// TODO remove this struct and use ggml_cuda_mmq_sram_layout instead.
545struct ggml_cuda_mmq_util_funcs {
546    int              vdr;
547    ggml_cuda_mmq_load_tiles_t load_tiles;
548    ggml_cuda_mmq_vec_dot_t    vec_dot;
549    ggml_cuda_mmq_write_back_t write_back;
550
551    constexpr __host__ __device__ ggml_cuda_mmq_util_funcs(
552            int vdr, ggml_cuda_mmq_load_tiles_t load_tiles, ggml_cuda_mmq_vec_dot_t vec_dot, ggml_cuda_mmq_write_back_t write_back) :
553        vdr(vdr), load_tiles(load_tiles), vec_dot(vec_dot), write_back(write_back) {}
554};
555
556template <ggml_type type, int J, bool fallback>
557static constexpr __device__ ggml_cuda_mmq_util_funcs ggml_cuda_mmq_get_util_funcs() {
558    if (!ggml_cuda_mmq_get_config(type, J, fallback).use_mma_data_layout()) {
559        switch (type) {
560            case GGML_TYPE_Q1_0:
561                return ggml_cuda_mmq_util_funcs(
562                    VDR_Q1_0_Q8_1_MMQ,
563                    ggml_cuda_mmq_load_tiles_q1_0<type, J, fallback>,
564                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
565                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
566            case GGML_TYPE_Q2_0:
567                return ggml_cuda_mmq_util_funcs(
568                    VDR_Q2_0_Q8_1_MMQ,
569                    ggml_cuda_mmq_load_tiles_q2_0<type, J, fallback>,
570                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
571                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
572            case GGML_TYPE_Q4_0:
573                return ggml_cuda_mmq_util_funcs(
574                    VDR_Q4_0_Q8_1_MMQ,
575                    ggml_cuda_mmq_load_tiles_q4_0<type, J, fallback>,
576                    ggml_cuda_mmq_vec_dot_q4_0_q8_1_dp4a<type, J, fallback>,
577                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
578            case GGML_TYPE_Q4_1:
579                return ggml_cuda_mmq_util_funcs(
580                    VDR_Q4_1_Q8_1_MMQ,
581                    ggml_cuda_mmq_load_tiles_q4_1<type, J, fallback>,
582                    ggml_cuda_mmq_vec_dot_q4_1_q8_1_dp4a<type, J, fallback>,
583                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
584            case GGML_TYPE_Q5_0:
585                return ggml_cuda_mmq_util_funcs(
586                    VDR_Q5_0_Q8_1_MMQ,
587                    ggml_cuda_mmq_load_tiles_q5_0<type, J, fallback>,
588                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
589                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
590            case GGML_TYPE_Q5_1:
591                return ggml_cuda_mmq_util_funcs(
592                    VDR_Q5_1_Q8_1_MMQ,
593                    ggml_cuda_mmq_load_tiles_q5_1<type, J, fallback>,
594                    ggml_cuda_mmq_vec_dot_q8_1_q8_1_dp4a<type, J, fallback>,
595                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
596            case GGML_TYPE_Q8_0:
597                return ggml_cuda_mmq_util_funcs(
598                    VDR_Q8_0_Q8_1_MMQ,
599                    ggml_cuda_mmq_load_tiles_q8_0<type, J, fallback>,
600                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
601                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
602// ---------------------------------------------------------------------------------------------
603            case GGML_TYPE_Q2_K:
604                return ggml_cuda_mmq_util_funcs(
605                    VDR_Q2_K_Q8_1_MMQ,
606                    ggml_cuda_mmq_load_tiles_q2_K<type, J, fallback>,
607                    ggml_cuda_mmq_vec_dot_q2_K_q8_1_dp4a<type, J, fallback>,
608                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
609            case GGML_TYPE_Q3_K:
610                return ggml_cuda_mmq_util_funcs(
611                    VDR_Q3_K_Q8_1_MMQ,
612                    ggml_cuda_mmq_load_tiles_q3_K<type, J, fallback>,
613                    ggml_cuda_mmq_vec_dot_q3_K_q8_1_dp4a<type, J, fallback>,
614                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
615            case GGML_TYPE_Q4_K:
616                return ggml_cuda_mmq_util_funcs(
617                    VDR_Q4_K_Q8_1_MMQ,
618                    ggml_cuda_mmq_load_tiles_q4_K<type, J, fallback>,
619                    ggml_cuda_mmq_vec_dot_q4_K_q8_1_dp4a<type, J, fallback>,
620                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
621            case GGML_TYPE_Q5_K:
622                return ggml_cuda_mmq_util_funcs(
623                    VDR_Q5_K_Q8_1_MMQ,
624                    ggml_cuda_mmq_load_tiles_q5_K<type, J, fallback>,
625                    ggml_cuda_mmq_vec_dot_q5_K_q8_1_dp4a<type, J, fallback>,
626                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
627            case GGML_TYPE_Q6_K:
628                return ggml_cuda_mmq_util_funcs(
629                    VDR_Q6_K_Q8_1_MMQ,
630                    ggml_cuda_mmq_load_tiles_q6_K<type, J, fallback>,
631                    ggml_cuda_mmq_vec_dot_q6_K_q8_1_dp4a<type, J, fallback>,
632                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
633// ---------------------------------------------------------------------------------------------
634            case GGML_TYPE_IQ1_S:
635                return ggml_cuda_mmq_util_funcs(
636                    VDR_IQ1_S_Q8_1_MMQ,
637                    ggml_cuda_mmq_load_tiles_iq1_s<type, J, fallback>,
638                    ggml_cuda_mmq_vec_dot_q8_1_q8_1_dp4a<type, J, fallback>,
639                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
640            case GGML_TYPE_IQ2_XXS:
641                return ggml_cuda_mmq_util_funcs(
642                    VDR_IQ2_XXS_Q8_1_MMQ,
643                    ggml_cuda_mmq_load_tiles_iq2_xxs<type, J, fallback>,
644                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
645                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
646            case GGML_TYPE_IQ2_XS:
647                return ggml_cuda_mmq_util_funcs(
648                    VDR_IQ2_XS_Q8_1_MMQ,
649                    ggml_cuda_mmq_load_tiles_iq2_xs<type, J, fallback>,
650                    ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_dp4a<type, J, fallback>,
651                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
652            case GGML_TYPE_IQ2_S:
653                return ggml_cuda_mmq_util_funcs(
654                    VDR_IQ2_S_Q8_1_MMQ,
655                    ggml_cuda_mmq_load_tiles_iq2_s<type, J, fallback>,
656                    ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_dp4a<type, J, fallback>,
657                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
658            case GGML_TYPE_TQ2_T:
659            case GGML_TYPE_TQK6:
660            case GGML_TYPE_TQK7:
661            case GGML_TYPE_TQP5:
662            case GGML_TYPE_TQP6:
663            case GGML_TYPE_TQP7:
664                return ggml_cuda_mmq_util_funcs(
665                    VDR_IQ2_XS_Q8_1_MMQ,
666                    ggml_cuda_mmq_load_tiles_tq<type, J, fallback>,
667                    ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_dp4a<type, J, fallback>,
668                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
669            case GGML_TYPE_IQ3_XXS:
670                return ggml_cuda_mmq_util_funcs(
671                    VDR_IQ3_XXS_Q8_1_MMQ,
672                    ggml_cuda_mmq_load_tiles_iq3_xxs<type, J, fallback>,
673                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
674                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
675            case GGML_TYPE_IQ3_S:
676                return ggml_cuda_mmq_util_funcs(
677                    VDR_IQ3_S_Q8_1_MMQ,
678                    ggml_cuda_mmq_load_tiles_iq3_s<type, J, fallback>,
679                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
680                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
681            case GGML_TYPE_IQ4_XS:
682                return ggml_cuda_mmq_util_funcs(
683                    VDR_IQ4_XS_Q8_1_MMQ,
684                    ggml_cuda_mmq_load_tiles_iq4_xs<type, J, fallback>,
685                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
686                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
687            case GGML_TYPE_IQ4_NL:
688                return ggml_cuda_mmq_util_funcs(
689                    VDR_IQ4_NL_Q8_1_MMQ,
690                    ggml_cuda_mmq_load_tiles_iq4_nl<type, J, fallback>,
691                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
692                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
693// ---------------------------------------------------------------------------------------------
694            case GGML_TYPE_MXFP4:
695                return ggml_cuda_mmq_util_funcs(
696                    VDR_MXFP4_Q8_1_MMQ,
697                    ggml_cuda_mmq_load_tiles_mxfp4<type, J, fallback>,
698                    ggml_cuda_mmq_vec_dot_q8_0_q8_1_dp4a<type, J, fallback>,
699                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
700            case GGML_TYPE_NVFP4:
701                return ggml_cuda_mmq_util_funcs(
702                    VDR_NVFP4_Q8_1_MMQ,
703                    ggml_cuda_mmq_load_tiles_nvfp4<type, J, fallback>,
704                    ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_dp4a<type, J, fallback>,
705                    ggml_cuda_mmq_write_back_dp4a<type, J, fallback>);
706            default:
707                return ggml_cuda_mmq_util_funcs(1, nullptr, nullptr, nullptr);
708        }
709    }
710
711// ---------------------------------------------------------------------------------------------
712
713#ifdef BLACKWELL_MMA_AVAILABLE
714    switch (type) {
715        case GGML_TYPE_MXFP4:
716            return ggml_cuda_mmq_util_funcs(
717                -1,
718                ggml_cuda_mmq_load_tiles_mxfp4_fp4<type, J, fallback>,
719                ggml_cuda_mmq_vec_dot_fp4_fp4_mma<type, J, fallback>,
720                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
721        case GGML_TYPE_NVFP4:
722            return ggml_cuda_mmq_util_funcs(
723                -1,
724                ggml_cuda_mmq_load_tiles_nvfp4_nvfp4<type, J, fallback>,
725                ggml_cuda_mmq_vec_dot_fp4_fp4_mma<type, J, fallback>,
726                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
727        default:
728            break;
729    }
730#endif // BLACKWELL_MMA_AVAILABLE
731
732// ---------------------------------------------------------------------------------------------
733
734    switch (type) {
735        case GGML_TYPE_Q1_0:
736            return ggml_cuda_mmq_util_funcs(
737                -1,
738                ggml_cuda_mmq_load_tiles_q1_0<type, J, fallback>,
739                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
740                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
741        case GGML_TYPE_Q2_0:
742            return ggml_cuda_mmq_util_funcs(
743                -1,
744                ggml_cuda_mmq_load_tiles_q2_0<type, J, fallback>,
745                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
746                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
747        case GGML_TYPE_Q4_0:
748            return ggml_cuda_mmq_util_funcs(
749                -1,
750                ggml_cuda_mmq_load_tiles_q4_0<type, J, fallback>,
751                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_DS4>,
752                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
753        case GGML_TYPE_Q4_1:
754            return ggml_cuda_mmq_util_funcs(
755                -1,
756                ggml_cuda_mmq_load_tiles_q4_1<type, J, fallback>,
757                ggml_cuda_mmq_vec_dot_q8_1_q8_1_mma<type, J, fallback>,
758                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
759        case GGML_TYPE_Q5_0:
760            return ggml_cuda_mmq_util_funcs(
761                -1,
762                ggml_cuda_mmq_load_tiles_q5_0<type, J, fallback>,
763                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
764                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
765        case GGML_TYPE_Q5_1:
766            return ggml_cuda_mmq_util_funcs(
767                -1,
768                ggml_cuda_mmq_load_tiles_q5_1<type, J, fallback>,
769                ggml_cuda_mmq_vec_dot_q8_1_q8_1_mma<type, J, fallback>,
770                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
771        case GGML_TYPE_Q8_0:
772            return ggml_cuda_mmq_util_funcs(
773                -1,
774                ggml_cuda_mmq_load_tiles_q8_0<type, J, fallback>,
775                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
776                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
777// ---------------------------------------------------------------------------------------------
778        case GGML_TYPE_Q2_K:
779            return ggml_cuda_mmq_util_funcs(
780                -1,
781                ggml_cuda_mmq_load_tiles_q2_K<type, J, fallback>,
782                ggml_cuda_mmq_vec_dot_q2_K_q8_1_mma<type, J, fallback>,
783                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
784        case GGML_TYPE_Q3_K:
785            return ggml_cuda_mmq_util_funcs(
786                -1,
787                ggml_cuda_mmq_load_tiles_q3_K<type, J, fallback>,
788                ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_mma<type, J, fallback>,
789                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
790        case GGML_TYPE_Q4_K:
791            return ggml_cuda_mmq_util_funcs(
792                -1,
793                ggml_cuda_mmq_load_tiles_q4_K<type, J, fallback>,
794                ggml_cuda_mmq_vec_dot_q8_1_q8_1_mma<type, J, fallback>,
795                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
796        case GGML_TYPE_Q5_K:
797            return ggml_cuda_mmq_util_funcs(
798                -1,
799                ggml_cuda_mmq_load_tiles_q5_K<type, J, fallback>,
800                ggml_cuda_mmq_vec_dot_q8_1_q8_1_mma<type, J, fallback>,
801                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
802        case GGML_TYPE_Q6_K:
803            return ggml_cuda_mmq_util_funcs(
804                -1,
805                ggml_cuda_mmq_load_tiles_q6_K<type, J, fallback>,
806                ggml_cuda_mmq_vec_dot_q6_K_q8_1_mma<type, J, fallback>,
807                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
808// ---------------------------------------------------------------------------------------------
809        case GGML_TYPE_IQ1_S:
810            return ggml_cuda_mmq_util_funcs(
811                -1,
812                ggml_cuda_mmq_load_tiles_iq1_s<type, J, fallback>,
813                ggml_cuda_mmq_vec_dot_q8_1_q8_1_mma<type, J, fallback>,
814                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
815        case GGML_TYPE_IQ2_XXS:
816            return ggml_cuda_mmq_util_funcs(
817                -1,
818                ggml_cuda_mmq_load_tiles_iq2_xxs<type, J, fallback>,
819                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
820                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
821        case GGML_TYPE_IQ2_XS:
822            return ggml_cuda_mmq_util_funcs(
823                -1,
824                ggml_cuda_mmq_load_tiles_iq2_xs<type, J, fallback>,
825                ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_mma<type, J, fallback>,
826                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
827        case GGML_TYPE_IQ2_S:
828            return ggml_cuda_mmq_util_funcs(
829                -1,
830                ggml_cuda_mmq_load_tiles_iq2_s<type, J, fallback>,
831                ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_mma<type, J, fallback>,
832                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
833        case GGML_TYPE_TQ2_T:
834        case GGML_TYPE_TQK6:
835        case GGML_TYPE_TQK7:
836        case GGML_TYPE_TQP5:
837        case GGML_TYPE_TQP6:
838        case GGML_TYPE_TQP7:
839            return ggml_cuda_mmq_util_funcs(
840                -1,
841                ggml_cuda_mmq_load_tiles_tq<type, J, fallback>,
842                ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_mma<type, J, fallback>,
843                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
844        case GGML_TYPE_IQ3_XXS:
845            return ggml_cuda_mmq_util_funcs(
846                -1,
847                ggml_cuda_mmq_load_tiles_iq3_xxs<type, J, fallback>,
848                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
849                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
850        case GGML_TYPE_IQ3_S:
851            return ggml_cuda_mmq_util_funcs(
852                -1,
853                ggml_cuda_mmq_load_tiles_iq3_s<type, J, fallback>,
854                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
855                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
856        case GGML_TYPE_IQ4_XS:
857            return ggml_cuda_mmq_util_funcs(
858                -1,
859                ggml_cuda_mmq_load_tiles_iq4_xs<type, J, fallback>,
860                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
861                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
862        case GGML_TYPE_IQ4_NL:
863            return ggml_cuda_mmq_util_funcs(
864                -1,
865                ggml_cuda_mmq_load_tiles_iq4_nl<type, J, fallback>,
866                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
867                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
868// ---------------------------------------------------------------------------------------------
869        case GGML_TYPE_MXFP4:
870            return ggml_cuda_mmq_util_funcs(
871                -1,
872                ggml_cuda_mmq_load_tiles_mxfp4<type, J, fallback>,
873                ggml_cuda_mmq_vec_dot_q8_0_q8_1_mma<type, J, fallback, MMQ_Q8_1_DS_LAYOUT_D4>,
874                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
875        case GGML_TYPE_NVFP4:
876            return ggml_cuda_mmq_util_funcs(
877                -1,
878                ggml_cuda_mmq_load_tiles_nvfp4<type, J, fallback>,
879                ggml_cuda_mmq_vec_dot_q8_0_16_q8_1_mma<type, J, fallback>,
880                ggml_cuda_mmq_write_back_mma<type, J, fallback>);
881        default:
882            return ggml_cuda_mmq_util_funcs(1, nullptr, nullptr, nullptr);
883    }
884}
885
886template <ggml_type type, int J, bool fallback>
887static constexpr __device__ int ggml_cuda_mmq_get_vdr() {
888    return ggml_cuda_mmq_get_util_funcs<type, J, fallback>().vdr;
889}
890
891template <ggml_type type, int J, bool fallback>
892static constexpr __device__ ggml_cuda_mmq_load_tiles_t ggml_cuda_mmq_get_load_tiles() {
893    return ggml_cuda_mmq_get_util_funcs<type, J, fallback>().load_tiles;
894}
895
896template <ggml_type type, int J, bool fallback>
897static constexpr __device__ ggml_cuda_mmq_vec_dot_t ggml_cuda_mmq_get_vec_dot() {
898    return ggml_cuda_mmq_get_util_funcs<type, J, fallback>().vec_dot;
899}
900
901template <ggml_type type, int J, bool fallback>
902static constexpr __device__ ggml_cuda_mmq_write_back_t ggml_cuda_mmq_get_write_back() {
903    return ggml_cuda_mmq_get_util_funcs<type, J, fallback>().write_back;
904}
905
906// ---------------------------------------------------------------------------------------------
907
908template <ggml_type type, int J, bool fallback, bool fixup>
909static __device__ __forceinline__ void mul_mat_q_process_tile(
910        const char * __restrict__ x, const int offset_x, const int * __restrict__ y,
911        const int * __restrict__ ids_dst, float * __restrict__ dst, float * __restrict__ tmp_fixup,
912        const float * __restrict__ y_scale,
913        const int stride_row_x, const int ncols_y, const int stride_col_dst,
914        const int tile_x_max_i, const int tile_y_max_j, const int kb0_start, const int kb0_stop) {
915
916    constexpr int              warp_size  = ggml_cuda_get_physical_warp_size();
917    constexpr int              nwarps     = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size;
918    constexpr int              qk         = ggml_cuda_type_traits<type>::qk;
919    constexpr int              I          = ggml_cuda_mmq_get_I(type, J, fallback);
920    constexpr ggml_cuda_mmq_load_tiles_t load_tiles = ggml_cuda_mmq_get_load_tiles<type, J, fallback>();
921    constexpr ggml_cuda_mmq_vec_dot_t    vec_dot    = ggml_cuda_mmq_get_vec_dot<type, J, fallback>();
922    constexpr ggml_cuda_mmq_write_back_t write_back = ggml_cuda_mmq_get_write_back<type, J, fallback>();
923
924    extern __shared__ int data_mul_mat_q[];
925    int * tile_y = data_mul_mat_q + J;
926    int * tile_x = tile_y + GGML_PAD(J*MMQ_TILE_Y_K, nwarps*warp_size);
927
928#if defined(BLACKWELL_MMA_AVAILABLE)
929    // FP4 tile stores 8 blocks
930    constexpr int ne_block = (type == GGML_TYPE_MXFP4 || type == GGML_TYPE_NVFP4) ? QK_FP4_MMQ : QK8_1_MMQ;
931#else
932    constexpr int ne_block = QK8_1_MMQ;
933#endif  // defined(BLACKWELL_MMA_AVAILABLE)
934
935    constexpr int ITER_K          = ggml_cuda_mmq_get_K_vram(type, J, fallback);
936    constexpr int blocks_per_iter = ITER_K / qk;
937
938    float sum[J*I / (nwarps*warp_size)] = {0.0f};
939
940    constexpr int sz = sizeof(block_q8_1_mmq) / sizeof(int);
941
942    for (int kb0 = kb0_start; kb0 < kb0_stop; kb0 += blocks_per_iter) {
943        load_tiles(x, tile_x, offset_x + kb0, tile_x_max_i, stride_row_x);
944        {
945            const int * by0 = y + ncols_y * (kb0 * qk / ne_block) * sz;
946#pragma unroll
947            for (int l0 = 0; l0 < J * MMQ_TILE_Y_K; l0 += nwarps * warp_size) {
948                int l = l0 + threadIdx.y*warp_size + threadIdx.x;
949
950                tile_y[l] = by0[l];
951            }
952        }
953
954        __syncthreads();
955
956        vec_dot(tile_x, tile_y, sum, 0);
957
958        __syncthreads();
959
960        {
961            const int * by0 = y + ncols_y * ((kb0 * qk / ne_block) * sz + sz);
962#pragma unroll
963            for (int l0 = 0; l0 < J * MMQ_TILE_Y_K; l0 += nwarps * warp_size) {
964                int l = l0 + threadIdx.y*warp_size + threadIdx.x;
965
966                tile_y[l] = by0[l];
967            }
968        }
969
970        __syncthreads();
971
972        vec_dot(tile_x, tile_y, sum, MMQ_TILE_NE_K);
973
974        __syncthreads();
975    }
976
977    if (fixup) {
978        write_back(sum, ids_dst, tmp_fixup + blockIdx.x*(J*I), y_scale, I, I, J);
979    } else {
980        write_back(sum, ids_dst, dst, y_scale, stride_col_dst, tile_x_max_i, tile_y_max_j);
981    }
982}
983
984
985// The mul_mat_q kernel implements "stream-k" work partitioning as described in https://arxiv.org/abs/2301.03598
986
987template <ggml_type type, int J, bool fallback>
988__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, fallback), ggml_cuda_mmq_get_occupancy(type, J, fallback))
989static __global__ void mul_mat_q(
990        const char * __restrict__ x, const int * __restrict__ y, const int32_t * __restrict__ ids_dst,
991        const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup,
992        const float * __restrict__ y_scale,
993        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,
994        const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
995        const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
996        const uint3 ntx) {
997
998    // Skip unused template specializations for faster compilation:
999    if (ggml_cuda_mmq_get_config(type, J, fallback).type == GGML_TYPE_COUNT) {
1000        NO_DEVICE_CODE;
1001        return;
1002    }
1003
1004    constexpr int warp_size = ggml_cuda_get_physical_warp_size();
1005    constexpr int nwarps    = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size;
1006    constexpr int qk        = ggml_cuda_type_traits<type>::qk;
1007    constexpr int I         = ggml_cuda_mmq_get_I(type, J, fallback);
1008
1009    const uint32_t nty = (nrows_x + I - 1) / I; // Number of tiles y
1010
1011    // Initialize the ids for writing back data with just the index.
1012    // For regular matrix multiplications this is never changed.
1013    // For MoE the correct indices are loaded from ids_dst.
1014    extern __shared__ int ids_dst_shared[]; // Stored at beginning of shared memory.
1015#pragma unroll
1016    for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
1017        const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
1018
1019        if (j0 + nwarps*warp_size > J && j >= J) {
1020            break;
1021        }
1022
1023        ids_dst_shared[j] = j;
1024    }
1025    __syncthreads();
1026
1027    if constexpr (!ggml_cuda_mmq_get_stream_k(type, J, fallback)) {
1028        const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y);
1029        const int wt = tmp2.x;
1030        const int zt = tmp2.y;
1031        const int jt = blockIdx.y;
1032        const int it = blockIdx.x;
1033
1034        // Defaults for regular matrix multiplication:
1035        int col_low    = 0;
1036        int col_high   = ncols_dst;
1037        int col_diff   = ncols_dst;
1038        int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
1039        int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
1040        int offset_y_scale;
1041        if constexpr (type == GGML_TYPE_NVFP4) {
1042            offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
1043        } else {
1044            GGML_UNUSED(offset_y_scale);
1045        }
1046
1047        if (ids_dst) {
1048            col_low  = expert_bounds[zt + 0];
1049            col_high = expert_bounds[zt + 1];
1050            col_diff = col_high - col_low;
1051
1052            offset_y   = 0;
1053            offset_dst = 0;
1054            if constexpr (type == GGML_TYPE_NVFP4) {
1055                offset_y_scale = 0;
1056            }
1057
1058            if (jt*J >= col_diff) {
1059                return;
1060            }
1061
1062            // __syncthreads(); // There is no previous tile that could cause a race condition.
1063#pragma unroll
1064            for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
1065                const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
1066
1067                if (j0 + nwarps*warp_size > J && j >= J) {
1068                    break;
1069                }
1070
1071                ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
1072            }
1073            __syncthreads();
1074        }
1075
1076        offset_y   += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int));
1077        offset_dst += it*I;
1078        const float * y_scale_tile = nullptr;
1079        if constexpr (type == GGML_TYPE_NVFP4) {
1080            offset_y_scale += col_low + jt*J;
1081            y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
1082        }
1083
1084        const int tile_x_max_i = nrows_x  - it*I - 1;
1085        const int tile_y_max_j = col_diff - jt*J - 1;
1086
1087        const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I*stride_row_x;
1088
1089        constexpr bool fixup = false;
1090        mul_mat_q_process_tile<type, J, fallback, fixup>
1091            (x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
1092             stride_row_x, ncols_y, stride_col_dst,
1093             tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z);
1094        return;
1095    }
1096
1097    constexpr int ITER_K          = ggml_cuda_mmq_get_K_vram(type, J, fallback);
1098    constexpr int blocks_per_iter = ITER_K / qk;
1099
1100    // kbc == k block continuous, current index in continuous ijk space.
1101    int kbc      = int64_t(blockIdx.x)    *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
1102    int kbc_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
1103
1104    kbc      -= fastmodulo(kbc,      blocks_per_ne00) % blocks_per_iter;
1105    kbc_stop -= fastmodulo(kbc_stop, blocks_per_ne00) % blocks_per_iter;
1106
1107    // kb0 == k index when doing the matrix multiplication for an output tile.
1108    int kb0_start = fastmodulo(kbc, blocks_per_ne00);
1109    int kb0_stop  = min(blocks_per_ne00.z, uint32_t(kb0_start + kbc_stop - kbc));
1110    while (kbc < kbc_stop && kb0_stop == int(blocks_per_ne00.z)) {
1111        int tmp = fastdiv(kbc, blocks_per_ne00);
1112        uint2 tmp2 = fast_div_modulo(tmp, ntx);
1113        const int jt = tmp2.y;
1114        tmp = tmp2.x;
1115        tmp2 = fast_div_modulo(tmp, nchannels_y);
1116        const int zt = tmp2.y;
1117        tmp = tmp2.x;
1118        tmp2 = fast_div_modulo(tmp, nsamples_y);
1119        const int wt = tmp2.y;
1120        const int it = tmp2.x;
1121
1122        // Defaults for regular matrix multiplication:
1123        int col_low    = 0;
1124        int col_high   = ncols_dst;
1125        int col_diff   = ncols_dst;
1126        int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
1127        int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
1128        int offset_y_scale;
1129        if constexpr (type == GGML_TYPE_NVFP4) {
1130            offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
1131        } else {
1132            GGML_UNUSED(offset_y_scale);
1133        }
1134
1135        if (ids_dst) {
1136            col_low  = expert_bounds[zt + 0];
1137            col_high = expert_bounds[zt + 1];
1138            col_diff = col_high - col_low;
1139
1140            offset_y   = 0;
1141            offset_dst = 0;
1142            if constexpr (type == GGML_TYPE_NVFP4) {
1143                offset_y_scale = 0;
1144            }
1145
1146            if (jt*J >= col_diff) {
1147                kbc += blocks_per_ne00.z;
1148                kbc -= fastmodulo(kbc, blocks_per_ne00);
1149
1150                kb0_start = 0;
1151                kb0_stop  = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
1152
1153                continue;
1154            }
1155
1156            __syncthreads();
1157#pragma unroll
1158            for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
1159                const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
1160
1161                if (j0 + nwarps*warp_size > J && j >= J) {
1162                    break;
1163                }
1164
1165                ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
1166            }
1167            __syncthreads();
1168        }
1169
1170        offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
1171        offset_dst += it*I;
1172        const float * y_scale_tile = nullptr;
1173        if constexpr (type == GGML_TYPE_NVFP4) {
1174            offset_y_scale += col_low + jt * J;
1175            y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
1176        }
1177
1178        const int tile_x_max_i = nrows_x  - it*I - 1;
1179        const int tile_y_max_j = col_diff - jt*J - 1;
1180
1181        const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I*stride_row_x;
1182
1183        constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
1184        mul_mat_q_process_tile<type, J, fallback, fixup>
1185            (x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
1186             stride_row_x, ncols_y, stride_col_dst,
1187             tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
1188
1189        kbc += blocks_per_ne00.z;
1190        kbc -= fastmodulo(kbc, blocks_per_ne00);
1191
1192        kb0_start = 0;
1193        kb0_stop  = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc));
1194    }
1195
1196    if (kbc >= kbc_stop) {
1197        return;
1198    }
1199
1200    int tmp = fastdiv(kbc, blocks_per_ne00);
1201    uint2 tmp2 = fast_div_modulo(tmp, ntx);
1202    const int jt = tmp2.y;
1203    tmp = tmp2.x;
1204    tmp2 = fast_div_modulo(tmp, nchannels_y);
1205    const int zt = tmp2.y;
1206    tmp = tmp2.x;
1207    tmp2 = fast_div_modulo(tmp, nsamples_y);
1208    const int wt = tmp2.y;
1209    const int it = tmp2.x;
1210
1211    // Defaults for regular matrix multiplication:
1212    int col_low    = 0;
1213    int col_high   = ncols_dst;
1214    int col_diff   = ncols_dst;
1215    int offset_y       = wt*stride_sample_y   + zt*stride_channel_y;
1216    int offset_dst     = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst;
1217    int offset_y_scale;
1218    if constexpr (type == GGML_TYPE_NVFP4) {
1219        offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y;
1220    } else {
1221        GGML_UNUSED(offset_y_scale);
1222    }
1223
1224    if (ids_dst) {
1225        col_low  = expert_bounds[zt + 0];
1226        col_high = expert_bounds[zt + 1];
1227        col_diff = col_high - col_low;
1228
1229        offset_y   = 0;
1230        offset_dst = 0;
1231        if constexpr (type == GGML_TYPE_NVFP4) {
1232            offset_y_scale = 0;
1233        }
1234
1235        if (jt*J >= col_diff) {
1236            return;
1237        }
1238
1239        // The memory layout for the fixup buffer is always contiguous, therefore reset ids:
1240        __syncthreads();
1241#pragma unroll
1242        for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) {
1243            const int j = j0 + threadIdx.y*warp_size + threadIdx.x;
1244
1245            if (j0 + nwarps*warp_size > J && j >= J) {
1246                break;
1247            }
1248
1249            ids_dst_shared[j] = j;
1250        }
1251        __syncthreads();
1252    }
1253
1254    offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int));
1255    offset_dst += it*I;
1256    const float * y_scale_tile = nullptr;
1257    if constexpr (type == GGML_TYPE_NVFP4) {
1258        offset_y_scale += col_low + jt * J;
1259        y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr;
1260    }
1261
1262    const int tile_x_max_i = nrows_x  - it*I - 1;
1263    const int tile_y_max_j = col_diff - jt*J - 1;
1264
1265    const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I*stride_row_x;
1266
1267    constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
1268    mul_mat_q_process_tile<type, J, fallback, fixup>
1269        (x, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile,
1270         stride_row_x, ncols_y, stride_col_dst,
1271         tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop);
1272}
1273
1274template <ggml_type type, int J, bool fallback>
1275__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, fallback)/2, 1)
1276static __global__ void mul_mat_q_stream_k_fixup(
1277        const int32_t * __restrict__ ids_dst, const int32_t * __restrict__ expert_bounds, float * __restrict__ dst,
1278        float * __restrict__ tmp_last_tile, const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst,
1279        const int stride_col_dst, const uint3 nchannels_y, const int stride_channel_dst, const uint3 nsamples_y,
1280        const int stride_sample_dst, const uint3 ntx) {
1281    constexpr int warp_size       = ggml_cuda_get_physical_warp_size();
1282    constexpr int nwarps          = (ggml_cuda_mmq_get_nthreads(type, J, fallback) / 2) / warp_size;
1283    constexpr int I               = ggml_cuda_mmq_get_I(type, J, fallback);
1284    constexpr int qk              = ggml_cuda_type_traits<type>::qk;
1285    constexpr int ITER_K          = ggml_cuda_mmq_get_K_vram(type, J, fallback);
1286    constexpr int blocks_per_iter = ITER_K / qk;
1287
1288    float sum[J / nwarps] = {0.0f};
1289    const int i = blockIdx.y*warp_size + threadIdx.x;
1290
1291    const int nty = (nrows_x + I - 1) / I;
1292
1293    const int bidx0 = blockIdx.x;
1294
1295    // kbc == k block continuous, current index in continuous ijk space.
1296    int kbc0      = int64_t(blockIdx.x)    *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
1297    int kbc0_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
1298
1299    kbc0      -= fastmodulo(kbc0,      blocks_per_ne00) % blocks_per_iter;
1300    kbc0_stop -= fastmodulo(kbc0_stop, blocks_per_ne00) % blocks_per_iter;
1301
1302    const bool did_not_have_any_data   = kbc0 == kbc0_stop;
1303    const bool wrote_beginning_of_tile = fastmodulo(kbc0, blocks_per_ne00) == 0;
1304    const bool did_not_write_last      = fastdiv(kbc0, blocks_per_ne00) == fastdiv(kbc0_stop, blocks_per_ne00) && fastmodulo(kbc0_stop, blocks_per_ne00) != 0;
1305    if (did_not_have_any_data || wrote_beginning_of_tile || did_not_write_last) {
1306        return;
1307    }
1308
1309    bool any_fixup = false;
1310
1311    // Iterate over previous blocks and sum up partial sums written to fixup buffer.
1312    // All CUDA blocks that get here must have a previous block that needs a fixup.
1313    int bidx = bidx0 - 1;
1314    int kbc_stop = kbc0;
1315    while(true) {
1316        int kbc = int64_t(bidx)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x;
1317        kbc -= fastmodulo(kbc, blocks_per_ne00) % blocks_per_iter;
1318
1319        if (kbc == kbc_stop) { // Did not have any data.
1320            bidx--;
1321            kbc_stop = kbc;
1322            continue;
1323        }
1324
1325        any_fixup = true;
1326
1327
1328#pragma unroll
1329        for (int j0 = 0; j0 < J; j0 += nwarps) {
1330            const int j = j0 + threadIdx.y;
1331
1332            sum[j0/nwarps] += tmp_last_tile[bidx*(J*I) + j*I + i];
1333        }
1334
1335        // If this block started in a previous tile we are done and don't need to combine additional partial results.
1336        if (fastmodulo(kbc, blocks_per_ne00) == 0 || fastdiv(kbc, blocks_per_ne00) < fastdiv(kbc0, blocks_per_ne00)) {
1337            break;
1338        }
1339        bidx--;
1340        kbc_stop = kbc;
1341    }
1342
1343    if (!any_fixup) {
1344        return;
1345    }
1346
1347    int tmp = fastdiv(kbc0, blocks_per_ne00);
1348    uint2 tmp2 = fast_div_modulo(tmp, ntx);
1349    const int jt = tmp2.y;
1350    tmp = tmp2.x;
1351    tmp2 = fast_div_modulo(tmp, nchannels_y);
1352    const int zt = tmp2.y;
1353    tmp = tmp2.x;
1354    tmp2 = fast_div_modulo(tmp, nsamples_y);
1355    const int wt = tmp2.y;
1356    const int it = tmp2.x;
1357
1358    if (!ids_dst) {
1359        const int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst + it*I;
1360        dst += offset_dst;
1361
1362        const int i_max = nrows_x   - it*I - 1;
1363        const int j_max = ncols_dst - jt*J - 1;
1364        if (fallback && i > i_max) {
1365            return;
1366        }
1367
1368#pragma unroll
1369        for (int j0 = 0; j0 < J; j0 += nwarps) {
1370            const int j = j0 + threadIdx.y;
1371
1372            if (j > j_max) {
1373                return;
1374            }
1375
1376            dst[j*stride_col_dst + i] += sum[j0/nwarps];
1377        }
1378        return;
1379    }
1380
1381    __shared__ int ids_dst_shared[J];
1382    const int col_low  = expert_bounds[zt + 0];
1383    const int col_high = expert_bounds[zt + 1];
1384    const int col_diff = col_high - col_low;
1385
1386    for (int j = threadIdx.y*warp_size + threadIdx.x; j < J; j += nwarps*warp_size) {
1387        ids_dst_shared[j] = ids_dst[col_low + jt*J + j];
1388    }
1389    __syncthreads();
1390
1391    const int offset_dst = it*I;
1392    dst += offset_dst;
1393
1394    const int i_max = nrows_x  - it*I - 1;
1395    const int j_max = col_diff - jt*J - 1;
1396    if (fallback && i > i_max) {
1397        return;
1398    }
1399
1400#pragma unroll
1401    for (int j0 = 0; j0 < J; j0 += nwarps) {
1402        const int j = j0 + threadIdx.y;
1403
1404        if (j > j_max) {
1405            return;
1406        }
1407
1408        dst[ids_dst_shared[j]*stride_col_dst + i] += sum[j0/nwarps];
1409    }
1410}
1411
1412struct mmq_args {
1413    const char * x; ggml_type type_x; const int * y; const int32_t * ids_dst; const int32_t * expert_bounds; float * dst;
1414    const float * y_scale;
1415    int64_t ncols_x; int64_t nrows_x; int64_t ncols_dst; int64_t stride_row_x; int64_t ncols_y; int64_t nrows_dst;
1416    int64_t nchannels_x; int64_t nchannels_y; int64_t stride_channel_x; int64_t stride_channel_y; int64_t stride_channel_dst;
1417    int64_t nsamples_x; int64_t nsamples_y; int64_t stride_sample_x; int64_t stride_sample_y; int64_t stride_sample_dst;
1418    int64_t ncols_max;
1419    int64_t ncols_opt; // value to optimize the tile size against, launch grid still uses ncols_max
1420};
1421
1422static size_t mmq_get_nbytes_shared(const ggml_cuda_mmq_config & config, const int cc) {
1423    const size_t nbs_ids = config.J*sizeof(int);
1424    const size_t nbs_x = ggml_cuda_mmq_get_nbytes_shared_x(config, cc);
1425    const size_t nbs_y = config.J * (sizeof(block_q8_1_mmq));
1426    return nbs_ids + nbs_x + GGML_PAD(nbs_y, config.nthreads*sizeof(int));
1427}
1428
1429template <ggml_type type, int J, bool fallback>
1430static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
1431    const int id = ggml_cuda_get_device();
1432    const int cc = ggml_cuda_info().devices[id].cc;
1433    const int nsm = ggml_cuda_info().devices[id].nsm;
1434    const int warp_size = ggml_cuda_info().devices[id].warp_size;
1435
1436    const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
1437    GGML_ASSERT(config.nthreads % warp_size == 0);
1438    const int nwarps = config.nthreads / warp_size;
1439    const int nbytes_shared = mmq_get_nbytes_shared(config, cc);
1440
1441    const dim3 block_dims(warp_size, nwarps, 1);
1442
1443    CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q<type, J, false>), nbytes_shared);
1444    CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q<type, J,  true>), nbytes_shared);
1445
1446    const int nty  = (args.nrows_x   + config.I - 1) / config.I;
1447    const int ntx  = (args.ncols_max + config.J - 1) / config.J;
1448    const int ntzw = args.nchannels_y * args.nsamples_y;
1449    const dim3 block_nums_xy_tiling(nty, ntx, ntzw);
1450
1451    GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0);
1452    GGML_ASSERT(args.nsamples_y  % args.nsamples_x  == 0);
1453    const int channel_ratio = args.nchannels_y / args.nchannels_x;
1454    const int sample_ratio  = args.nsamples_y  / args.nsamples_x;
1455
1456    const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits<type>::qk);
1457    const uint3 ntx_fd             = init_fastdiv_values(ntx);
1458    const uint3 nchannels_y_fd     = init_fastdiv_values(args.nchannels_y);
1459    const uint3 nsamples_y_fd      = init_fastdiv_values(args.nsamples_y);
1460    const uint3 channel_ratio_fd   = init_fastdiv_values(channel_ratio);
1461    const uint3 sample_ratio_fd    = init_fastdiv_values(sample_ratio);
1462
1463    if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) {
1464        mul_mat_q<type, J, fallback><<<block_nums_xy_tiling, block_dims, nbytes_shared, stream>>>
1465            (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale,
1466             blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
1467             channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
1468             sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
1469             ntx_fd);
1470        return;
1471    }
1472
1473    // 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.
1474    // This is worthwhile if the efficiency of tiling is high and skipping the fixup kernel is more important.
1475    const int ntiles_dst = ntx * nty * ntzw;
1476    const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm;
1477    const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves);
1478    const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1);
1479
1480    GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow.
1481
1482    const bool fixup_needed = ntiles_dst % block_nums_stream_k.x != 0;
1483
1484    ggml_cuda_pool & pool = ctx.pool(id);
1485    ggml_cuda_pool_alloc<float> tmp_fixup(pool);
1486    if (fixup_needed) {
1487        tmp_fixup.alloc(block_nums_stream_k.x * config.J*config.I);
1488    }
1489
1490    const dim3 block_nums_fixup(block_nums_stream_k.x, config.I/warp_size, 1);
1491    const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z);
1492
1493    mul_mat_q<type, J, fallback><<<block_nums_stream_k, block_dims, nbytes_shared, stream>>>
1494        (args.x, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale,
1495         blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst,
1496         channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst,
1497         sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst,
1498         ntx_fd);
1499
1500    if (!fixup_needed) {
1501        return;
1502    }
1503
1504    CUDA_CHECK(cudaGetLastError());
1505    mul_mat_q_stream_k_fixup<type, J, fallback><<<block_nums_fixup, block_dims_fixup, 0, stream>>>
1506        (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst,
1507         args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst,
1508         ntx_fd);
1509}
1510
1511template <ggml_type type, bool fallback>
1512void mul_mat_q_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
1513    const int    id    = ggml_cuda_get_device();
1514    const int    cc    = ggml_cuda_info().devices[id].cc;
1515    const size_t smpbo = ggml_cuda_info().devices[id].smpbo;
1516
1517    int J_best        = 0;
1518    int ntiles_J_best = INT_MAX;
1519
1520    for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) {
1521        const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc);
1522        if (config.type == GGML_TYPE_COUNT) {
1523            continue;
1524        }
1525
1526        if (mmq_get_nbytes_shared(config, cc) > smpbo) {
1527            continue;
1528        }
1529
1530        const int ntiles_x = (args.ncols_opt + config.J - 1) / config.J;
1531
1532        if (ntiles_x < ntiles_J_best) {
1533            J_best = J;
1534            ntiles_J_best = ntiles_x;
1535        }
1536    }
1537
1538    switch (J_best) {
1539        case   8:
1540            launch_mul_mat_q<type,   8, fallback>(ctx, args, stream);
1541            break;
1542        case  16:
1543            launch_mul_mat_q<type,  16, fallback>(ctx, args, stream);
1544            break;
1545        case  24:
1546            launch_mul_mat_q<type,  24, fallback>(ctx, args, stream);
1547            break;
1548        case  32:
1549            launch_mul_mat_q<type,  32, fallback>(ctx, args, stream);
1550            break;
1551        case  40:
1552            launch_mul_mat_q<type,  40, fallback>(ctx, args, stream);
1553            break;
1554        case  48:
1555            launch_mul_mat_q<type,  48, fallback>(ctx, args, stream);
1556            break;
1557        case  56:
1558            launch_mul_mat_q<type,  56, fallback>(ctx, args, stream);
1559            break;
1560        case  64:
1561            launch_mul_mat_q<type,  64, fallback>(ctx, args, stream);
1562            break;
1563        case  72:
1564            launch_mul_mat_q<type,  72, fallback>(ctx, args, stream);
1565            break;
1566        case  80:
1567            launch_mul_mat_q<type,  80, fallback>(ctx, args, stream);
1568            break;
1569        case  88:
1570            launch_mul_mat_q<type,  88, fallback>(ctx, args, stream);
1571            break;
1572        case  96:
1573            launch_mul_mat_q<type,  96, fallback>(ctx, args, stream);
1574            break;
1575        case 104:
1576            launch_mul_mat_q<type, 104, fallback>(ctx, args, stream);
1577            break;
1578        case 112:
1579            launch_mul_mat_q<type, 112, fallback>(ctx, args, stream);
1580            break;
1581        case 120:
1582            launch_mul_mat_q<type, 120, fallback>(ctx, args, stream);
1583            break;
1584        case 128:
1585            launch_mul_mat_q<type, 128, fallback>(ctx, args, stream);
1586            break;
1587        default:
1588            fprintf(stderr, "J_best=%d\n", J_best);
1589            GGML_ABORT("fatal error");
1590            break;
1591    }
1592}
1593
1594template <ggml_type type>
1595void mul_mat_q_case(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) {
1596    if (args.nrows_x % 128 == 0) {
1597        constexpr bool fallback = false;
1598        mul_mat_q_switch_J<type, fallback>(ctx, args, stream);
1599    } else {
1600        constexpr bool fallback = true;
1601        mul_mat_q_switch_J<type, fallback>(ctx, args, stream);
1602    }
1603}
1604
1605#define DECL_MMQ_CASE(type)                                                        \
1606    template void mul_mat_q_case<type>(ggml_backend_cuda_context & ctx, const mmq_args & args, cudaStream_t stream) \
1607
1608extern DECL_MMQ_CASE(GGML_TYPE_Q1_0);
1609extern DECL_MMQ_CASE(GGML_TYPE_Q2_0);
1610extern DECL_MMQ_CASE(GGML_TYPE_Q4_0);
1611extern DECL_MMQ_CASE(GGML_TYPE_Q4_1);
1612extern DECL_MMQ_CASE(GGML_TYPE_Q5_0);
1613extern DECL_MMQ_CASE(GGML_TYPE_Q5_1);
1614extern DECL_MMQ_CASE(GGML_TYPE_Q8_0);
1615// -----------------------------------------
1616extern DECL_MMQ_CASE(GGML_TYPE_Q2_K);
1617extern DECL_MMQ_CASE(GGML_TYPE_Q3_K);
1618extern DECL_MMQ_CASE(GGML_TYPE_Q4_K);
1619extern DECL_MMQ_CASE(GGML_TYPE_Q5_K);
1620extern DECL_MMQ_CASE(GGML_TYPE_Q6_K);
1621// -----------------------------------------
1622extern DECL_MMQ_CASE(GGML_TYPE_IQ1_S);
1623extern DECL_MMQ_CASE(GGML_TYPE_IQ2_XXS);
1624extern DECL_MMQ_CASE(GGML_TYPE_IQ2_XS);
1625extern DECL_MMQ_CASE(GGML_TYPE_IQ2_S);
1626extern DECL_MMQ_CASE(GGML_TYPE_IQ3_XXS);
1627extern DECL_MMQ_CASE(GGML_TYPE_IQ3_S);
1628extern DECL_MMQ_CASE(GGML_TYPE_IQ4_NL);
1629extern DECL_MMQ_CASE(GGML_TYPE_IQ4_XS);
1630extern DECL_MMQ_CASE(GGML_TYPE_TQ2_T);
1631extern DECL_MMQ_CASE(GGML_TYPE_TQK6);
1632extern DECL_MMQ_CASE(GGML_TYPE_TQK7);
1633extern DECL_MMQ_CASE(GGML_TYPE_TQP5);
1634extern DECL_MMQ_CASE(GGML_TYPE_TQP6);
1635extern DECL_MMQ_CASE(GGML_TYPE_TQP7);
1636// -----------------------------------------
1637extern DECL_MMQ_CASE(GGML_TYPE_MXFP4);
1638extern DECL_MMQ_CASE(GGML_TYPE_NVFP4);
1639
1640// -------------------------------------------------------------------------------------------------------------------------
1641
1642void ggml_cuda_mul_mat_q(
1643        ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst);
1644
1645bool ggml_cuda_should_use_mmq(enum ggml_type type, int cc, int64_t ne11, int64_t n_experts);