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-metal / kernels / fa_tensor.metal

298 lines · 11395 bytes Raw Blame History
1#include "common.h"
2
3#ifdef GGML_METAL_HAS_TENSOR
4
5constant bool FC_flash_attn_ext_tensor_has_mask [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 0)]];
6constant bool FC_flash_attn_ext_tensor_has_sinks [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 1)]];
7constant bool FC_flash_attn_ext_tensor_has_bias [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 2)]];
8constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 3)]];
9
10// ref: https://arxiv.org/pdf/2307.08691.pdf
11template<
12 typename T, // Q, K, V and P types
13 typename T4,
14 short DK, // K head size
15 short DV, // V head size
16 short Q = OP_FLASH_ATTN_EXT_TENSOR_NQPSG, // queries per threadgroup
17 short C = OP_FLASH_ATTN_EXT_TENSOR_NCPSG, // cache items per threadgroup
18 short NSG = OP_FLASH_ATTN_EXT_TENSOR_NSG> // number of simd groups
19kernel void kernel_flash_attn_ext_tensor(
20 constant ggml_metal_kargs_flash_attn_ext & args,
21 device const char * q,
22 device const char * k,
23 device const char * v,
24 device const char * mask,
25 device const char * sinks,
26 device const char * blk,
27 device char * dst,
28 threadgroup char * shmem [[threadgroup(0)]],
29 uint3 tgpig [[threadgroup_position_in_grid]],
30 ushort tiisg [[thread_index_in_simdgroup]],
31 ushort sgitg [[simdgroup_index_in_threadgroup]]) {
32 constexpr short NW = N_SIMDWIDTH;
33 constexpr short NT = NW*NSG;
34 constexpr short NQ = Q/NSG;
35 constexpr short NC = C/NW; // columns per thread
36
37 static_assert(DK % 4 == 0, "DK must be divisible by 4");
38 static_assert(Q % NSG == 0, "Q must be divisible by NSG");
39 static_assert(C % NW == 0, "C must be divisible by NW");
40
41 const int iq3 = tgpig[2];
42 const int iq2 = tgpig[1];
43 const int iq1 = tgpig[0]*Q;
44
45 const short tiitg = sgitg*NW + tiisg;
46
47 threadgroup T * sq = (threadgroup T *) shmem; // [Q, DK] queries
48 threadgroup float * ss = (threadgroup float *) (sq + Q*DK); // [Q, C] scores
49 threadgroup T * sp = (threadgroup T *) (ss + Q*C); // [Q, C] probabilities
50 threadgroup float * sr = (threadgroup float *) (sp + Q*C); // [Q] per-row scale of O
51 threadgroup int * sf = (threadgroup int *) (sr + Q); // [1] last iteration (ic0 + 1) that rescaled O
52
53 q += iq1*args.nb01 + iq2*args.nb02 + iq3*args.nb03;
54
55 {
56 const int ikv2 = iq2/(args.ne02/args.ne_12_2);
57 const int ikv3 = iq3/(args.ne03/args.ne_12_3);
58
59 k += ikv2*args.nb12 + ikv3*args.nb13;
60 v += ikv2*args.nb22 + ikv3*args.nb23;
61 }
62
63 // with softcap the scale is small (scale/softcap), so it is applied to the scores to keep the precision of Q
64 const float qscale = FC_flash_attn_ext_tensor_has_scap ? 1.0f : args.scale;
65
66 // load the queries, with the scale folded in
67 for (int i = tiitg; i < Q*DK/4; i += NT) {
68 const int j = i/(DK/4);
69
70 float4 q4 = 0.0f;
71 if (iq1 + j < args.ne01) {
72 q4 = ((device const float4 *) (q + j*args.nb01))[i%(DK/4)];
73 }
74
75 ((threadgroup T4 *) sq)[i] = (T4) (q4*qscale);
76 }
77
78 device const half * pm[NQ];
79
80 FOR_UNROLL (short jj = 0; jj < NQ; ++jj) {
81 const short j = jj*NSG + sgitg;
82
83 pm[jj] = (device const half *) (mask + (iq1 + j)*args.nb31 + (iq2%args.ne32)*args.nb32 + (iq3%args.ne33)*args.nb33);
84 }
85
86 {
87 const int nblk1 = (args.ne01 + Q - 1)/Q;
88 const int nblk0 = (args.ne11 + C - 1)/C;
89
90 blk += (((iq3%args.ne33)*args.ne32 + (iq2%args.ne32))*nblk1 + iq1/Q)*nblk0;
91 }
92
93 float M[NQ];
94 float S[NQ];
95
96 FOR_UNROLL (short jj = 0; jj < NQ; ++jj) {
97 M[jj] = -FLT_MAX/2;
98 S[jj] = 0.0f;
99 }
100
101 float slope = 1.0f;
102
103 // ALiBi
104 if (FC_flash_attn_ext_tensor_has_bias) {
105 const short h = iq2;
106
107 const float base = h < args.n_head_log2 ? args.m0 : args.m1;
108 const short exph = h < args.n_head_log2 ? h + 1 : 2*(h - args.n_head_log2) + 1;
109
110 slope = pow(base, exph);
111 }
112
113 const int sk = args.ns10;
114 const int sv = args.ns20;
115
116 auto tq = tensor(sq, dextents<int32_t, 2>(DK, Q));
117 auto ts = tensor(ss, dextents<int32_t, 2>(C, Q));
118 auto tp = tensor(sp, dextents<int32_t, 2>(C, Q));
119
120 mpp::tensor_ops::matmul2d<
121 mpp::tensor_ops::matmul2d_descriptor(Q, C, DK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply),
122 execution_simdgroups<NSG>> mm_qk;
123
124 mpp::tensor_ops::matmul2d<
125 mpp::tensor_ops::matmul2d_descriptor(Q, DV, C, false, false, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
126 execution_simdgroups<NSG>> mm_pv;
127
128 auto tv0 = tensor((device T *) v, dextents<int32_t, 2>(DV, C), array<int, 2>({1, sv}));
129
130 // the O matrix from the paper
131 auto co = mm_pv.template get_destination_cooperative_tensor<decltype(tp), decltype(tv0), float>();
132
133 FOR_UNROLL (short i = 0; i < co.get_capacity(); ++i) {
134 if (co.is_valid_element(i)) {
135 co[i] = 0.0f;
136 }
137 }
138
139 if (tiitg == 0) {
140 sf[0] = 0;
141 }
142
143 threadgroup_barrier(mem_flags::mem_threadgroup);
144
145 // the host guarantees ne11 % C == 0
146 for (int ic0 = 0, ic = 0; ic < args.ne11; ++ic0, ic += C) {
147 char blk_cur = 1;
148
149 if (FC_flash_attn_ext_tensor_has_mask) {
150 blk_cur = blk[ic0];
151
152 if (blk_cur == 0) {
153 continue;
154 }
155 }
156
157 // Q*K^T
158 {
159 auto tk = tensor((device T *) (k + (uint64_t) ic*args.nb11), dextents<int32_t, 2>(DK, C), array<int, 2>({1, sk}));
160
161 mm_qk.run(tq, tk, ts);
162 }
163
164 threadgroup_barrier(mem_flags::mem_threadgroup);
165
166 // online softmax
167 FOR_UNROLL (short jj = 0; jj < NQ; ++jj) {
168 const short j = jj*NSG + sgitg;
169
170 float s[NC];
171
172 FOR_UNROLL (short ii = 0; ii < NC; ++ii) {
173 s[ii] = ss[j*C + ii*NW + tiisg];
174 }
175
176 if (FC_flash_attn_ext_tensor_has_scap) {
177 FOR_UNROLL (short ii = 0; ii < NC; ++ii) {
178 s[ii] = args.logit_softcap*precise::tanh(s[ii]*args.scale);
179 }
180 }
181
182 if (FC_flash_attn_ext_tensor_has_mask && blk_cur != 2 && iq1 + j < args.ne31) {
183 FOR_UNROLL (short ii = 0; ii < NC; ++ii) {
184 s[ii] += slope*(float) pm[jj][ic + ii*NW + tiisg];
185 }
186 }
187
188 float m = M[jj];
189
190 FOR_UNROLL (short ii = 0; ii < NC; ++ii) {
191 m = max(m, s[ii]);
192 }
193
194 m = simd_max(m);
195
196 // lazy rescaling: move the running max only when it grows by more than 8 (e^8 fits in half)
197 float ms = 1.0f;
198
199 if (m > M[jj] + 8.0f) {
200 ms = exp(M[jj] - m);
201 M[jj] = m;
202
203 if (tiisg == 0) {
204 sf[0] = ic0 + 1;
205 }
206 }
207
208 float sum = 0.0f;
209
210 FOR_UNROLL (short ii = 0; ii < NC; ++ii) {
211 // the sum uses the same rounded values as P*V
212 const T p = (T) exp(s[ii] - M[jj]);
213
214 sp[j*C + ii*NW + tiisg] = p;
215
216 sum += (float) p;
217 }
218
219 S[jj] = S[jj]*ms + simd_sum(sum);
220
221 if (tiisg == 0) {
222 sr[j] = ms;
223 }
224 }
225
226 threadgroup_barrier(mem_flags::mem_threadgroup);
227
228 // O = diag(ms)*O + P*V
229 if (sf[0] == ic0 + 1) {
230 FOR_UNROLL (short i = 0; i < co.get_capacity(); ++i) {
231 if (co.is_valid_element(i)) {
232 co[i] *= sr[co.get_multidimensional_index(i)[1]];
233 }
234 }
235 }
236
237 {
238 auto tv = tensor((device T *) (v + (uint64_t) ic*args.nb21), dextents<int32_t, 2>(DV, C), array<int, 2>({1, sv}));
239
240 mm_pv.run(tp, tv, co);
241 }
242
243 threadgroup_barrier(mem_flags::mem_threadgroup);
244 }
245
246 FOR_UNROLL (short jj = 0; jj < NQ; ++jj) {
247 const short j = jj*NSG + sgitg;
248
249 // the sink only adds to the denominator - its rescale of O is folded into the final scale
250 float ms = 1.0f;
251
252 if (FC_flash_attn_ext_tensor_has_sinks) {
253 const float s = ((device const float *) sinks)[iq2];
254 const float m = max(M[jj], s);
255
256 ms = exp(M[jj] - m);
257
258 S[jj] = S[jj]*ms + exp(s - m);
259 }
260
261 if (tiisg == 0) {
262 sr[j] = S[jj] == 0.0f ? 0.0f : ms/S[jj];
263 }
264 }
265
266 threadgroup_barrier(mem_flags::mem_threadgroup);
267
268 FOR_UNROLL (short i = 0; i < co.get_capacity(); ++i) {
269 if (co.is_valid_element(i)) {
270 co[i] *= sr[co.get_multidimensional_index(i)[1]];
271 }
272 }
273
274 // store to global memory - rows past ne01 are clipped by the tensor extents
275 device float * pdst = (device float *) dst + ((uint64_t) iq3*args.ne2*args.ne1 + iq2 + (uint64_t) iq1*args.ne1)*DV;
276
277 auto td = tensor(pdst, dextents<int32_t, 2>(DV, args.ne01 - iq1), array<int, 2>({1, args.ne1*DV}));
278
279 co.store(td);
280}
281
282typedef decltype(kernel_flash_attn_ext_tensor<half, half4, 64, 64>) flash_attn_ext_tensor_t;
283
284template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 64, 64>;
285template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 128, 128>;
286template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 192, 128>;
287template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 256, 256>;
288template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
289template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
290
291template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 64, 64>;
292template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 128, 128>;
293template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 192, 128>;
294template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 256, 256>;
295template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
296template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
297
298#endif // GGML_METAL_HAS_TENSOR