interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-cuda / fattn.cu

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