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-common.cuh

1327 lines · 50176 bytes Raw Blame History
1#pragma once
2
3#include "common.cuh"
4#include "convert.cuh"
5#include "vecdotq.cuh"
6
7#include <cstdint>
8
9#define FATTN_KQ_STRIDE 256
10#define HALF_MAX_HALF __float2half(65504.0f/2) // Use neg. of this instead of -INFINITY to initialize KQ max vals to avoid NaN upon subtraction.
11#define SOFTMAX_FTZ_THRESHOLD -20.0f // Softmax exp. of values smaller than this are flushed to zero to avoid NaNs.
12
13// log(2) = 0.6931, by adding this to the KQ maximum used for the softmax the numerical range representable
14// by the VKQ accumulators is effectively being shifted up by a factor of 2.
15// This reduces issues with numerical overflow but also causes larger values to be flushed to zero.
16// However, as the output from FlashAttention will usually be used as an input for a matrix multiplication this should be negligible.
17// Still, the value range should be shifted as much as necessary but as little as possible.
18// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
19#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
20
21typedef void (* fattn_kernel_t)(
22 const char * __restrict__ Q,
23 const char * __restrict__ K,
24 const char * __restrict__ V,
25 const char * __restrict__ mask,
26 const char * __restrict__ sinks,
27 const int * __restrict__ KV_max,
28 const int * __restrict__ KV_rows,
29 float * __restrict__ dst,
30 float2 * __restrict__ dst_meta,
31 const float scale,
32 const float max_bias,
33 const float m0,
34 const float m1,
35 const uint32_t n_head_log2,
36 const float logit_softcap,
37 const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
38 const int32_t nb01, const int32_t nb02, const int32_t nb03,
39 const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
40 const int32_t nb11, const int32_t nb12, const int64_t nb13,
41 const int32_t nb21, const int32_t nb22, const int64_t nb23,
42 const int32_t ne31, const int32_t ne32, const int32_t ne33,
43 const int32_t nb31, const int32_t nb32, const int64_t nb33);
44
45typedef float (*vec_dot_KQ_t)(
46 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds);
47
48struct ggml_cuda_flash_attn_ext_f16_extra_data {
49 uintptr_t K;
50 uintptr_t V;
51 uintptr_t end;
52};
53
54static inline ggml_cuda_flash_attn_ext_f16_extra_data ggml_cuda_flash_attn_ext_get_f16_extra_data(
55 const ggml_tensor * dst, const bool need_f16_K, const bool need_f16_V) {
56 GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT);
57
58 const ggml_tensor * K = dst->src[1];
59 const ggml_tensor * V = dst->src[2];
60
61 GGML_ASSERT(K != nullptr);
62 GGML_ASSERT(V != nullptr);
63
64 const bool V_is_K_view = V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs));
65
66 ggml_cuda_flash_attn_ext_f16_extra_data data = {};
67 data.end = (uintptr_t) dst->data + ggml_nbytes(dst);
68
69 if (need_f16_K && K->type != GGML_TYPE_F16) {
70 data.end = GGML_PAD(data.end, 128);
71 data.K = data.end;
72 data.end += ggml_nelements(K)*ggml_type_size(GGML_TYPE_F16);
73 }
74
75 if (need_f16_V && V->type != GGML_TYPE_F16) {
76 if (V_is_K_view) {
77 data.V = data.K;
78 } else {
79 data.end = GGML_PAD(data.end, 128);
80 data.V = data.end;
81 data.end += ggml_nelements(V)*ggml_type_size(GGML_TYPE_F16);
82 }
83 }
84
85 return data;
86}
87
88template <int D, int nthreads>
89static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_f16(
90 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds_v) {
91
92 const half2 * K_h2 = (const half2 *) K_c;
93 GGML_UNUSED(Q_q8);
94 GGML_UNUSED(Q_ds_v);
95
96 constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
97 constexpr int cpy_ne = cpy_nb / 4;
98
99 float sum = 0.0f;
100
101#pragma unroll
102 for (int k_KQ_0 = 0; k_KQ_0 < D/2; k_KQ_0 += nthreads*cpy_ne) {
103 __align__(16) half2 tmp[cpy_ne];
104 ggml_cuda_memcpy_1<sizeof(tmp)>(tmp, K_h2 + k_KQ_0 + (threadIdx.x % nthreads)*cpy_ne);
105#pragma unroll
106 for (int k_KQ_1 = 0; k_KQ_1 < cpy_ne; ++k_KQ_1) {
107#ifdef V_DOT2_F32_F16_AVAILABLE
108 ggml_cuda_mad(sum, tmp[k_KQ_1] , ((const half2 *) Q_v)[k_KQ_0/nthreads + k_KQ_1]);
109#else
110 ggml_cuda_mad(sum, __half22float2(tmp[k_KQ_1]), ((const float2 *) Q_v)[k_KQ_0/nthreads + k_KQ_1]);
111#endif // V_DOT2_F32_F16_AVAILABLE
112 }
113 }
114
115 return sum;
116}
117
118template <int D, int nthreads>
119static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_bf16(
120 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds_v) {
121
122 const nv_bfloat162 * K_bf16 = (const nv_bfloat162 *) K_c;
123 GGML_UNUSED(Q_q8);
124 GGML_UNUSED(Q_ds_v);
125
126 constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
127 constexpr int cpy_ne = cpy_nb / 4;
128
129 float sum = 0.0f;
130
131#pragma unroll
132 for (int k_KQ_0 = 0; k_KQ_0 < D/2; k_KQ_0 += nthreads*cpy_ne) {
133 __align__(16) nv_bfloat162 tmp[cpy_ne];
134 ggml_cuda_memcpy_1<sizeof(tmp)>(tmp, K_bf16 + k_KQ_0 + (threadIdx.x % nthreads)*cpy_ne);
135#pragma unroll
136 for (int k_KQ_1 = 0; k_KQ_1 < cpy_ne; ++k_KQ_1) {
137#ifdef V_DOT2_F32_F16_AVAILABLE
138 // FIXME replace macros in vector FA kernel with templating and use FP32 for BF16
139 ggml_cuda_mad(sum, ggml_cuda_cast<float2>(tmp[k_KQ_1]), __half22float2(((const half2 *) Q_v)[k_KQ_0/nthreads + k_KQ_1]));
140#else
141 ggml_cuda_mad(sum, ggml_cuda_cast<float2>(tmp[k_KQ_1]), ((const float2 *) Q_v)[k_KQ_0/nthreads + k_KQ_1]);
142#endif // V_DOT2_F32_F16_AVAILABLE
143 }
144 }
145
146 return sum;
147}
148
149template<int D, int nthreads>
150static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_q4_0(
151 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8, const void * __restrict__ Q_ds_v) {
152
153 const block_q4_0 * K_q4_0 = (const block_q4_0 *) K_c;
154 GGML_UNUSED(Q_v);
155
156 float sum = 0.0f;
157
158#pragma unroll
159 for (int k_KQ_0 = 0; k_KQ_0 < int(D/sizeof(int)); k_KQ_0 += nthreads) {
160 const int k_KQ = k_KQ_0 + (nthreads == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads);
161
162 const int ib = k_KQ / QI8_1;
163 const int iqs4 = k_KQ % QI4_0;
164 const int shift = k_KQ & (QI8_1/2);
165
166 int v;
167 ggml_cuda_memcpy_1<sizeof(int), 2>(&v, K_q4_0[ib].qs + sizeof(int)*iqs4);
168 v = (v >> shift) & 0x0F0F0F0F;
169 const int u = Q_q8[k_KQ_0/nthreads];
170
171 const int sumi = ggml_cuda_dp4a(v, u, 0);
172
173 const float2 Q_ds = ((const float2 *) Q_ds_v)[k_KQ_0/nthreads];
174 sum += __half2float(K_q4_0[ib].d) * (sumi*Q_ds.x - (8/QI8_1)*Q_ds.y);
175 }
176
177 return sum;
178}
179
180template<int D, int nthreads>
181static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_q4_1(
182 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8, const void * __restrict__ Q_ds_v) {
183
184 const block_q4_1 * K_q4_1 = (const block_q4_1 *) K_c;
185 GGML_UNUSED(Q_v);
186
187 float sum = 0.0f;
188
189#pragma unroll
190 for (int k_KQ_0 = 0; k_KQ_0 < int(D/sizeof(int)); k_KQ_0 += nthreads) {
191 const int k_KQ = k_KQ_0 + (nthreads == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads);
192
193 const int ib = k_KQ / QI8_1;
194 const int iqs4 = k_KQ % QI4_1;
195 const int shift = k_KQ & (QI8_1/2);
196
197 int v;
198 ggml_cuda_memcpy_1<sizeof(int)>(&v, K_q4_1[ib].qs + sizeof(int)*iqs4);
199 v = (v >> shift) & 0x0F0F0F0F;
200 const int u = Q_q8[k_KQ_0/nthreads];
201
202 const int sumi = ggml_cuda_dp4a(v, u, 0);
203
204 const float2 K_dm = __half22float2(K_q4_1[ib].dm);
205 const float2 Q_ds = ((const float2 *) Q_ds_v)[k_KQ_0/nthreads];
206
207 sum += K_dm.x*Q_ds.x*sumi + K_dm.y*Q_ds.y/QI8_1;
208 }
209
210 return sum;
211}
212
213template<int D, int nthreads>
214static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_q5_0(
215 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8, const void * __restrict__ Q_ds_v) {
216
217 const block_q5_0 * K_q5_0 = (const block_q5_0 *) K_c;
218 GGML_UNUSED(Q_v);
219
220 float sum = 0.0f;
221
222#pragma unroll
223 for (int k_KQ_0 = 0; k_KQ_0 < int(D/sizeof(int)); k_KQ_0 += nthreads) {
224 const int k_KQ = k_KQ_0 + (nthreads == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads);
225
226 const int ib = k_KQ / QI8_1;
227 const int iqs4 = k_KQ % QI5_0;
228 const int iqs8 = k_KQ % QI8_1;
229 const int shift = k_KQ & (QI8_1/2);
230
231 int v;
232 ggml_cuda_memcpy_1<sizeof(int), 2>(&v, K_q5_0[ib].qs + sizeof(int)*iqs4);
233 v = (v >> shift) & 0x0F0F0F0F;
234
235 {
236 int vh;
237 ggml_cuda_memcpy_1<sizeof(int), 2>(&vh, K_q5_0[ib].qh);
238 vh >>= iqs8 * QI5_0;
239
240 v |= (vh << 4) & 0x00000010; // 0 -> 4
241 v |= (vh << 11) & 0x00001000; // 1 -> 12
242 v |= (vh << 18) & 0x00100000; // 2 -> 20
243 v |= (vh << 25) & 0x10000000; // 3 -> 28
244 }
245
246 const int u = Q_q8[k_KQ_0/nthreads];
247
248 const int sumi = ggml_cuda_dp4a(v, u, 0);
249
250 const float2 Q_ds = ((const float2 *) Q_ds_v)[k_KQ_0/nthreads];
251
252 sum += __half2float(K_q5_0[ib].d) * (sumi*Q_ds.x - (16/QI8_1)*Q_ds.y);
253 }
254
255 return sum;
256}
257
258template<int D, int nthreads>
259static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_q5_1(
260 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8, const void * __restrict__ Q_ds_v) {
261
262 const block_q5_1 * K_q5_1 = (const block_q5_1 *) K_c;
263 GGML_UNUSED(Q_v);
264
265 float sum = 0.0f;
266
267#pragma unroll
268 for (int k_KQ_0 = 0; k_KQ_0 < int(D/sizeof(int)); k_KQ_0 += nthreads) {
269 const int k_KQ = k_KQ_0 + (nthreads == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads);
270
271 const int ib = k_KQ / QI8_1;
272 const int iqs4 = k_KQ % QI5_1;
273 const int iqs8 = k_KQ % QI8_1;
274 const int shift = k_KQ & (QI8_1/2);
275
276 int v;
277 ggml_cuda_memcpy_1<sizeof(int)>(&v, K_q5_1[ib].qs + sizeof(int)*iqs4);
278 v = (v >> shift) & 0x0F0F0F0F;
279
280 {
281 int vh;
282 ggml_cuda_memcpy_1<sizeof(int)>(&vh, K_q5_1[ib].qh);
283 vh >>= iqs8 * QI5_0;
284
285 v |= (vh << 4) & 0x00000010; // 0 -> 4
286 v |= (vh << 11) & 0x00001000; // 1 -> 12
287 v |= (vh << 18) & 0x00100000; // 2 -> 20
288 v |= (vh << 25) & 0x10000000; // 3 -> 28
289 }
290
291 const int u = Q_q8[k_KQ_0/nthreads];
292
293 const int sumi = ggml_cuda_dp4a(v, u, 0);
294
295 const float2 K_dm = __half22float2(K_q5_1[ib].dm);
296 const float2 Q_ds = ((const float2 *) Q_ds_v)[k_KQ_0/nthreads];
297
298 sum += K_dm.x*Q_ds.x*sumi + K_dm.y*Q_ds.y/QI8_1;
299 }
300
301 return sum;
302}
303
304template <int D, int nthreads>
305static __device__ __forceinline__ float vec_dot_fattn_vec_KQ_q8_0(
306 const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8, const void * __restrict__ Q_ds_v) {
307
308 const block_q8_0 * K_q8_0 = (const block_q8_0 *) K_c;
309 GGML_UNUSED(Q_v);
310
311 float sum = 0.0f;
312
313#pragma unroll
314 for (int k_KQ_0 = 0; k_KQ_0 < int(D/sizeof(int)); k_KQ_0 += nthreads) {
315 const int k_KQ = k_KQ_0 + (nthreads == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads);
316
317 const int ib = k_KQ / QI8_0;
318 const int iqs = k_KQ % QI8_0;
319
320 int v;
321 ggml_cuda_memcpy_1<sizeof(v), 2>(&v, K_q8_0[ib].qs + 4*iqs);
322
323 const float2 * Q_ds = (const float2 *) Q_ds_v;
324 const float Q_d = Q_ds[k_KQ_0/nthreads].x;
325
326 sum += vec_dot_q8_0_q8_1_impl<float, 1>(&v, &Q_q8[k_KQ_0/nthreads], K_q8_0[ib].d, Q_d);
327 }
328
329 return sum;
330}
331
332template <typename Tds, int ni>
333static __device__ __forceinline__ void quantize_q8_1_to_shared(
334 const float * __restrict__ x, const float scale, int * __restrict__ yq32, void * __restrict__ yds) {
335
336 float vals[sizeof(int)] = {0.0f};
337#pragma unroll
338 for (int l = 0; l < int(sizeof(int)); ++l) {
339 vals[l] = (ni == WARP_SIZE || threadIdx.x < ni) ? scale * x[4*threadIdx.x + l] : 0.0f;
340 }
341
342 float amax = fabsf(vals[0]);
343 float sum = vals[0];
344#pragma unroll
345 for (int l = 1; l < int(sizeof(int)); ++l) {
346 amax = fmaxf(amax, fabsf(vals[l]));
347 sum += vals[l];
348 }
349#pragma unroll
350 for (int mask = QI8_1/2; mask > 0; mask >>= 1) {
351 amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, mask, 32));
352 sum += __shfl_xor_sync(0xFFFFFFFF, sum, mask, 32);
353 }
354
355 const float d = amax / 127;
356 int q32 = 0;
357 int8_t * q8 = (int8_t *) &q32;
358
359 if (d != 0.0f) {
360#pragma unroll
361 for (int l = 0; l < int(sizeof(int)); ++l) {
362 q8[l] = roundf(vals[l] / d);
363 }
364 }
365
366 yq32[threadIdx.x] = q32;
367 if (threadIdx.x % QI8_1 == 0 && (ni == WARP_SIZE || threadIdx.x < ni)) {
368 if (std::is_same<Tds, half2>::value) {
369 ((half2 *) yds)[threadIdx.x/QI8_1] = make_half2(d, sum);
370 } else {
371 ((float2 *) yds)[threadIdx.x/QI8_1] = make_float2(d, sum);
372 }
373 }
374}
375
376typedef void (*dequantize_V_t)(const void *, void *, const int64_t);
377
378template <typename T, int ne>
379static __device__ __forceinline__ void dequantize_V_f16(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
380 if constexpr (std::is_same_v<T, half>) {
381 ggml_cuda_memcpy_1<ne*sizeof(half)>(dst, (const half *) vx + i0);
382 } else if constexpr (std::is_same_v<T, float>) {
383 static_assert(ne % 2 == 0, "bad ne");
384 __align__(16) half2 tmp[ne/2];
385 ggml_cuda_memcpy_1<ne*sizeof(half)>(tmp, (const half *) vx + i0);
386 float2 * dst_f2 = (float2 *) dst;
387#pragma unroll
388 for (int l = 0; l < ne/2; ++l) {
389 dst_f2[l] = __half22float2(tmp[l]);
390 }
391 } else {
392 static_assert(std::is_same_v<T, void>, "unsupported type");
393 }
394}
395
396template <typename T, int ne>
397static __device__ __forceinline__ void dequantize_V_bf16(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
398 static_assert(std::is_same_v<T, float>, "BF16 V dequantization only supports float output");
399 static_assert(ne % 2 == 0, "bad ne");
400 __align__(16) nv_bfloat162 tmp[ne/2];
401 ggml_cuda_memcpy_1<ne*sizeof(nv_bfloat16)>(tmp, (const nv_bfloat16 *) vx + i0);
402 float2 * dst_f2 = (float2 *) dst;
403#pragma unroll
404 for (int l = 0; l < ne/2; ++l) {
405 dst_f2[l] = ggml_cuda_cast<float2>(tmp[l]);
406 }
407}
408
409template <typename T, int ne>
410static __device__ __forceinline__ void dequantize_V_q4_0(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
411 const block_q4_0 * x = (const block_q4_0 *) vx;
412
413 const int64_t ib = i0 / QK4_0;
414 const int iqs = i0 % (QK4_0/2);
415 const int shift = (i0 % QK4_0) / (QK4_0/2);
416
417 int q;
418 static_assert(ne == 2 || ne == 4, "bad ne");
419 ggml_cuda_memcpy_1<ne, 2>(&q, x[ib].qs + iqs);
420#if defined(GGML_USE_HIP)
421 // Keep this VMEM read close to its packed-byte dequantization. Hoisting it too far
422 // increases VGPR pressure substantially in some FlashAttention vector kernels.
423 __builtin_amdgcn_sched_group_barrier(0x20, 1, 0);
424#endif // defined(GGML_USE_HIP)
425 q >>= 4*shift;
426 q &= 0x0F0F0F0F;
427 q = __vsub4(q, 0x08080808);
428
429 const int8_t * q8 = (const int8_t *) &q;
430
431#ifdef FP16_AVAILABLE
432 if constexpr (std::is_same_v<T, half>) {
433 const half2 d = __half2half2(x[ib].d);
434
435#pragma unroll
436 for (int l0 = 0; l0 < ne; l0 += 2) {
437 ((half2 *) dst)[l0/2] = d * make_half2(q8[l0 + 0], q8[l0 + 1]);
438 }
439 } else
440#endif // FP16_AVAILABLE
441 if constexpr (std::is_same_v<T, float>) {
442 const float d = x[ib].d;
443
444#pragma unroll
445 for (int l = 0; l < ne; ++l) {
446 ((float *) dst)[l] = d * q8[l];
447 }
448 } else {
449 static_assert(std::is_same_v<T, void>, "bad type");
450 }
451}
452
453template <typename T, int ne>
454static __device__ __forceinline__ void dequantize_V_q4_1(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
455 const block_q4_1 * x = (const block_q4_1 *) vx;
456
457 const int64_t ib = i0 / QK4_1;
458 const int iqs = i0 % (QK4_1/2);
459 const int shift = (i0 % QK4_1) / (QK4_1/2);
460
461 int q;
462 static_assert(ne == 2 || ne == 4, "bad ne");
463 ggml_cuda_memcpy_1<ne>(&q, x[ib].qs + iqs);
464 q >>= 4*shift;
465 q &= 0x0F0F0F0F;
466
467 const int8_t * q8 = (const int8_t *) &q;
468
469#ifdef FP16_AVAILABLE
470 if constexpr (std::is_same_v<T, half>) {
471 const half2 dm = x[ib].dm;
472 const half2 d = __half2half2( __low2half(dm));
473 const half2 m = __half2half2(__high2half(dm));
474
475#pragma unroll
476 for (int l0 = 0; l0 < ne; l0 += 2) {
477 ((half2 *) dst)[l0/2] = d * make_half2(q8[l0 + 0], q8[l0 + 1]) + m;
478 }
479 } else
480#endif // FP16_AVAILABLE
481 if constexpr (std::is_same_v<T, float>) {
482 const float2 dm = __half22float2(x[ib].dm);
483
484#pragma unroll
485 for (int l = 0; l < ne; ++l) {
486 ((float *) dst)[l] = dm.x * q8[l] + dm.y;
487 }
488 } else {
489 static_assert(std::is_same_v<T, void>, "bad type");
490 }
491}
492
493template <typename T, int ne>
494static __device__ __forceinline__ void dequantize_V_q5_0(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
495 const block_q5_0 * x = (const block_q5_0 *) vx;
496
497 const int64_t ib = i0 / QK5_0;
498 const int idq = i0 % QK5_0;
499 const int iqs = i0 % (QK5_0/2);
500 const int shift = (i0 % QK5_0) / (QK5_0/2);
501
502 int q;
503 static_assert(ne == 2 || ne == 4, "bad ne");
504 ggml_cuda_memcpy_1<ne, 2>(&q, x[ib].qs + iqs);
505 q >>= 4*shift;
506 q &= 0x0F0F0F0F;
507
508 {
509 int qh;
510 ggml_cuda_memcpy_1<ne, 2>(&qh, x[ib].qh);
511#pragma unroll
512 for (int l = 0; l < ne; ++l) {
513 q |= ((qh >> (idq + l)) & 0x00000001) << (8*l + 4);
514 }
515 }
516
517 q = __vsub4(q, 0x10101010);
518
519 const int8_t * q8 = (const int8_t *) &q;
520
521#ifdef FP16_AVAILABLE
522 if constexpr (std::is_same_v<T, half>) {
523 const half2 d = __half2half2(x[ib].d);
524
525#pragma unroll
526 for (int l0 = 0; l0 < ne; l0 += 2) {
527 ((half2 *) dst)[l0/2] = d * make_half2(q8[l0 + 0], q8[l0 + 1]);
528 }
529 } else
530#endif // FP16_AVAILABLE
531 if constexpr (std::is_same_v<T, float>) {
532 const float d = x[ib].d;
533
534#pragma unroll
535 for (int l = 0; l < ne; ++l) {
536 ((float *) dst)[l] = d * q8[l];
537 }
538 } else {
539 static_assert(std::is_same_v<T, void>, "bad type");
540 }
541}
542
543template <typename T, int ne>
544static __device__ __forceinline__ void dequantize_V_q5_1(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
545 const block_q5_1 * x = (const block_q5_1 *) vx;
546
547 const int64_t ib = i0 / QK5_1;
548 const int idq = i0 % QK5_1;
549 const int iqs = i0 % (QK5_1/2);
550 const int shift = (i0 % QK5_1) / (QK5_1/2);
551
552 int q;
553 static_assert(ne == 2 || ne == 4, "bad ne");
554 ggml_cuda_memcpy_1<ne>(&q, x[ib].qs + iqs);
555 q >>= 4*shift;
556 q &= 0x0F0F0F0F;
557
558 {
559 int qh;
560 ggml_cuda_memcpy_1<ne>(&qh, x[ib].qh);
561#pragma unroll
562 for (int l = 0; l < ne; ++l) {
563 q |= ((qh >> (idq + l)) & 0x00000001) << (8*l + 4);
564 }
565 }
566
567 const int8_t * q8 = (const int8_t *) &q;
568
569#ifdef FP16_AVAILABLE
570 if constexpr (std::is_same_v<T, half>) {
571 const half2 dm = x[ib].dm;
572 const half2 d = __half2half2( __low2half(dm));
573 const half2 m = __half2half2(__high2half(dm));
574
575#pragma unroll
576 for (int l0 = 0; l0 < ne; l0 += 2) {
577 ((half2 *) dst)[l0/2] = d * make_half2(q8[l0 + 0], q8[l0 + 1]) + m;
578 }
579 } else
580#endif // FP16_AVAILABLE
581 if constexpr (std::is_same_v<T, float>) {
582 const float2 dm = __half22float2(x[ib].dm);
583
584#pragma unroll
585 for (int l = 0; l < ne; ++l) {
586 ((float *) dst)[l] = dm.x * q8[l] + dm.y;
587 }
588 } else {
589 static_assert(std::is_same_v<T, void>, "bad type");
590 }
591}
592
593template <typename T, int ne>
594static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict__ vx, void * __restrict__ dst, const int64_t i0) {
595 const block_q8_0 * x = (const block_q8_0 *) vx;
596
597 const int64_t ib = i0 / QK8_0;
598 const int iqs = i0 % QK8_0;
599
600 static_assert(ne % 2 == 0, "bad ne");
601 int8_t qs[ne];
602 ggml_cuda_memcpy_1<ne, 2>(qs, x[ib].qs + iqs);
603
604#ifdef FP16_AVAILABLE
605 if constexpr (std::is_same<T, half>::value) {
606 const half2 d = __half2half2(x[ib].d);
607
608#pragma unroll
609 for (int l0 = 0; l0 < ne; l0 += 2) {
610 ((half2 *) dst)[l0/2] = d * make_half2(qs[l0 + 0], qs[l0 + 1]);
611 }
612 } else
613#endif // FP16_AVAILABLE
614 if constexpr (std::is_same<T, float>::value) {
615 const float d = x[ib].d;
616
617#pragma unroll
618 for (int l = 0; l < ne; ++l) {
619 ((float *) dst)[l] = d * qs[l];
620 }
621 } else {
622 static_assert(std::is_same_v<T, void>, "unsupported type");
623 }
624}
625
626template <ggml_type type_K, int D, int nthreads>
627constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() {
628 if constexpr (type_K == GGML_TYPE_F16) {
629 return vec_dot_fattn_vec_KQ_f16<D, nthreads>;
630 } else if constexpr (type_K == GGML_TYPE_Q4_0) {
631 return vec_dot_fattn_vec_KQ_q4_0<D, nthreads>;
632 } else if constexpr (type_K == GGML_TYPE_Q4_1) {
633 return vec_dot_fattn_vec_KQ_q4_1<D, nthreads>;
634 } else if constexpr (type_K == GGML_TYPE_Q5_0) {
635 return vec_dot_fattn_vec_KQ_q5_0<D, nthreads>;
636 } else if constexpr (type_K == GGML_TYPE_Q5_1) {
637 return vec_dot_fattn_vec_KQ_q5_1<D, nthreads>;
638 } else if constexpr (type_K == GGML_TYPE_Q8_0) {
639 return vec_dot_fattn_vec_KQ_q8_0<D, nthreads>;
640 } else if constexpr (type_K == GGML_TYPE_BF16) {
641 return vec_dot_fattn_vec_KQ_bf16<D, nthreads>;
642 } else {
643 static_assert(type_K == -1, "bad type");
644 return nullptr;
645 }
646}
647
648template <ggml_type type_V, typename T, int ne>
649constexpr __device__ dequantize_V_t get_dequantize_V() {
650 if constexpr (type_V == GGML_TYPE_F16) {
651 return dequantize_V_f16<T, ne>;
652 } else if constexpr (type_V == GGML_TYPE_Q4_0) {
653 return dequantize_V_q4_0<T, ne>;
654 } else if constexpr (type_V == GGML_TYPE_Q4_1) {
655 return dequantize_V_q4_1<T, ne>;
656 } else if constexpr (type_V == GGML_TYPE_Q5_0) {
657 return dequantize_V_q5_0<T, ne>;
658 } else if constexpr (type_V == GGML_TYPE_Q5_1) {
659 return dequantize_V_q5_1<T, ne>;
660 } else if constexpr (type_V == GGML_TYPE_Q8_0) {
661 return dequantize_V_q8_0<T, ne>;
662 } else if constexpr (type_V == GGML_TYPE_BF16) {
663 return dequantize_V_bf16<float, ne>;
664 } else {
665 static_assert(type_V == -1, "bad type");
666 return nullptr;
667 }
668}
669
670template <int ncols1>
671__launch_bounds__(FATTN_KQ_STRIDE/2, 1)
672static __global__ void flash_attn_mask_to_KV_max(
673 const half2 * mask_ptr, int * KV_max_ptr, const int ne30, const int64_t s31, const int64_t s33) {
674 const half2 * GGML_CUDA_RESTRICT mask = mask_ptr;
675 int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
676
677 const int ne31 = gridDim.x;
678 const int tid = threadIdx.x;
679 const int sequence = blockIdx.y;
680 const int jt = blockIdx.x;
681
682 mask += sequence*s33 + jt*ncols1*s31;
683
684 __shared__ int buf_iw[WARP_SIZE];
685 if (tid < WARP_SIZE) {
686 buf_iw[tid] = 1;
687 }
688 ggml_cuda_pdl_sync();
689 __syncthreads();
690
691 int KV_max_sj = (ne30 - 1) * FATTN_KQ_STRIDE;
692 for (; KV_max_sj >= 0; KV_max_sj -= FATTN_KQ_STRIDE) {
693 int all_inf = 1;
694
695#pragma unroll
696 for (int j = 0; j < ncols1; ++j) {
697 const float2 tmp = __half22float2(mask[j*s31 + KV_max_sj/2 + tid]);
698 all_inf = all_inf && int(isinf(tmp.x)) && int(isinf(tmp.y));
699 }
700
701 all_inf = warp_reduce_all(all_inf);
702 if (tid % WARP_SIZE == 0) {
703 buf_iw[tid / WARP_SIZE] = all_inf;
704 }
705 __syncthreads();
706 all_inf = buf_iw[tid % WARP_SIZE];
707 __syncthreads();
708 all_inf = warp_reduce_all(all_inf);
709
710 if (!all_inf) {
711 break;
712 }
713 }
714
715 // If the break in the loop was not triggered, KV_max_sj is now -FATTN_KQ_STRIDE.
716 // If the break was triggered it's the lower edge of the tile with the first non-masked values.
717 // In either case, walk back the decrementation by FATTN_KQ_STRIDE.
718 KV_max_sj += FATTN_KQ_STRIDE;
719
720 if (threadIdx.x != 0) {
721 return;
722 }
723
724 KV_max[sequence*ne31 + jt] = KV_max_sj;
725}
726
727void ggml_cuda_flash_attn_ext_compact_mask(
728 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);
729
730template<int D, int ncols1, int ncols2> // D == head size
731__launch_bounds__(D, 1)
732static __global__ void flash_attn_stream_k_fixup_uniform(
733 float * dst_ptr,
734 const float2 * dst_fixup_ptr,
735 const int ne01, const int ne02,
736 const int ne12, const int nblocks_stream_k,
737 const int gqa_ratio,
738 const int blocks_per_tile,
739 const uint3 fd_iter_j_z_ne12,
740 const uint3 fd_iter_j_z,
741 const uint3 fd_iter_j) {
742 constexpr int ncols = ncols1*ncols2;
743 ggml_cuda_pdl_lc();
744 float * GGML_CUDA_RESTRICT dst = dst_ptr;
745 const float2 * GGML_CUDA_RESTRICT dst_fixup = dst_fixup_ptr;
746
747 const int tile_idx = blockIdx.x; // One block per output tile.
748 const int j = blockIdx.y;
749 const int c = blockIdx.z;
750 const int jc = j*ncols2 + c;
751 const int tid = threadIdx.x;
752
753 // nblocks_stream_k is a multiple of ntiles_dst (== gridDim.x), so each tile gets the same number of blocks.
754 const int b_first = tile_idx * blocks_per_tile;
755 const int b_last = b_first + blocks_per_tile - 1;
756
757 const float * dst_fixup_data = ((const float *) dst_fixup) + nblocks_stream_k*(2*2*ncols);
758
759 // z_KV == K/V head index, zt_gqa = Q head start index per K/V head, jt = token position start index
760 const uint2 dm0 = fast_div_modulo(tile_idx, fd_iter_j_z_ne12);
761 const uint2 dm1 = fast_div_modulo(dm0.y, fd_iter_j_z);
762 const uint2 dm2 = fast_div_modulo(dm1.y, fd_iter_j);
763
764 const int sequence = dm0.x;
765 const int z_KV = dm1.x;
766 const int zt_gqa = dm2.x;
767 const int jt = dm2.y;
768
769 const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
770
771 if (jt*ncols1 + j >= ne01 || zt_gqa*ncols2 + c >= gqa_ratio) {
772 return;
773 }
774
775 dst += sequence*ne02*ne01*D + jt*ne02*(ncols1*D) + zt_Q*D + (j*ne02 + c)*D + tid;
776
777 ggml_cuda_pdl_sync();
778 // Load the partial result that needs a fixup
779 float dst_val = *dst;
780 float max_val;
781 float rowsum;
782 {
783 const float2 tmp = dst_fixup[b_last*ncols + jc];
784 max_val = tmp.x;
785 rowsum = tmp.y;
786 }
787
788 // Combine with all previous blocks in this tile.
789 for (int bidx = b_last - 1; bidx >= b_first; --bidx) {
790 const float dst_add = dst_fixup_data[bidx*ncols*D + jc*D + tid];
791
792 const float2 tmp = dst_fixup[(nblocks_stream_k + bidx)*ncols + jc];
793
794 const float max_val_new = fmaxf(max_val, tmp.x);
795
796 const float diff_val = max_val - max_val_new;
797 const float diff_add = tmp.x - max_val_new;
798
799 const float scale_val = diff_val >= SOFTMAX_FTZ_THRESHOLD ? expf(diff_val) : 0.0f;
800 const float scale_add = diff_add >= SOFTMAX_FTZ_THRESHOLD ? expf(diff_add) : 0.0f;
801
802 dst_val = scale_val*dst_val + scale_add*dst_add;
803 rowsum = scale_val*rowsum + scale_add*tmp.y;
804
805 max_val = max_val_new;
806 }
807
808 // Write back final result:
809 *dst = dst_val / rowsum;
810}
811
812// General fixup kernel for the case where the number of blocks per tile is not uniform across tiles
813// (blocks_num.x not a multiple of ntiles_dst)
814template <int D, int ncols1, int ncols2> // D == head size
815__launch_bounds__(D, 1)
816static __global__ void flash_attn_stream_k_fixup_general(
817 float * dst_ptr,
818 const float2 * dst_fixup_ptr,
819 const int ne01, const int ne02,
820 const int gqa_ratio,
821 const int total_work,
822 const uint3 fd_iter_k_j_z_ne12,
823 const uint3 fd_iter_k_j_z,
824 const uint3 fd_iter_k_j,
825 const uint3 fd_iter_k) {
826 float * GGML_CUDA_RESTRICT dst = dst_ptr;
827 const float2 * GGML_CUDA_RESTRICT dst_fixup = dst_fixup_ptr;
828 constexpr int ncols = ncols1*ncols2;
829
830 const int bidx0 = blockIdx.x;
831 const int j = blockIdx.y;
832 const int c = blockIdx.z;
833 const int jc = j*ncols2 + c;
834 const int tid = threadIdx.x;
835
836 const float * dst_fixup_data = ((const float *) dst_fixup) + gridDim.x*(2*2*ncols);
837
838 const int kbc0 = int64_t(bidx0 + 0)*total_work / gridDim.x;
839 const int kbc0_stop = int64_t(bidx0 + 1)*total_work / gridDim.x;
840
841 const bool did_not_have_any_data = kbc0 == kbc0_stop;
842 const bool wrote_beginning_of_tile = fastmodulo(kbc0, fd_iter_k) == 0;
843 const bool did_not_write_last = fastdiv(kbc0, fd_iter_k) == fastdiv(kbc0_stop, fd_iter_k) && fastmodulo(kbc0_stop, fd_iter_k) != 0;
844 if (did_not_have_any_data || wrote_beginning_of_tile || did_not_write_last) {
845 return;
846 }
847
848 // z_KV == K/V head index, zt_gqa = Q head start index per K/V head, jt = token position start index
849 const uint2 dm0 = fast_div_modulo(kbc0, fd_iter_k_j_z_ne12);
850 const uint2 dm1 = fast_div_modulo(dm0.y, fd_iter_k_j_z);
851 const uint2 dm2 = fast_div_modulo(dm1.y, fd_iter_k_j);
852 const uint2 dm3 = fast_div_modulo(dm2.y, fd_iter_k);
853
854 const int sequence = dm0.x;
855 const int z_KV = dm1.x;
856 const int zt_gqa = dm2.x;
857 const int jt = dm3.x;
858
859 const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
860
861 if (jt*ncols1 + j >= ne01 || zt_gqa*ncols2 + c >= gqa_ratio) {
862 return;
863 }
864
865 dst += sequence*ne02*ne01*D + jt*ne02*(ncols1*D) + zt_Q*D + (j*ne02 + c)*D + tid;
866
867 // Load the partial result that needs a fixup:
868 float dst_val = 0.0f;
869 float max_val = 0.0f;
870 float rowsum = 0.0f;
871 ggml_cuda_pdl_sync();
872 {
873 dst_val = *dst;
874
875 const float2 tmp = dst_fixup[bidx0*ncols + jc];
876 max_val = tmp.x;
877 rowsum = tmp.y;
878 }
879
880 // Iterate over previous blocks and compute the combined results.
881 // All CUDA blocks that get here must have a previous block that needs a fixup.
882 const int tile_kbc0 = fastdiv(kbc0, fd_iter_k);
883 int bidx = bidx0 - 1;
884 int kbc_stop = kbc0;
885 while(true) {
886 const int kbc = int64_t(bidx)*total_work / gridDim.x;
887 if (kbc == kbc_stop) { // Did not have any data.
888 bidx--;
889 kbc_stop = kbc;
890 continue;
891 }
892
893 const float dst_add = dst_fixup_data[bidx*ncols*D + jc*D + tid];
894
895 const float2 tmp = dst_fixup[(gridDim.x + bidx)*ncols + jc];
896
897 // Scale the current and new value accumulators depending on the max. values.
898 const float max_val_new = fmaxf(max_val, tmp.x);
899
900 const float diff_val = max_val - max_val_new;
901 const float diff_add = tmp.x - max_val_new;
902
903 const float scale_val = diff_val >= SOFTMAX_FTZ_THRESHOLD ? expf(diff_val) : 0.0f;
904 const float scale_add = diff_add >= SOFTMAX_FTZ_THRESHOLD ? expf(diff_add) : 0.0f;
905
906 dst_val = scale_val*dst_val + scale_add*dst_add;
907 rowsum = scale_val*rowsum + scale_add*tmp.y;
908
909 max_val = max_val_new;
910
911 // If this block started in a previous tile we are done and don't need to combine additional partial results.
912 if (fastmodulo(kbc, fd_iter_k) == 0 || fastdiv(kbc, fd_iter_k) < tile_kbc0) {
913 break;
914 }
915 bidx--;
916 kbc_stop = kbc;
917 }
918
919 // Write back final result:
920 *dst = dst_val / rowsum;
921}
922
923template<int D> // D == head size
924__launch_bounds__(D, 1)
925static __global__ void flash_attn_combine_results(
926 const float * VKQ_parts_ptr,
927 const float2 * VKQ_meta_ptr,
928 float * dst_ptr,
929 const int parallel_blocks) {
930 ggml_cuda_pdl_lc();
931 const float * GGML_CUDA_RESTRICT VKQ_parts = VKQ_parts_ptr;
932 const float2 * GGML_CUDA_RESTRICT VKQ_meta = VKQ_meta_ptr;
933 float * GGML_CUDA_RESTRICT dst = dst_ptr;
934 // Dimension 0: threadIdx.x
935 // Dimension 1: blockIdx.x
936 // Dimension 2: blockIdx.y
937 // Dimension 3: blockIdx.z
938 // Memory layout is permuted with [0, 2, 1, 3]
939
940 const int ne01 = gridDim.x;
941 const int ne02 = gridDim.y;
942
943 const int col = blockIdx.x;
944 const int head = blockIdx.y;
945 const int sequence = blockIdx.z;
946
947 const int j_dst_unrolled = (sequence*ne01 + col)*ne02 + head;
948
949 VKQ_parts += j_dst_unrolled * parallel_blocks*D;
950 VKQ_meta += j_dst_unrolled * parallel_blocks;
951 dst += j_dst_unrolled * D;
952
953 const int tid = threadIdx.x;
954 __builtin_assume(tid < D);
955
956 extern __shared__ float2 meta[];
957 ggml_cuda_pdl_sync();
958 for (int i = tid; i < 2*parallel_blocks; i += D) {
959 ((float *) meta)[i] = ((const float *)VKQ_meta) [i];
960 }
961
962 __syncthreads();
963
964 float kqmax = meta[0].x;
965 for (int l = 1; l < parallel_blocks; ++l) {
966 kqmax = max(kqmax, meta[l].x);
967 }
968
969 float VKQ_numerator = 0.0f;
970 float VKQ_denominator = 0.0f;
971 for (int l = 0; l < parallel_blocks; ++l) {
972 const float KQ_max_scale = expf(meta[l].x - kqmax);
973
974 VKQ_numerator += KQ_max_scale * VKQ_parts[l*D + tid];
975 VKQ_denominator += KQ_max_scale * meta[l].y;
976 }
977
978 dst[tid] = VKQ_numerator / VKQ_denominator;
979}
980
981template <int DV, int ncols1, int ncols2>
982void launch_fattn(
983 ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared,
984 const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse,
985 const int warp_size = WARP_SIZE, const bool async_kv_preload = false
986) {
987 constexpr int ncols = ncols1 * ncols2;
988
989 const ggml_tensor * Q = dst->src[0];
990 const ggml_tensor * K = dst->src[1];
991 const ggml_tensor * V = dst->src[2];
992
993 const bool V_is_K_view = V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs));
994
995 const ggml_tensor * mask = dst->src[3];
996 const ggml_tensor * sinks = dst->src[4];
997 const ggml_tensor * kv_rows = dst->src[5];
998
999 // with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows
1000 const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1];
1001 GGML_ASSERT(!kv_rows || !use_sparse);
1002
1003 ggml_tensor * KQV = dst;
1004
1005 GGML_ASSERT(Q->type == GGML_TYPE_F32);
1006 GGML_ASSERT(KQV->type == GGML_TYPE_F32);
1007
1008 GGML_ASSERT(Q->nb[0] == ggml_element_size(Q));
1009 GGML_ASSERT(K->nb[0] == ggml_element_size(K));
1010 GGML_ASSERT(V->nb[0] == ggml_element_size(V));
1011
1012 GGML_ASSERT(!mask || mask->type == GGML_TYPE_F16);
1013
1014 ggml_cuda_pool & pool = ctx.pool();
1015 cudaStream_t main_stream = ctx.stream();
1016 const int id = ggml_cuda_get_device();
1017 const int cc = ggml_cuda_info().devices[id].cc;
1018 const int nsm = ggml_cuda_info().devices[id].nsm;
1019
1020 const ggml_cuda_flash_attn_ext_f16_extra_data f16_extra =
1021 ggml_cuda_flash_attn_ext_get_f16_extra_data(KQV, need_f16_K, need_f16_V);
1022
1023 ggml_cuda_pool_alloc<int> KV_max(pool);
1024 ggml_cuda_pool_alloc<float> dst_tmp(pool);
1025 ggml_cuda_pool_alloc<float2> dst_tmp_meta(pool);
1026
1027 const char * K_data = (const char *) K->data;
1028 size_t nb11 = K->nb[1];
1029 size_t nb12 = K->nb[2];
1030 size_t nb13 = K->nb[3];
1031
1032 const char * V_data = (const char *) V->data;
1033 size_t nb21 = V->nb[1];
1034 size_t nb22 = V->nb[2];
1035 size_t nb23 = V->nb[3];
1036
1037 if (need_f16_K && K->type != GGML_TYPE_F16) {
1038 const size_t bs = ggml_blck_size(K->type);
1039 const size_t ts = ggml_type_size(K->type);
1040
1041 GGML_ASSERT(f16_extra.K != 0);
1042 half * K_f16 = (half *) f16_extra.K;
1043 if (ggml_is_contiguously_allocated(K)) {
1044 to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(K->type);
1045 to_fp16(K_data, K_f16, ggml_nelements(K), main_stream);
1046
1047 nb11 = nb11*bs*sizeof(half)/ts;
1048 nb12 = nb12*bs*sizeof(half)/ts;
1049 nb13 = nb13*bs*sizeof(half)/ts;
1050 } else {
1051 GGML_ASSERT(K->nb[0] == ts);
1052 to_fp16_nc_cuda_t to_fp16 = ggml_get_to_fp16_nc_cuda(K->type);
1053 const int64_t s01 = nb11 / ts;
1054 const int64_t s02 = nb12 / ts;
1055 const int64_t s03 = nb13 / ts;
1056 to_fp16(K_data, K_f16, K->ne[0], K->ne[1], K->ne[2], K->ne[3], s01, s02, s03, main_stream);
1057
1058 nb11 = K->ne[0] * sizeof(half);
1059 nb12 = K->ne[1] * nb11;
1060 nb13 = K->ne[2] * nb12;
1061 }
1062 K_data = (char *) K_f16;
1063 }
1064
1065 if (need_f16_V && V->type != GGML_TYPE_F16) {
1066 if (V_is_K_view) {
1067 V_data = K_data;
1068 nb21 = nb11;
1069 nb22 = nb12;
1070 nb23 = nb13;
1071 } else {
1072 const size_t bs = ggml_blck_size(V->type);
1073 const size_t ts = ggml_type_size(V->type);
1074
1075 GGML_ASSERT(f16_extra.V != 0);
1076 half * V_f16 = (half *) f16_extra.V;
1077 if (ggml_is_contiguously_allocated(V)) {
1078 to_fp16_cuda_t to_fp16 = ggml_get_to_fp16_cuda(V->type);
1079 to_fp16(V_data, V_f16, ggml_nelements(V), main_stream);
1080 V_data = (char *) V_f16;
1081
1082 nb21 = nb21*bs*sizeof(half)/ts;
1083 nb22 = nb22*bs*sizeof(half)/ts;
1084 nb23 = nb23*bs*sizeof(half)/ts;
1085 } else {
1086 GGML_ASSERT(V->nb[0] == ts);
1087 to_fp16_nc_cuda_t to_fp16 = ggml_get_to_fp16_nc_cuda(V->type);
1088 const int64_t s01 = nb21 / ts;
1089 const int64_t s02 = nb22 / ts;
1090 const int64_t s03 = nb23 / ts;
1091 to_fp16(V_data, V_f16, V->ne[0], V->ne[1], V->ne[2], V->ne[3], s01, s02, s03, main_stream);
1092
1093 nb21 = V->ne[0] * sizeof(half);
1094 nb22 = V->ne[1] * nb21;
1095 nb23 = V->ne[2] * nb22;
1096 }
1097 V_data = (char *) V_f16;
1098 }
1099 }
1100
1101 const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1);
1102 const int gqa_ratio = Q->ne[2] / K->ne[2];
1103 const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2);
1104 const int ntiles_dst = ntiles_x * ntiles_z_gqa * K->ne[2] * Q->ne[3];
1105
1106 // sparse: a query tile of ncols1 queries shares one index list, the union of the queries' visible columns
1107 int32_t n_kv_max = 0;
1108 if (use_sparse) {
1109 GGML_ASSERT(mask != nullptr);
1110 const int32_t n_kv_max_query = ggml_get_op_params_i32(KQV, 4);
1111 GGML_ASSERT(n_kv_max_query > 0);
1112 n_kv_max = std::min<int64_t>(K->ne[1], int64_t(ncols1)*n_kv_max_query);
1113
1114 const size_t n_lists = size_t(ntiles_x) * mask->ne[3];
1115
1116 KV_max.alloc(size_t(n_kv_max)*n_lists + n_lists);
1117 ggml_cuda_flash_attn_ext_compact_mask(mask, KV_max.ptr, KV_max.ptr + size_t(n_kv_max)*n_lists, Q->ne[1], ncols1, n_kv_max, main_stream);
1118 }
1119
1120 // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped.
1121 // Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
1122 // multiple sequences of possibly different lengths, or kv_rows lists that end with padding.
1123 const bool scan_mask = !use_sparse && mask && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
1124 if (scan_mask) {
1125 const int64_t s31 = mask->nb[1] / sizeof(half2);
1126 const int64_t s33 = mask->nb[3] / sizeof(half2);
1127
1128 const dim3 blocks_num_KV_max(ntiles_x, Q->ne[3], 1);
1129 const dim3 block_dim_KV_max(FATTN_KQ_STRIDE/2, 1, 1);
1130
1131 const int ne_KV_max = blocks_num_KV_max.x*blocks_num_KV_max.y;
1132 const int iter_k = n_kv_cols / FATTN_KQ_STRIDE;
1133
1134 KV_max.alloc(ne_KV_max);
1135 ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_KV_max, block_dim_KV_max, 0, main_stream);
1136 ggml_cuda_kernel_launch(flash_attn_mask_to_KV_max<ncols1>, launch_params,
1137 (const half2 *) mask->data, KV_max.ptr, iter_k, s31, s33);
1138 CUDA_CHECK(cudaGetLastError());
1139 }
1140
1141 // K/V are shared by all slices when read through kv_rows
1142 if (kv_rows) {
1143 nb13 = 0;
1144 nb23 = 0;
1145 }
1146
1147 const dim3 block_dim(warp_size, nwarps, 1);
1148 int max_blocks_per_sm = 1; // Max. number of active blocks limited by occupancy.
1149 CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, fattn_kernel, block_dim.x * block_dim.y * block_dim.z, nbytes_shared));
1150 GGML_ASSERT(max_blocks_per_sm > 0);
1151 int parallel_blocks = max_blocks_per_sm;
1152
1153 const int64_t n_kv = use_sparse ? n_kv_max : n_kv_cols;
1154 const int ntiles_KV = (n_kv + nbatch_fa - 1) / nbatch_fa; // Max. number of parallel blocks limited by KV cache length.
1155
1156 dim3 blocks_num;
1157 if (stream_k) {
1158 // Stream-K splits the work before the mask scan is applied, so skipped KV tiles make the blocks uneven.
1159 const bool prefer_whole_tiles = GGML_CUDA_CC_IS_NVIDIA(cc) && cc == GGML_CUDA_CC_DGX_SPARK && async_kv_preload && scan_mask;
1160
1161 auto should_use_stream_k = [prefer_whole_tiles](const int cc, const int ntiles_dst, const int max_blocks, const int DKQ) {
1162 const int tiles_nwaves = (ntiles_dst + max_blocks - 1) / max_blocks;
1163 const int tiles_efficiency_percent = 100 * ntiles_dst / (max_blocks*tiles_nwaves);
1164
1165 if (prefer_whole_tiles && tiles_efficiency_percent >= 75) {
1166 return false;
1167 }
1168 if (GGML_CUDA_CC_IS_NVIDIA(cc) && cc >= GGML_CUDA_CC_ADA_LOVELACE) {
1169 return true;
1170 }
1171 if (amd_wmma_available(cc) && DKQ == 64) {
1172 return true; // TODO better configuration
1173 }
1174 return tiles_efficiency_percent < 75;
1175 };
1176
1177 const int max_blocks = max_blocks_per_sm*nsm;
1178 const bool use_stream_k = should_use_stream_k(cc, ntiles_dst, max_blocks, Q->ne[0]);
1179
1180 blocks_num.x = ntiles_dst;
1181 blocks_num.y = 1;
1182 blocks_num.z = 1;
1183
1184 if(use_stream_k) {
1185 const int nblocks_stream_k_raw = std::min(max_blocks, ntiles_KV*ntiles_dst);
1186 // Round down to a multiple of ntiles_dst so that each output tile gets the same number of blocks (avoids fixup).
1187 // Only do this if the occupancy loss from rounding is acceptable.
1188 const int nblocks_stream_k_rounded = (nblocks_stream_k_raw / ntiles_dst) * ntiles_dst;
1189 const int max_efficiency_loss_percent = 5;
1190 const int efficiency_loss_percent = nblocks_stream_k_rounded > 0
1191 ? 100 * (nblocks_stream_k_raw - nblocks_stream_k_rounded) / nblocks_stream_k_raw
1192 : 100;
1193 const int nblocks_stream_k = efficiency_loss_percent <= max_efficiency_loss_percent
1194 ? nblocks_stream_k_rounded
1195 : nblocks_stream_k_raw;
1196
1197 blocks_num.x = nblocks_stream_k;
1198 }
1199
1200 if (ntiles_dst % blocks_num.x != 0) { // Fixup is only needed if the SMs work on fractional tiles.
1201 dst_tmp_meta.alloc((size_t(blocks_num.x) * ncols * (2 + DV/2)));
1202 }
1203 } else {
1204 // parallel_blocks must not be larger than what the tensor size allows:
1205 parallel_blocks = std::min(parallel_blocks, ntiles_KV);
1206
1207 // If ntiles_total % blocks_per_wave != 0 then some efficiency is lost due to tail effects.
1208 // Test whether parallel_blocks can be set to a higher value for better efficiency.
1209 const int blocks_per_wave = nsm * max_blocks_per_sm;
1210 int nwaves_best = 0;
1211 int efficiency_percent_best = 0;
1212 for (int parallel_blocks_test = parallel_blocks; parallel_blocks_test <= ntiles_KV; ++parallel_blocks_test) {
1213 const int nblocks_total = ntiles_dst * parallel_blocks_test;
1214 const int nwaves = (nblocks_total + blocks_per_wave - 1) / blocks_per_wave;
1215 const int efficiency_percent = 100 * nblocks_total / (nwaves*blocks_per_wave);
1216
1217 // Stop trying configurations with more waves if we already have good efficiency to avoid excessive overhead.
1218 if (efficiency_percent_best >= 95 && nwaves > nwaves_best) {
1219 break;
1220 }
1221
1222 if (efficiency_percent > efficiency_percent_best) {
1223 nwaves_best = nwaves;
1224 efficiency_percent_best = efficiency_percent;
1225 parallel_blocks = parallel_blocks_test;
1226 }
1227 }
1228
1229 blocks_num.x = ntiles_x;
1230 blocks_num.y = parallel_blocks;
1231 blocks_num.z = ntiles_z_gqa*K->ne[2]*Q->ne[3];
1232
1233 if (parallel_blocks > 1) {
1234 dst_tmp.alloc(parallel_blocks*ggml_nelements(KQV));
1235 dst_tmp_meta.alloc(parallel_blocks*ggml_nrows(KQV));
1236 }
1237 }
1238
1239 float scale = 1.0f;
1240 float max_bias = 0.0f;
1241 float logit_softcap = 0.0f;
1242
1243 memcpy(&scale, (const float *) KQV->op_params + 0, sizeof(float));
1244 memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
1245 memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
1246
1247 if (logit_softcap != 0.0f) {
1248 scale /= logit_softcap;
1249 }
1250
1251 const uint32_t n_head = Q->ne[2];
1252 const uint32_t n_head_log2 = 1u << uint32_t(floorf(log2f(float(n_head))));
1253
1254 const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
1255 const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
1256
1257 // TODO other tensor dimensions after removal of WMMA kernel:
1258 const uint3 ne01 = init_fastdiv_values(Q->ne[1]);
1259
1260 GGML_ASSERT(block_dim.x % warp_size == 0);
1261
1262 ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream);
1263 ggml_cuda_kernel_launch(fattn_kernel, launch_params,
1264 (const char *) Q->data,
1265 K_data,
1266 V_data,
1267 mask ? ((const char *) mask->data) : nullptr,
1268 sinks ? ((const char *) sinks->data) : nullptr,
1269 KV_max.ptr,
1270 kv_rows ? (const int *) kv_rows->data : nullptr,
1271 !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr,
1272 scale, max_bias, m0, m1, n_head_log2, logit_softcap,
1273 Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3],
1274 K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13,
1275 nb21, nb22, nb23,
1276 mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
1277 mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0
1278 );
1279 CUDA_CHECK(cudaGetLastError());
1280
1281 if (stream_k) {
1282 if ((int)blocks_num.x % ntiles_dst == 0 && (int)blocks_num.x > ntiles_dst) {
1283 // Optimized fixup: nblocks_stream_k is a multiple of ntiles_dst, launch one block per tile.
1284 const int nblocks_sk = (int)blocks_num.x;
1285 const int bpt = nblocks_sk / ntiles_dst;
1286
1287 const uint3 fd0 = init_fastdiv_values(ntiles_x * ntiles_z_gqa * K->ne[2]);
1288 const uint3 fd1 = init_fastdiv_values(ntiles_x * ntiles_z_gqa);
1289 const uint3 fd2 = init_fastdiv_values(ntiles_x);
1290
1291 const dim3 block_dim_combine(DV, 1, 1);
1292 const dim3 blocks_num_combine = {(unsigned)ntiles_dst, ncols1, ncols2};
1293
1294 const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, 0, main_stream);
1295 ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_uniform<DV, ncols1, ncols2>, launch_params,
1296 (float *) KQV->data, dst_tmp_meta.ptr,
1297 Q->ne[1], Q->ne[2], K->ne[2], nblocks_sk,
1298 gqa_ratio, bpt, fd0, fd1, fd2);
1299 } else if (ntiles_dst % blocks_num.x != 0) {
1300 // General fixup for the cases where nblocks_stream_k < ntiles_dst.
1301 const int total_work = ntiles_KV * ntiles_dst;
1302
1303 const uint3 fd_k_j_z_ne12 = init_fastdiv_values(ntiles_KV * ntiles_x * ntiles_z_gqa * K->ne[2]);
1304 const uint3 fd_k_j_z = init_fastdiv_values(ntiles_KV * ntiles_x * ntiles_z_gqa);
1305 const uint3 fd_k_j = init_fastdiv_values(ntiles_KV * ntiles_x);
1306 const uint3 fd_k = init_fastdiv_values(ntiles_KV);
1307
1308 const dim3 block_dim_combine(DV, 1, 1);
1309 const dim3 blocks_num_combine = {blocks_num.x, ncols1, ncols2};
1310
1311 const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, 0, main_stream);
1312 ggml_cuda_kernel_launch(flash_attn_stream_k_fixup_general<DV, ncols1, ncols2>, launch_params,
1313 (float *) KQV->data, dst_tmp_meta.ptr,
1314 Q->ne[1], Q->ne[2], gqa_ratio, total_work,
1315 fd_k_j_z_ne12, fd_k_j_z, fd_k_j, fd_k);
1316 }
1317 } else if (parallel_blocks > 1) {
1318 const dim3 block_dim_combine(DV, 1, 1);
1319 const dim3 blocks_num_combine(Q->ne[1], Q->ne[2], Q->ne[3]);
1320 const size_t nbytes_shared_combine = parallel_blocks*sizeof(float2);
1321
1322 const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_combine, block_dim_combine, nbytes_shared_combine, main_stream);
1323 ggml_cuda_kernel_launch(flash_attn_combine_results<DV>, launch_params,
1324 dst_tmp.ptr, dst_tmp_meta.ptr, (float *) KQV->data, parallel_blocks);
1325 }
1326 CUDA_CHECK(cudaGetLastError());
1327}