okami.mom/strata

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

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
29.1 KiB761 linesraw
1#include "common.cuh"
2#include "fattn-common.cuh"
3#include "fattn-mma-f16.cuh"
4#include "fattn-tile.cuh"
5#include "fattn-vec.cuh"
6#include "fattn.cuh"
7
8#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
9// one list per group of ncols1 queries: a column is selected if any query of the group can see it
10__launch_bounds__(256, 1)
11static __global__ void flash_attn_mask_to_sparse_indices(
12        const half * mask_ptr, int32_t * indices_ptr, int32_t * counts_ptr, const int ne30, const int n_queries,
13        const int ncols1, const int n_kv_max, const int64_t s31, const int64_t s33) {
14    ggml_cuda_pdl_sync();
15
16    constexpr int values_per_lane = 8;
17    const int tid      = threadIdx.x;
18    const int warp     = tid / WARP_SIZE;
19    const int lane     = tid % WARP_SIZE;
20    const int sequence = blockIdx.y;
21    const int group    = blockIdx.x;
22
23    const int q0 = group*ncols1;
24    const int q1 = min(q0 + ncols1, n_queries);
25
26    const half * mask = mask_ptr + sequence*s33 + q0*s31;
27    int32_t * indices = indices_ptr + (int64_t(sequence)*gridDim.x + group)*n_kv_max;
28
29    __shared__ int warp_offsets[256/WARP_SIZE];
30    __shared__ int row_count;
31    __shared__ int chunk_count;
32
33    if (tid == 0) {
34        row_count = 0;
35    }
36    __syncthreads();
37
38    for (int i0 = 0; i0 < ne30; i0 += blockDim.x*values_per_lane) {
39        uint32_t selected_warp[values_per_lane];
40        int warp_count = 0;
41#pragma unroll
42        for (int item = 0; item < values_per_lane; ++item) {
43            const int i = i0 + (warp*values_per_lane + item)*WARP_SIZE + lane;
44            bool selected = false;
45            for (int q = 0; q < q1 - q0 && !selected; ++q) {
46                selected = i < ne30 && isfinite(__half2float(mask[q*s31 + i]));
47            }
48            selected_warp[item] = __ballot_sync(0xFFFFFFFF, selected);
49            warp_count += __popc(selected_warp[item]);
50        }
51
52        if (lane == 0) {
53            warp_offsets[warp] = warp_count;
54        }
55        __syncthreads();
56
57        if (tid == 0) {
58            int offset = 0;
59#pragma unroll
60            for (int iw = 0; iw < 256/WARP_SIZE; ++iw) {
61                const int count = warp_offsets[iw];
62                warp_offsets[iw] = offset;
63                offset += count;
64            }
65            chunk_count = offset;
66        }
67        __syncthreads();
68
69        const uint32_t lane_mask = lane == 0 ? 0 : (1u << lane) - 1;
70        int warp_item_offset = 0;
71#pragma unroll
72        for (int item = 0; item < values_per_lane; ++item) {
73            const int i = i0 + (warp*values_per_lane + item)*WARP_SIZE + lane;
74            const int dst = row_count + warp_offsets[warp] + warp_item_offset + __popc(selected_warp[item] & lane_mask);
75            if ((selected_warp[item] & (uint32_t(1) << lane)) && dst < n_kv_max) {
76                indices[dst] = i;
77            }
78            warp_item_offset += __popc(selected_warp[item]);
79        }
80        __syncthreads();
81
82        if (tid == 0) {
83            row_count += chunk_count;
84        }
85        __syncthreads();
86    }
87
88    const int count = min(row_count, n_kv_max);
89    for (int i = count + tid; i < n_kv_max; i += blockDim.x) {
90        indices[i] = -1;
91    }
92    if (tid == 0) {
93        counts_ptr[int64_t(sequence)*gridDim.x + group] = count;
94    }
95    __syncthreads();
96
97    // the dependent grid reads indices, signal once the row is complete
98    ggml_cuda_pdl_lc();
99}
100#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
101
102void ggml_cuda_flash_attn_ext_compact_mask(
103        const ggml_tensor * mask, int32_t * indices, int32_t * counts, int32_t n_queries, int32_t ncols1, int32_t n_kv_max, cudaStream_t stream) {
104#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA)
105    GGML_UNUSED_VARS(mask, indices, counts, n_queries, ncols1, n_kv_max, stream);
106    GGML_ABORT("sparse flash attention is only supported on NVIDIA CUDA");
107#else
108    const int64_t s31 = mask->nb[1] / sizeof(half);
109    const int64_t s33 = mask->nb[3] / sizeof(half);
110    const dim3 blocks_num((n_queries + ncols1 - 1)/ncols1, mask->ne[3], 1);
111    const dim3 block_dim(256, 1, 1);
112    const ggml_cuda_kernel_launch_params launch_params(blocks_num, block_dim, 0, stream);
113    ggml_cuda_kernel_launch(flash_attn_mask_to_sparse_indices, launch_params,
114        (const half *) mask->data, indices, counts, int(mask->ne[0]), n_queries, ncols1, n_kv_max, s31, s33);
115    CUDA_CHECK(cudaGetLastError());
116#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
117}
118
119bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1) {
120#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA)
121    GGML_UNUSED_VARS(cc, dst, ncols1);
122    return false;
123#else
124    const ggml_tensor * Q    = dst->src[0];
125    const ggml_tensor * K    = dst->src[1];
126    const ggml_tensor * mask = dst->src[3];
127
128    float max_bias = 0.0f;
129    float logit_softcap = 0.0f;
130    memcpy(&max_bias,      (const float *) dst->op_params + 1, sizeof(float));
131    memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
132
133    const int32_t n_kv_max = ggml_get_op_params_i32(dst, 4);
134
135    const int64_t n_gather = (ncols1 == 1 ? Q->ne[1] : ncols1) * (int64_t) n_kv_max;
136
137    return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) &&
138        mask != nullptr && n_kv_max > 0 && max_bias == 0.0f && logit_softcap == 0.0f &&
139        mask->ne[0] == K->ne[1] && mask->ne[1] >= Q->ne[1] && mask->ne[2] == 1 &&
140        K->ne[1] >= std::max<int64_t>(4096, 2*n_gather);
141#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
142}
143
144template <int DKQ, int DV, int ncols2>
145static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
146    const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
147    const ggml_tensor * Q = dst->src[0];
148
149#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
150    if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 1, ncols2)) {
151        if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1)) {
152            ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2>(ctx, dst);
153            return;
154        }
155    }
156#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA)
157
158    if constexpr (ncols2 <= 8) {
159        if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) {
160            ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2>(ctx, dst);
161            return;
162        }
163    }
164
165    if constexpr (ncols2 <= 16) {
166        if (Q->ne[1] <= 16/ncols2) {
167            ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2>(ctx, dst);
168            return;
169        }
170    }
171
172    if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) ||
173            (GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) {
174        ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2>(ctx, dst);
175        return;
176    }
177
178    ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2>(ctx, dst);
179}
180
181template <int DKQ, int DV>
182static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
183    const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
184    const ggml_tensor * KQV  = dst;
185    const ggml_tensor * Q    = dst->src[0];
186    const ggml_tensor * K    = dst->src[1];
187    const ggml_tensor * V    = dst->src[2];
188    const ggml_tensor * mask = dst->src[3];
189
190    float max_bias = 0.0f;
191    memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
192
193    // Edge cases like no mask, ALiBi, unpadded K/V, or misaligned addresses for large data transfers
194    //     are put into the template specialization without GQA optimizations.
195    bool use_gqa_opt = mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0;
196    for (const ggml_tensor * t : {Q, K, V, mask}) {
197        if (t == nullptr || ggml_is_quantized(t->type)) {
198            continue;
199        }
200        for (size_t i = 1; i < GGML_MAX_DIMS; ++i) {
201            if (t->nb[i] % 16 != 0) {
202                use_gqa_opt = false;
203                break;
204            }
205        }
206    }
207
208    GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
209    const int gqa_ratio = Q->ne[2] / K->ne[2];
210
211    // On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute:
212    if (cc == GGML_CUDA_CC_VOLTA) {
213        if (use_gqa_opt && gqa_ratio % 8 == 0) {
214            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
215            return;
216        }
217
218        if (use_gqa_opt && gqa_ratio % 4 == 0) {
219            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
220            return;
221        }
222
223        if constexpr (DKQ <= 256) {
224            if (use_gqa_opt && gqa_ratio % 2 == 0) {
225                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
226                return;
227            }
228
229            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
230            return;
231        } else {
232            GGML_ABORT("fatal error");
233        }
234    }
235
236    // On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask.
237    if (amd_wmma_available(cc)) {
238        if (use_gqa_opt && gqa_ratio % 8 == 0) {
239            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
240            return;
241        }
242
243        if (use_gqa_opt && gqa_ratio % 4 == 0) {
244            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
245            return;
246        }
247
248        if (use_gqa_opt && gqa_ratio % 2 == 0) {
249            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
250            return;
251        }
252    }
253
254    if (use_gqa_opt && gqa_ratio > 4) {
255        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
256        return;
257    }
258
259    if (use_gqa_opt && gqa_ratio > 2) {
260        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
261        return;
262    }
263
264    if (use_gqa_opt && gqa_ratio > 1) {
265        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
266        return;
267    }
268
269    if constexpr (DKQ <= 256) {
270        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
271    } else {
272        GGML_ABORT("fatal error");
273    }
274}
275
276static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
277    const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
278    const ggml_tensor * KQV  = dst;
279    const ggml_tensor * Q    = dst->src[0];
280    const ggml_tensor * K    = dst->src[1];
281    const ggml_tensor * V    = dst->src[2];
282    const ggml_tensor * mask = dst->src[3];
283
284    switch (Q->ne[0]) {
285        case 64:
286            GGML_ASSERT(V->ne[0] == 64);
287            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64,  64>(ctx, dst);
288            break;
289        case 80:
290            GGML_ASSERT(V->ne[0] == 80);
291            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80,  80>(ctx, dst);
292            break;
293        case 96:
294            GGML_ASSERT(V->ne[0] == 96);
295            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96,  96>(ctx, dst);
296            break;
297        case 112:
298            GGML_ASSERT(V->ne[0] == 112);
299            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst);
300            break;
301        case 128:
302            GGML_ASSERT(V->ne[0] == 128);
303            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst);
304            break;
305        case 192: {
306            // MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
307            GGML_ASSERT(V->ne[0] == 128);
308            float max_bias = 0.0f;
309            memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
310            const bool use_gqa_opt = mask && max_bias == 0.0f;
311            GGML_ASSERT(use_gqa_opt);
312            GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
313            const int gqa_ratio = Q->ne[2] / K->ne[2];
314            if (gqa_ratio % 16 == 0) {
315                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst);
316            } else {
317                GGML_ASSERT(gqa_ratio % 8 == 0);
318                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128,  8>(ctx, dst);
319            }
320        } break;
321        case 256:
322            GGML_ASSERT(V->ne[0] == 256);
323            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst);
324            break;
325        case 320:
326            // For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build).
327            GGML_ASSERT(V->ne[0] == 256);
328            {
329                float max_bias = 0.0f;
330                memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
331
332                const bool use_gqa_opt = mask && max_bias == 0.0f;
333                GGML_ASSERT(use_gqa_opt);
334                GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
335                const int gqa_ratio = Q->ne[2] / K->ne[2];
336                GGML_ASSERT(gqa_ratio % 32 == 0);
337
338                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst);
339            }
340            break;
341        case 512:
342            GGML_ASSERT(V->ne[0] == 512);
343            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst);
344            break;
345        case 576: {
346            // For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels.
347            GGML_ASSERT(V->ne[0] == 512);
348            float max_bias = 0.0f;
349            memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
350
351            const bool use_gqa_opt = mask && max_bias == 0.0f;
352            GGML_ASSERT(use_gqa_opt);
353
354            GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
355            const int gqa_ratio = Q->ne[2] / K->ne[2];
356            if (gqa_ratio == 20) { // GLM 4.7 Flash
357                if (cc >= GGML_CUDA_CC_DGX_SPARK) {
358                    if (Q->ne[1] <= 8) {
359                        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
360                        break;
361                    }
362                    ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
363                    break;
364                }
365                if (cc >= GGML_CUDA_CC_BLACKWELL) {
366                    if (Q->ne[1] <= 4 && K->ne[1] >= 65536) {
367                        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
368                        break;
369                    }
370                    ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
371                    break;
372                }
373                if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
374                    if (Q->ne[1] <= 4) {
375                        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
376                        break;
377                    }
378                    ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
379                    break;
380                }
381                if (cc >= GGML_CUDA_CC_TURING) {
382                    if (Q->ne[1] <= 4) {
383                        if (K->ne[1] <= 16384) {
384                            ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
385                            break;
386                        }
387                        ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst);
388                        break;
389                    }
390                    ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
391                    break;
392                }
393                // Volta:
394                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
395            } else if (gqa_ratio % 16 == 0) {
396                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
397            } else {
398                ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512,  4>(ctx, dst);
399            }
400        } break;
401        default:
402            GGML_ABORT("fatal error");
403            break;
404    }
405}
406
407#define FATTN_VEC_CASE(D, type_K_case, type_V_case)                                                                                \
408    if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) {                                                                    \
409        const bool type_K_okay = type_K == GGML_TYPE_##type_K_case || (type_K == GGML_TYPE_F32 && GGML_TYPE_##type_K_case == GGML_TYPE_F16); \
410        const bool type_V_okay = type_V == GGML_TYPE_##type_V_case || (type_V == GGML_TYPE_F32 && GGML_TYPE_##type_V_case == GGML_TYPE_F16); \
411        if (head_size == (D) && type_K_okay && type_V_okay) {                                                                      \
412            return ggml_cuda_flash_attn_ext_vec_case<D, GGML_TYPE_##type_K_case, GGML_TYPE_##type_V_case>;                         \
413        }                                                                                                                          \
414    }                                                                                                                              \
415
416#define FATTN_VEC_CASES_ALL_D(type_K_case, type_V_case) \
417    FATTN_VEC_CASE( 64, type_K_case, type_V_case)       \
418    FATTN_VEC_CASE(128, type_K_case, type_V_case)       \
419    FATTN_VEC_CASE(256, type_K_case, type_V_case)       \
420
421typedef void (* fattn_vec_case_t)(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
422
423// Vector kernel for the given head size and K/V types, nullptr if its template instance was not compiled:
424static fattn_vec_case_t ggml_cuda_get_fattn_vec_case(const int64_t head_size, const ggml_type type_K, const ggml_type type_V) {
425    FATTN_VEC_CASES_ALL_D(F16,  F16)
426    FATTN_VEC_CASES_ALL_D(Q4_0, F16)
427    FATTN_VEC_CASES_ALL_D(Q4_1, F16)
428    FATTN_VEC_CASES_ALL_D(Q5_0, F16)
429    FATTN_VEC_CASES_ALL_D(Q5_1, F16)
430    FATTN_VEC_CASES_ALL_D(Q8_0, F16)
431    FATTN_VEC_CASES_ALL_D(BF16, F16)
432
433    FATTN_VEC_CASES_ALL_D(F16,  Q4_0)
434    FATTN_VEC_CASES_ALL_D(Q4_0, Q4_0)
435    FATTN_VEC_CASES_ALL_D(Q4_1, Q4_0)
436    FATTN_VEC_CASES_ALL_D(Q5_0, Q4_0)
437    FATTN_VEC_CASES_ALL_D(Q5_1, Q4_0)
438    FATTN_VEC_CASES_ALL_D(Q8_0, Q4_0)
439    FATTN_VEC_CASES_ALL_D(BF16, Q4_0)
440
441    FATTN_VEC_CASES_ALL_D(F16,  Q4_1)
442    FATTN_VEC_CASES_ALL_D(Q4_0, Q4_1)
443    FATTN_VEC_CASES_ALL_D(Q4_1, Q4_1)
444    FATTN_VEC_CASES_ALL_D(Q5_0, Q4_1)
445    FATTN_VEC_CASES_ALL_D(Q5_1, Q4_1)
446    FATTN_VEC_CASES_ALL_D(Q8_0, Q4_1)
447    FATTN_VEC_CASES_ALL_D(BF16, Q4_1)
448
449    FATTN_VEC_CASES_ALL_D(F16,  Q5_0)
450    FATTN_VEC_CASES_ALL_D(Q4_0, Q5_0)
451    FATTN_VEC_CASES_ALL_D(Q4_1, Q5_0)
452    FATTN_VEC_CASES_ALL_D(Q5_0, Q5_0)
453    FATTN_VEC_CASES_ALL_D(Q5_1, Q5_0)
454    FATTN_VEC_CASES_ALL_D(Q8_0, Q5_0)
455    FATTN_VEC_CASES_ALL_D(BF16, Q5_0)
456
457    FATTN_VEC_CASES_ALL_D(F16,  Q5_1)
458    FATTN_VEC_CASES_ALL_D(Q4_0, Q5_1)
459    FATTN_VEC_CASES_ALL_D(Q4_1, Q5_1)
460    FATTN_VEC_CASES_ALL_D(Q5_0, Q5_1)
461    FATTN_VEC_CASES_ALL_D(Q5_1, Q5_1)
462    FATTN_VEC_CASES_ALL_D(Q8_0, Q5_1)
463    FATTN_VEC_CASES_ALL_D(BF16, Q5_1)
464
465    FATTN_VEC_CASES_ALL_D(F16,  Q8_0)
466    FATTN_VEC_CASES_ALL_D(Q4_0, Q8_0)
467    FATTN_VEC_CASES_ALL_D(Q4_1, Q8_0)
468    FATTN_VEC_CASES_ALL_D(Q5_0, Q8_0)
469    FATTN_VEC_CASES_ALL_D(Q5_1, Q8_0)
470    FATTN_VEC_CASES_ALL_D(Q8_0, Q8_0)
471    FATTN_VEC_CASES_ALL_D(BF16, Q8_0)
472
473    FATTN_VEC_CASES_ALL_D(F16,  BF16)
474    FATTN_VEC_CASES_ALL_D(Q4_0, BF16)
475    FATTN_VEC_CASES_ALL_D(Q4_1, BF16)
476    FATTN_VEC_CASES_ALL_D(Q5_0, BF16)
477    FATTN_VEC_CASES_ALL_D(Q5_1, BF16)
478    FATTN_VEC_CASES_ALL_D(Q8_0, BF16)
479    FATTN_VEC_CASES_ALL_D(BF16, BF16)
480
481    return nullptr;
482}
483
484static void ggml_cuda_flash_attn_ext_vec(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
485    const ggml_tensor * Q = dst->src[0];
486    const ggml_tensor * K = dst->src[1];
487    const ggml_tensor * V = dst->src[2];
488
489    fattn_vec_case_t vec_case = ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type);
490    if (vec_case == nullptr) {
491        static bool warned = false;
492        if (!warned) {
493            GGML_LOG_WARN("%s: no FlashAttention vector kernel compiled for K/V types %s-%s, converting K and V to f16 instead (slow). "
494                "Add \"%s-%s\" to GGML_CUDA_FA_QUANTS to compile it.\n",
495                __func__, ggml_type_name(K->type), ggml_type_name(V->type), ggml_type_name(K->type), ggml_type_name(V->type));
496            warned = true;
497        }
498        vec_case = ggml_cuda_get_fattn_vec_case(Q->ne[0], GGML_TYPE_F16, GGML_TYPE_F16);
499    }
500    GGML_ASSERT(vec_case != nullptr);
501    vec_case(ctx, dst);
502}
503
504// Best FlashAttention kernel for a specific GPU:
505enum best_fattn_kernel {
506    BEST_FATTN_KERNEL_NONE    =   0,
507    BEST_FATTN_KERNEL_TILE    = 200,
508    BEST_FATTN_KERNEL_VEC     = 100,
509    BEST_FATTN_KERNEL_MMA_F16 = 400,
510};
511
512// K/V types for which there is a vector kernel template instance, other kernels convert these to f16:
513static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) {
514    switch (type) {
515        case GGML_TYPE_F32:
516        case GGML_TYPE_F16:
517        case GGML_TYPE_BF16:
518        case GGML_TYPE_Q4_0:
519        case GGML_TYPE_Q4_1:
520        case GGML_TYPE_Q5_0:
521        case GGML_TYPE_Q5_1:
522        case GGML_TYPE_Q8_0:
523            return true;
524        default:
525            return false;
526    }
527}
528
529static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) {
530#ifndef FLASH_ATTN_AVAILABLE
531    GGML_UNUSED(device); GGML_UNUSED(dst);
532    return BEST_FATTN_KERNEL_NONE;
533#endif// FLASH_ATTN_AVAILABLE
534
535    const ggml_tensor * KQV   = dst;
536    const ggml_tensor * Q     = dst->src[0];
537    const ggml_tensor * K     = dst->src[1];
538    const ggml_tensor * V     = dst->src[2];
539    const ggml_tensor * mask  = dst->src[3];
540
541    const int gqa_ratio = Q->ne[2] / K->ne[2];
542    GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
543
544    float max_bias = 0.0f;
545    memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
546
547    // The effective batch size for the kernel can be increased by gqa_ratio.
548    // The kernel versions without this optimization are also used for ALiBi, if there is no mask, or if the KV cache is not padded,
549    bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0;
550    for (const ggml_tensor * t : {Q, K, V, mask}) {
551        if (t == nullptr || ggml_is_quantized(t->type)) {
552            continue;
553        }
554        for (size_t i = 1; i < GGML_MAX_DIMS; ++i) {
555            if (t->nb[i] % 16 != 0) {
556                gqa_opt_applies = false;
557                break;
558            }
559        }
560    }
561
562    const int cc = ggml_cuda_info().devices[device].cc;
563
564    switch (K->ne[0]) {
565        case  40:
566        case  64:
567        case  72:
568        case  80:
569        case  96:
570        case 128:
571        case 112:
572        case 256:
573            if (V->ne[0] != K->ne[0]) {
574                return BEST_FATTN_KERNEL_NONE;
575            }
576            break;
577        case 192:
578            if (V->ne[0] != 128 || !gqa_opt_applies) {
579                return BEST_FATTN_KERNEL_NONE;
580            }
581            if (gqa_ratio % 8 != 0) {
582                return BEST_FATTN_KERNEL_NONE;
583            }
584            break;
585        case 320:
586            if (V->ne[0] != 256 || !gqa_opt_applies) {
587                return BEST_FATTN_KERNEL_NONE;
588            }
589            if (gqa_ratio % 32 != 0) {
590                return BEST_FATTN_KERNEL_NONE;
591            }
592            break;
593        case 512:
594            if (V->ne[0] != K->ne[0]) {
595                return BEST_FATTN_KERNEL_NONE;
596            }
597            if (!gqa_opt_applies) {
598                return BEST_FATTN_KERNEL_NONE;
599            }
600            break;
601        case 576:
602            if (V->ne[0] != 512) {
603                return BEST_FATTN_KERNEL_NONE;
604            }
605            if (!gqa_opt_applies) {
606                return BEST_FATTN_KERNEL_NONE;
607            }
608            break;
609        default:
610            return BEST_FATTN_KERNEL_NONE;
611    }
612
613    if (!ggml_cuda_fattn_kv_type_supported(K->type) || !ggml_cuda_fattn_kv_type_supported(V->type)) {
614        return BEST_FATTN_KERNEL_NONE;
615    }
616
617    if (mask && mask->ne[2] != 1) {
618        return BEST_FATTN_KERNEL_NONE;
619    }
620
621    // For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes:
622    // 192 satisfies % 64 == 0 but has no vec instance (DKQ != DV); force it onto the MMA path.
623    const bool can_use_vector_kernel = Q->ne[0] <= 256 && Q->ne[0] % 64 == 0 && Q->ne[0] != 192 && K->ne[1] % FATTN_KQ_STRIDE == 0;
624
625    // If Turing tensor cores are available, use them:
626    if (turing_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
627        if (can_use_vector_kernel) {
628            if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
629                // the sparse gather exists only in the MMA kernel: (DKQ, DV, 1, 8) with GQA > 4
630                const bool sparse_decode = gqa_opt_applies && gqa_ratio > 4 &&
631                    ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(K->ne[0], V->ne[0], 1, 8) &&
632                    ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1);
633                if (cc >= GGML_CUDA_CC_ADA_LOVELACE && Q->ne[1] == 1 && Q->ne[3] == 1 && !(gqa_ratio > 4 && K->ne[1] >= 8192) && !sparse_decode) {
634                    return BEST_FATTN_KERNEL_VEC;
635                }
636            } else {
637                if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
638                    if (Q->ne[1] <= 2) {
639                        return BEST_FATTN_KERNEL_VEC;
640                    }
641                } else {
642                    if (Q->ne[1] == 1) {
643                        return BEST_FATTN_KERNEL_VEC;
644                    }
645                }
646            }
647            if (!gqa_opt_applies && Q->ne[1] == 1) {
648                return BEST_FATTN_KERNEL_VEC;
649            }
650        }
651        return BEST_FATTN_KERNEL_MMA_F16;
652    }
653
654    const int ncols2_max = Q->ne[0] == 320 ? 32 : ((Q->ne[0] == 576 || Q->ne[0] == 192) ? 16 : 8);
655    int gqa_ratio_eff = 1;
656    while (gqa_ratio % (2*gqa_ratio_eff) == 0 && gqa_ratio_eff < ncols2_max) {
657        gqa_ratio_eff *= 2;
658    }
659
660    if (volta_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
661        if (can_use_vector_kernel && Q->ne[1] * gqa_ratio_eff <= 2) {
662            return BEST_FATTN_KERNEL_VEC;
663        }
664        if (Q->ne[1] * gqa_ratio_eff <= 16) {
665            return BEST_FATTN_KERNEL_TILE; // On Volta tensor cores are only faster for sufficiently large matrices.
666        }
667        return BEST_FATTN_KERNEL_MMA_F16;
668    }
669
670    // AMD MFMA needs a certain minimum batch size to outscale the tile kernel for large head sizes.
671    if ((amd_mfma_available(cc) && Q->ne[0] <= 256) && Q->ne[0] != 40 && Q->ne[0] != 72) {
672        if ((Q->ne[0] <= 64 && Q->ne[1] * gqa_ratio_eff > 8)) {
673            return BEST_FATTN_KERNEL_MMA_F16;
674        }
675        if ((Q->ne[0] <= 128 && Q->ne[1] * gqa_ratio_eff > 16)) {
676            return BEST_FATTN_KERNEL_MMA_F16;
677        }
678        if ((Q->ne[0] <= 256 && Q->ne[1] * gqa_ratio_eff > 64)) {
679            return BEST_FATTN_KERNEL_MMA_F16;
680        }
681    }
682
683    // AMD WMMA is faster than the tile kernel if the wide tiles with high arithmetic intensity can be utilized.
684    if ((amd_wmma_available(cc) && gqa_opt_applies && Q->ne[0] <= 256) && Q->ne[0] != 40 && Q->ne[0] != 72 &&
685            Q->ne[1] * gqa_ratio_eff > (Q->ne[0] <= 128 ? 8 : 16)) {
686        return BEST_FATTN_KERNEL_MMA_F16;
687    }
688
689    // If there are no tensor cores available, use the generic tile kernel:
690    if (can_use_vector_kernel) {
691        if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
692            if (Q->ne[1] == 1) {
693                if (!gqa_opt_applies) {
694                    return BEST_FATTN_KERNEL_VEC;
695                }
696            }
697        } else {
698            if (Q->ne[1] <= 2) {
699                return BEST_FATTN_KERNEL_VEC;
700            }
701        }
702    }
703    return BEST_FATTN_KERNEL_TILE;
704}
705
706size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) {
707    GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT);
708
709    const ggml_tensor * Q = dst->src[0];
710    const ggml_tensor * K = dst->src[1];
711    const ggml_tensor * V = dst->src[2];
712
713    GGML_ASSERT(K != nullptr);
714    GGML_ASSERT(V != nullptr);
715
716    const best_fattn_kernel kernel = ggml_cuda_get_best_fattn_kernel(device, dst);
717
718    bool need_f16_K = false;
719    bool need_f16_V = false;
720
721    switch (kernel) {
722        case BEST_FATTN_KERNEL_TILE:
723        case BEST_FATTN_KERNEL_MMA_F16:
724            need_f16_K = true;
725            need_f16_V = true;
726            break;
727        case BEST_FATTN_KERNEL_VEC: {
728            const bool f16_fallback = ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) == nullptr;
729            need_f16_K = K->type == GGML_TYPE_F32 || f16_fallback;
730            need_f16_V = V->type == GGML_TYPE_F32 || f16_fallback;
731        } break;
732        case BEST_FATTN_KERNEL_NONE:
733            break;
734    }
735
736    const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra =
737        ggml_cuda_flash_attn_ext_get_f16_extra_data(dst, need_f16_K, need_f16_V);
738
739    return f16_extra.end - (uintptr_t) dst->data;
740}
741
742void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
743    ggml_cuda_set_device(ctx.device);
744    switch (ggml_cuda_get_best_fattn_kernel(ggml_cuda_get_device(), dst)) {
745        case BEST_FATTN_KERNEL_NONE:
746            GGML_ABORT("fatal error");
747        case BEST_FATTN_KERNEL_TILE:
748            ggml_cuda_flash_attn_ext_tile(ctx, dst);
749            break;
750        case BEST_FATTN_KERNEL_VEC:
751            ggml_cuda_flash_attn_ext_vec(ctx, dst);
752            break;
753        case BEST_FATTN_KERNEL_MMA_F16:
754            ggml_cuda_flash_attn_ext_mma_f16(ctx, dst);
755            break;
756    }
757}
758
759bool ggml_cuda_flash_attn_ext_supported(int device, const ggml_tensor * dst) {
760    return ggml_cuda_get_best_fattn_kernel(device, dst) != BEST_FATTN_KERNEL_NONE;
761}