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-sycl / fattn-mkl.cpp

682 lines · 30029 bytes Raw Blame History
1// Flash attention via oneMKL GEMM (XMX-accelerated).
2// Uses column_major::gemm for Q*K^T and S*V matmuls
3// with an online softmax SYCL kernel.
4//
5// All GQA query heads sharing a KV head are batched into single
6// GEMM calls, amortizing MKL launch overhead across K and V reuse.
7//
8
9#include "common.hpp"
10#include "fattn-common.hpp"
11#include "convert.hpp"
12#include "fattn.hpp"
13
14#include <oneapi/mkl.hpp>
15#include <cstdio>
16#include <chrono>
17#include <vector>
18
19#define MKL_FA_CHUNK_SIZE_KV 8192
20
21// Number of query rows processed per tile. The score buffers (KQ_f32, S_f16)
22// are sized q_tile_rows * chunk_size, so this bounds their footprint
23// regardless of batch size (n_query_rows = n_queries * gqa_ratio). A typical
24// single-ubatch prefill (e.g. ubatch 1024 * gqa 8 = 8192 rows) is exactly one
25// tile, so it runs with no extra iterations. Larger batches tile and stay
26// bounded. Override with GGML_SYCL_MKL_FA_Q_TILE.
27#define MKL_FA_Q_TILE 8192
28
29#define MKL_FA_WG_SIZE 256
30
31using oneapi::mkl::transpose;
32using oneapi::mkl::blas::column_major::gemm;
33
34// ---------------------------------------------------------------------------
35// Helpers
36// ---------------------------------------------------------------------------
37
38// Pack all GQA Q heads for one KV head into fp16, applying q_scale.
39// Launches one kernel per GQA group — each kernel copies exactly
40// n_queries * DKQ elements using the per-group dst offset and
41// per-head source stride.
42static void mkl_fa_pack_q_fp16(
43 dpct::queue_ptr stream,
44 sycl::half * __restrict dst,
45 const float * __restrict q_src,
46 int n_queries, int DKQ,
47 int gqa_ratio, int kvh_base_head,
48 float q_scale, int64_t q_row_stride, int64_t q_head_stride,
49 int64_t wg_size) {
50
51 for (int iqg = 0; iqg < gqa_ratio; iqg++) {
52 int iqh = kvh_base_head + iqg;
53 sycl::half * dst_g = dst + (int64_t)iqg * n_queries * DKQ;
54
55 const int64_t n_elem = (int64_t)n_queries * DKQ;
56 const int64_t wg = ((n_elem + wg_size - 1) / wg_size) * wg_size;
57
58 stream->submit([&](sycl::handler & cgh) {
59 cgh.parallel_for(sycl::nd_range<1>(wg, wg_size),
60 [=](sycl::nd_item<1> item) {
61 int64_t e = item.get_global_id(0);
62 if (e >= n_elem) return;
63
64 int64_t q = e / DKQ;
65 int64_t d = e - q * DKQ;
66
67 // Stride-aware source offset: handles permuted,
68 // sliced, or contiguous Q tensor layouts.
69 int64_t src_off = d
70 + q * q_row_stride
71 + (int64_t)iqh * q_head_stride;
72
73 dst_g[e] = sycl::half(
74 q_src[src_off] * q_scale);
75 });
76 });
77 }
78}
79
80// Zero-initialize the online softmax state arrays.
81// KQ_max → -inf, KQ_sum → 0, VKQ_accum → 0.
82// Merged into one kernel to avoid per-array launch overhead.
83static void mkl_fa_init_softmax_state(
84 dpct::queue_ptr stream,
85 float * kmax, float * ksum, float * vacc,
86 int n_query_rows, int DV, int64_t wg_size) {
87
88 const float neg_inf = -1e30f;
89 const int64_t n_maxsum = n_query_rows;
90 const int64_t n_vacc = (int64_t)n_query_rows * DV;
91 const int64_t total = (n_vacc > n_maxsum) ? n_vacc : n_maxsum;
92 const int64_t wg = ((total + wg_size - 1) / wg_size) * wg_size;
93
94 stream->submit([&](sycl::handler & cgh) {
95 cgh.parallel_for(sycl::nd_range<1>(wg, wg_size),
96 [=](sycl::nd_item<1> item) {
97 int64_t i = item.get_global_id(0);
98 if (i < n_maxsum) {
99 kmax[i] = neg_inf;
100 ksum[i] = 0.0f;
101 }
102 if (i < n_vacc) {
103 vacc[i] = 0.0f;
104 }
105 });
106 });
107}
108
109// Online softmax over one KV chunk for a tile of GQA query rows.
110// The tile spans absolute rows [q0, q0 + q_rows). Score buffers
111// (KQ_f32/S_f16) are indexed RELATIVE to the tile; the persistent state
112// (VKQ_accum/KQ_max/KQ_sum) and mask are indexed by ABSOLUTE row.
113// One WORK-GROUP per query row (local size = wg_size): work-items stride
114// over the chunk so adjacent items touch adjacent elements (coalesced),
115// the row max/sum come from group reductions, and the DV-long VKQ
116// rescale is spread across the items. Item 0 is the sole writer of
117// KQ_max/KQ_sum; its writes are ordered after every other item's reads
118// by the second group reduction (a collective). Per-element math is
119// identical to the original one-item-per-row kernel: softcap before
120// mask, native::exp, -1e30 sentinel, half-precision S. Only the float
121// summation order differs (tree vs serial), i.e. last-ulp level.
122static void mkl_fa_online_softmax_chunk(
123 dpct::queue_ptr stream,
124 float * __restrict KQ_f32,
125 sycl::half * __restrict S_f16,
126 float * __restrict KQ_max,
127 float * __restrict KQ_sum,
128 float * __restrict VKQ_accum,
129 int q0, int q_rows, int n_queries, int DV,
130 int chunk_size, int chunk_start,
131 int kvh_head,
132 const sycl::half * mask_data, int64_t mask_head_stride,
133 int64_t mask_row_stride, int mask_n_heads,
134 float logit_softcap, int64_t wg_size,
135 const sycl::event & dep_event) {
136
137 // One work-group per query row: exactly q_rows groups of wg_size
138 // items. q_rows * wg_size is already a multiple of wg_size, so unlike
139 // the one-item-per-row kernels there is no round-up / tail guard.
140 const int64_t wg = q_rows * wg_size;
141 const int local_size = (int) wg_size; // stride in the loops below
142 stream->submit([&](sycl::handler & cgh) {
143 cgh.depends_on(dep_event);
144 cgh.parallel_for(sycl::nd_range<1>(wg, wg_size),
145 [=](sycl::nd_item<1> item) {
146 const int local_id = (int)item.get_local_id(0);
147 const int row = (int)item.get_group(0); // tile-relative
148 const int jc_abs = q0 + row;
149 const int gqa_group = jc_abs / n_queries;
150 const int q_row = jc_abs % n_queries;
151 // Score buffers are tile-local (relative index).
152 const float * __restrict KQ_row = KQ_f32
153 + row * (int64_t)chunk_size;
154 sycl::half * __restrict S_row = S_f16
155 + row * (int64_t)chunk_size;
156 // Persistent accumulator is full-sized (absolute index).
157 float * __restrict vkq = VKQ_accum
158 + jc_abs * (int64_t)DV;
159 const sycl::half * mask_h = nullptr;
160 int64_t m_stride = 0;
161 if (mask_data) {
162 int m_head = (mask_n_heads > 1)
163 ? (kvh_head + gqa_group) : 0;
164 mask_h = mask_data + (int64_t)m_head * mask_head_stride;
165 m_stride = mask_row_stride;
166 }
167 // Score at chunk offset i — original per-element math.
168 auto score = [&](int i) {
169 float s = KQ_row[i];
170 if (logit_softcap != 0.0f) {
171 s = logit_softcap * sycl::tanh(s);
172 }
173 if (mask_h) {
174 s += (float)mask_h[q_row * m_stride
175 + (chunk_start + i)];
176 }
177 return s;
178 };
179 // Pass 1: strided (coalesced) row-wise local maximum.
180 float local_max = -1e30f;
181 for (int i = local_id; i < chunk_size; i += local_size) {
182 float s = score(i);
183 if (s > local_max) local_max = s;
184 }
185 const float final_local_max = sycl::reduce_over_group(
186 item.get_group(), local_max, sycl::maximum<float>());
187 // Rescale previous accumulator by exp(old_max - new_max)
188 float old_max = KQ_max[jc_abs];
189 float new_max = (old_max > final_local_max) ? old_max : final_local_max;
190 float rescale = (old_max < -1e29f) ? 1.0f
191 : sycl::native::exp(old_max - new_max);
192 for (int v = local_id; v < DV; v += local_size) {
193 vkq[v] *= rescale;
194 }
195 // Pass 2: softmax numerators, strided; S row written once.
196 float local_sum = 0.0f;
197 for (int i = local_id; i < chunk_size; i += local_size) {
198 float s = score(i);
199 float val = sycl::native::exp(s - new_max);
200 S_row[i] = sycl::half(val);
201 local_sum += val;
202 }
203 const float total_sum = sycl::reduce_over_group(
204 item.get_group(), local_sum, sycl::plus<float>());
205 if (local_id == 0) {
206 KQ_sum[jc_abs] = KQ_sum[jc_abs] * rescale + total_sum;
207 KQ_max[jc_abs] = new_max;
208 }
209 });
210 });
211}
212
213// Write one GQA group's normalized output to its destination head.
214static void mkl_fa_normalize_head(
215 dpct::queue_ptr stream,
216 float * __restrict dst_batch,
217 const float * __restrict VKQ_accum,
218 const float * __restrict KQ_sum,
219 int iqh, int n_queries, int DV, int n_q_heads,
220 int64_t src_offset, int64_t wg_size) {
221
222 const int64_t wg = ((n_queries + wg_size - 1) / wg_size) * wg_size;
223
224 stream->submit([&](sycl::handler & cgh) {
225 cgh.parallel_for(sycl::nd_range<1>(wg, wg_size),
226 [=](sycl::nd_item<1> item) {
227 int jc = item.get_global_id(0);
228 if (jc >= n_queries) return;
229
230 int ksum_idx = (int)(src_offset / DV) + jc;
231 float inv_sum = 1.0f / KQ_sum[ksum_idx];
232 const float * __restrict src = VKQ_accum
233 + src_offset + jc * (int64_t)DV;
234 // Interleaved dst layout (matching TILE):
235 // rows alternate between heads, then increment query.
236 // offset = (query * n_q_heads + head) * DV
237 float * __restrict dst_row = dst_batch
238 + ((int64_t)jc * n_q_heads + iqh) * (int64_t)DV;
239
240 for (int v = 0; v < DV; v++) {
241 dst_row[v] = src[v] * inv_sum;
242 }
243 });
244 });
245}
246
247// ---------------------------------------------------------------------------
248// Per-chunk dequant
249//
250// Rather than dequantizing all of K/V up front (footprint scales with
251// context), we dequant one KV-head chunk at a time into a dense
252// [this_chunk x D] fp16 buffer (row-major, lda = D). The source address of
253// element (head=ikvh, row=chunk_start+r, col=c) decomposes into independent
254// linear terms head_off(ikvh) + row_off(chunk_start) + (r,c), so slicing a
255// chunk is a clean pointer offset in every layout case. The true-Gemma-
256// interleave vs padded-seq-view distinction is resolved once when the
257// descriptor is built; slicing does not reintroduce it.
258// ---------------------------------------------------------------------------
259enum mkl_fa_kv_desc_mode {
260 MKL_FA_KV_MODE_F16_DENSE = 0,
261 MKL_FA_KV_MODE_F16_INTERLEAVED = 1,
262 MKL_FA_KV_MODE_QUANT_CONTIG = 2,
263 MKL_FA_KV_MODE_QUANT_NC = 3,
264};
265
266struct mkl_fa_kv_desc {
267 const char * data = nullptr;
268 ggml_type type = GGML_TYPE_F16;
269 int64_t D = 0; // ne[0]
270 int64_t nb1 = 0; // byte stride, seq dim
271 int64_t nb2 = 0; // byte stride, head dim
272 int64_t nb3 = 0; // byte stride, batch dim
273 mkl_fa_kv_desc_mode mode = MKL_FA_KV_MODE_F16_DENSE;
274 int64_t ts = 0; // type size (mode 3 base offset)
275 int64_t s01 = 0; // nc row stride in blocks (mode 3)
276 int64_t s02 = 0; // nc head stride in blocks (mode 3)
277};
278
279static mkl_fa_kv_desc mkl_fa_make_desc(const ggml_tensor * T, bool interleaved) {
280 mkl_fa_kv_desc d;
281 d.data = (const char *)T->data;
282 d.type = T->type;
283 d.D = T->ne[0];
284 d.nb1 = (int64_t)T->nb[1];
285 d.nb2 = (int64_t)T->nb[2];
286 d.nb3 = (int64_t)T->nb[3];
287 d.ts = (int64_t)ggml_type_size(T->type);
288
289 if (T->type == GGML_TYPE_F16) {
290 // MLA's V cache is a 512-wide view of 576-wide K rows. Treat any
291 // padded row stride as strided even when there is only one KV head.
292 d.mode = interleaved || d.nb1 != d.D * (int64_t)sizeof(sycl::half)
293 ? MKL_FA_KV_MODE_F16_INTERLEAVED : MKL_FA_KV_MODE_F16_DENSE;
294 } else if (ggml_is_contiguously_allocated(T) && !interleaved) {
295 d.mode = MKL_FA_KV_MODE_QUANT_CONTIG;
296 } else {
297 d.mode = MKL_FA_KV_MODE_QUANT_NC;
298 d.s01 = d.nb1 / d.ts;
299 d.s02 = d.nb2 / d.ts;
300 }
301 return d;
302}
303
304// Dequant one KV-head chunk into a dense [this_chunk x D] fp16 buffer.
305static void mkl_fa_dequant_chunk(
306 dpct::queue_ptr stream, const mkl_fa_kv_desc & d, ggml_tensor * dst_ctx,
307 sycl::half * out, int ikvh, int ib, int chunk_start, int this_chunk) {
308
309 const int64_t D = d.D;
310 switch (d.mode) {
311 case MKL_FA_KV_MODE_F16_DENSE: {
312 // ib * nb3 selects this batch's KV (nb[3] != ne[1]*nb[1] for batched KV views)
313 const char * base = d.data + (int64_t)ikvh * d.nb2
314 + (int64_t)chunk_start * d.nb1 + (int64_t)ib * d.nb3;
315 stream->memcpy(out, base, (size_t)this_chunk * D * sizeof(sycl::half));
316 break;
317 }
318 case MKL_FA_KV_MODE_F16_INTERLEAVED: {
319 const char * base = d.data + (int64_t)ikvh * d.nb2
320 + (int64_t)chunk_start * d.nb1 + (int64_t)ib * d.nb3;
321 const int64_t row_halfs = d.nb1 / (int64_t)sizeof(sycl::half);
322 const sycl::half * src = (const sycl::half *)base;
323 stream->parallel_for(
324 sycl::range<2>((size_t)this_chunk, (size_t)D),
325 [=](sycl::item<2> it) {
326 int64_t r = it.get_id(0);
327 int64_t c = it.get_id(1);
328 out[r * D + c] = src[r * row_halfs + c];
329 });
330 break;
331 }
332 case MKL_FA_KV_MODE_QUANT_CONTIG: {
333 const char * base = d.data + (int64_t)ikvh * d.nb2
334 + (int64_t)chunk_start * d.nb1 + (int64_t)ib * d.nb3;
335 to_fp16_sycl_t to_fp16 = ggml_get_to_fp16_sycl(d.type, dst_ctx);
336 to_fp16(base, out, (int64_t)this_chunk * D, stream);
337 break;
338 }
339 default: { // MKL_FA_KV_MODE_QUANT_NC
340 to_fp16_nc_sycl_t to_fp16 = ggml_get_to_fp16_nc_sycl(d.type);
341 const int64_t base_blocks = (int64_t)ikvh * d.s02
342 + (int64_t)chunk_start * d.s01 + (int64_t)ib * d.nb3 / d.ts;
343 const char * base = d.data + base_blocks * d.ts;
344 // ne02 = ne03 = 1 → s02/s03 inert; head+chunk offset carried by base.
345 to_fp16(base, out, D, this_chunk, 1, 1, d.s01, d.s02, d.s02, stream);
346 break;
347 }
348 }
349}
350
351// ---------------------------------------------------------------------------
352// MKL Flash Attention orchestrator
353//
354// Pipeline: dequantize K/V → for each KV head:
355// pack GQA Q heads → MKL GEMM KQ → online softmax →
356// MKL GEMM VKQ → accumulate → normalize → scatter to dst
357// ---------------------------------------------------------------------------
358void ggml_sycl_flash_attn_ext_mkl(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
359
360 const ggml_tensor * Q = dst->src[0];
361 const ggml_tensor * K = dst->src[1];
362 const ggml_tensor * V = dst->src[2];
363 const ggml_tensor * mask = dst->src[3];
364 ggml_tensor * KQV = dst;
365
366 GGML_ASSERT(Q->type == GGML_TYPE_F32);
367 GGML_ASSERT(KQV->type == GGML_TYPE_F32);
368
369 // --- Op params ---
370 float scale = 1.0f, max_bias = 0.0f, logit_softcap = 0.0f;
371 memcpy(&scale, (const float *)KQV->op_params + 0, sizeof(float));
372 memcpy(&max_bias, (const float *)KQV->op_params + 1, sizeof(float));
373 memcpy(&logit_softcap, (const float *)KQV->op_params + 2, sizeof(float));
374
375 const float q_scale = scale;
376
377 // --- Dimensions ---
378 const int DKQ = (int)K->ne[0];
379 const int DV = (int)V->ne[0];
380 const int n_queries = (int)Q->ne[1];
381 const int n_q_heads = (int)Q->ne[2];
382 const int n_kv_heads = (int)K->ne[2];
383 const int n_batch = (int)Q->ne[3];
384 const int n_kv = (int)K->ne[1];
385 const int gqa_ratio = n_q_heads / n_kv_heads;
386 const int n_query_rows = n_queries * gqa_ratio;
387
388 GGML_ASSERT(n_q_heads % n_kv_heads == 0);
389 GGML_ASSERT(max_bias == 0.0f); // ALiBi not supported
390 GGML_ASSERT(Q->ne[3] == K->ne[3] || K->ne[3] == 1);
391
392 const int chunk_size = std::min(MKL_FA_CHUNK_SIZE_KV, n_kv);
393
394 // Query rows are processed in tiles of q_tile_rows so the score buffers
395 // (KQ_f32/S_f16 = q_tile_rows * chunk_size) stay bounded regardless of
396 // batch size. n_query_rows <= Q_TILE is a single tile (no extra work).
397 static int q_tile_env = ggml_sycl_get_env("GGML_SYCL_MKL_FA_Q_TILE", MKL_FA_Q_TILE);
398 const int q_tile_rows = std::max(1, std::min(q_tile_env, n_query_rows));
399
400 const int64_t wg_size = MKL_FA_WG_SIZE;
401
402 // --- Debug output (gated by GGML_SYCL_MKL_FA_DEBUG=1) ---
403 static int mkl_call_count = 0;
404 mkl_call_count++;
405 static int mkl_debug = ggml_sycl_get_env("GGML_SYCL_MKL_FA_DEBUG", 0);
406 const bool do_print = (mkl_debug == 1);
407
408 const int64_t q_row_stride = Q->nb[1] / sizeof(float);
409 const int64_t q_head_stride = Q->nb[2] / sizeof(float);
410
411 // Alias the dequantized buffers only when K and V expose the same values.
412 // MLA V is a narrower view of K and needs its own strided dequantization.
413 const bool V_is_K_view = V->ne[0] == K->ne[0] && V->view_src
414 && (V->view_src == K || (V->view_src == K->view_src
415 && V->view_offs == K->view_offs));
416
417 // Early interleaved detection for debug output.
418 // True interleaved detection happens after dequant (nb12_fp16 == nb11_fp16),
419 // but we can pre-detect on the original tensor strides.
420 const bool k_early_interleaved =
421 ((int64_t)K->ne[1] * K->nb[1] != K->nb[2]);
422 const bool v_early_interleaved =
423 !V_is_K_view && ((int64_t)V->ne[1] * V->nb[1] != V->nb[2]);
424
425 if (do_print) {
426 GGML_LOG_INFO("[MKL-FA] #%d D=%d DV=%d n_q=%d n_kv=%d "
427 "n_qh=%d n_kvh=%d gqa=%d batch=%d K=%s V=%s "
428 "chunk=%d buf=%.1fMB%s%s\n",
429 mkl_call_count, DKQ, DV, n_queries, n_kv,
430 n_q_heads, n_kv_heads, gqa_ratio, n_batch,
431 ggml_type_name(K->type), ggml_type_name(V->type),
432 chunk_size,
433 (double)((int64_t)n_query_rows * chunk_size * sizeof(float))
434 / (1024.0 * 1024.0),
435 k_early_interleaved ? " K_ILV" : "",
436 v_early_interleaved ? " V_ILV" : "");
437 GGML_LOG_INFO("[MKL-FA] #%d Q-nb1=%lld Q-nb2=%lld "
438 "q_rs=%lld q_hs=%lld dst_rs=%lld dst_hs=%lld\n",
439 mkl_call_count,
440 (long long)Q->nb[1], (long long)Q->nb[2],
441 (long long)q_row_stride, (long long)q_head_stride,
442 (long long)(KQV->nb[1] / sizeof(float)),
443 (long long)(KQV->nb[2] / sizeof(float)));
444 }
445
446 // --- Stream and allocators ---
447 dpct::queue_ptr stream = ctx.stream();
448
449#define MKL_TAKE_TIME(t0) auto t0 = std::chrono::steady_clock::now()
450#define MKL_ACCUM(acc, t0) do { if (do_print) { \
451 acc += (int64_t)std::chrono::duration_cast \
452 <std::chrono::microseconds>(std::chrono::steady_clock::now() - (t0)).count(); \
453} } while(0)
454
455 int64_t gemm_kq_time_us = 0;
456 int64_t gemm_vkq_time_us = 0;
457 int64_t softmax_time_us = 0;
458 int64_t dequant_time_us = 0;
459
460 MKL_TAKE_TIME(t_deq);
461
462 // --- K/V dequant descriptors ---
463 // Dequant is done per-chunk inside the KV loop (footprint independent of
464 // context). Output is always dense row-major fp16 [this_chunk x D], lda=D.
465 // Interleaved detection: ne[1]*nb[1] != nb[2] means heads are interleaved.
466 const bool k_interleaved =
467 ((int64_t)K->ne[1] * K->nb[1] != K->nb[2]) && K->ne[2] > 1;
468 const bool v_interleaved =
469 ((int64_t)V->ne[1] * V->nb[1] != V->nb[2]) && V->ne[2] > 1;
470
471 const mkl_fa_kv_desc K_desc = mkl_fa_make_desc(K, k_interleaved);
472 const mkl_fa_kv_desc V_desc = V_is_K_view
473 ? K_desc : mkl_fa_make_desc(V, v_interleaved);
474
475 MKL_ACCUM(dequant_time_us, t_deq);
476
477 // --- Resolve mask pointers ---
478 int64_t mask_head_stride = 0;
479 int64_t mask_row_stride = 0;
480 int mask_n_heads = 0;
481
482 if (mask) {
483 // Use actual fp16 device size (2 bytes), NOT sizeof(sycl::half)
484 // which may be 4 on the host in oneAPI.
485 mask_head_stride = mask->nb[2] / 2;
486 mask_row_stride = mask->nb[1] / 2;
487 mask_n_heads = (int)mask->ne[2];
488 }
489
490 // --- Allocate intermediates from pool ---
491 ggml_sycl_pool & pool = ctx.pool();
492
493 ggml_sycl_pool_alloc<float> KQ_f32(pool); // [q_tile_rows x chunk]
494 ggml_sycl_pool_alloc<sycl::half> S_f16(pool); // [q_tile_rows x chunk]
495 ggml_sycl_pool_alloc<float> VKQ_chunk(pool); // [q_tile_rows x DV]
496 ggml_sycl_pool_alloc<float> VKQ_accum(pool); // [n_query_rows x DV] (full)
497 ggml_sycl_pool_alloc<float> KQ_max(pool); // [n_query_rows] (full)
498 ggml_sycl_pool_alloc<float> KQ_sum(pool); // [n_query_rows] (full)
499 ggml_sycl_pool_alloc<sycl::half> Q_head_f16(pool); // [n_query_rows x DKQ] (full)
500 ggml_sycl_pool_alloc<sycl::half> K_chunk_f16(pool); // [chunk x DKQ] (per-chunk dequant)
501 ggml_sycl_pool_alloc<sycl::half> V_chunk_f16(pool); // [chunk x DV] (per-chunk dequant)
502
503 KQ_f32.alloc((size_t)q_tile_rows * chunk_size);
504 S_f16.alloc((size_t)q_tile_rows * chunk_size);
505 VKQ_chunk.alloc((size_t)q_tile_rows * DV);
506 VKQ_accum.alloc((size_t)n_query_rows * DV);
507 KQ_max.alloc(n_query_rows);
508 KQ_sum.alloc(n_query_rows);
509 Q_head_f16.alloc((size_t)n_query_rows * DKQ);
510 K_chunk_f16.alloc((size_t)chunk_size * DKQ);
511
512 sycl::half * V_chunk_f16_ptr;
513 if (V_is_K_view) {
514 V_chunk_f16_ptr = K_chunk_f16.ptr; // V aliases K (DV == DKQ)
515 } else {
516 V_chunk_f16.alloc((size_t)chunk_size * DV);
517 V_chunk_f16_ptr = V_chunk_f16.ptr;
518 }
519
520 sycl::half * Q_head_f16_ptr = Q_head_f16.ptr;
521 float * KQ_f32_ptr = KQ_f32.ptr;
522 sycl::half * S_f16_ptr = S_f16.ptr;
523 float * VKQ_chunk_ptr = VKQ_chunk.ptr;
524 float * VKQ_accum_ptr = VKQ_accum.ptr;
525 float * KQ_max_ptr = KQ_max.ptr;
526 float * KQ_sum_ptr = KQ_sum.ptr;
527 sycl::half * K_chunk_f16_ptr = K_chunk_f16.ptr;
528
529 const float alpha = 1.0f;
530 const float beta = 0.0f;
531
532 for (int ib = 0; ib < n_batch; ib++) {
533 const float * Q_batch = (const float *)Q->data
534 + ib * (Q->nb[3] / sizeof(float));
535 float * dst_batch = (float *)KQV->data
536 + ib * (KQV->nb[3] / sizeof(float));
537
538 const sycl::half * mask_batch = nullptr;
539 if (mask) {
540 int m_batch = (mask->ne[3] > 1) ? ib : 0;
541 mask_batch = (const sycl::half *)mask->data
542 + m_batch * (mask->nb[3] / 2); // 2 = actual fp16 device size
543 }
544
545 for (int ikvh = 0; ikvh < n_kv_heads; ikvh++) {
546 int kvh_base_head = ikvh * gqa_ratio;
547
548 // 1. Pack all GQA Q heads into fp16 (full n_query_rows)
549 mkl_fa_pack_q_fp16(stream,
550 Q_head_f16_ptr, Q_batch,
551 n_queries, DKQ,
552 gqa_ratio, kvh_base_head,
553 q_scale, q_row_stride, q_head_stride, wg_size);
554
555 // 2. Initialize softmax state (full n_query_rows)
556 mkl_fa_init_softmax_state(stream,
557 KQ_max_ptr, KQ_sum_ptr, VKQ_accum_ptr,
558 n_query_rows, DV, wg_size);
559
560 // 3. KV chunk loop (OUTER): dequant each chunk once, then tile queries.
561 for (int chunk_start = 0; chunk_start < n_kv; chunk_start += chunk_size) {
562 int this_chunk = std::min(chunk_size, n_kv - chunk_start);
563
564 // 3a. Dequant this KV chunk to dense fp16 (once per chunk)
565 {
566 MKL_TAKE_TIME(t0);
567 mkl_fa_dequant_chunk(stream, K_desc, KQV,
568 K_chunk_f16_ptr, ikvh, ib, chunk_start, this_chunk);
569 if (!V_is_K_view) {
570 mkl_fa_dequant_chunk(stream, V_desc, KQV,
571 V_chunk_f16_ptr, ikvh, ib, chunk_start, this_chunk);
572 }
573 MKL_ACCUM(dequant_time_us, t0);
574 }
575
576 // 3b. Query tile loop (INNER) — bounds KQ_f32/S_f16 footprint.
577 for (int q0 = 0; q0 < n_query_rows; q0 += q_tile_rows) {
578 int q_rows = std::min(q_tile_rows, n_query_rows - q0);
579 sycl::event kq_done, vkq_done;
580
581 // GEMM: KQ = Q_tile × K_chunk^T
582 {
583 MKL_TAKE_TIME(t0);
584 kq_done = gemm(*stream,
585 transpose::trans, transpose::nontrans,
586 this_chunk, q_rows, DKQ,
587 alpha,
588 K_chunk_f16_ptr, DKQ,
589 Q_head_f16_ptr + (int64_t)q0 * DKQ, DKQ,
590 beta,
591 KQ_f32_ptr, this_chunk,
592 std::vector<sycl::event>{*stream->ext_oneapi_get_last_event()});
593 MKL_ACCUM(gemm_kq_time_us, t0);
594 }
595 // Online softmax over this chunk for this query tile
596 {
597 MKL_TAKE_TIME(t0);
598 mkl_fa_online_softmax_chunk(stream,
599 KQ_f32_ptr, S_f16_ptr,
600 KQ_max_ptr, KQ_sum_ptr, VKQ_accum_ptr,
601 q0, q_rows, n_queries, DV,
602 this_chunk, chunk_start,
603 kvh_base_head,
604 mask_batch, mask_head_stride,
605 mask_row_stride, mask_n_heads,
606 logit_softcap, wg_size, kq_done);
607 MKL_ACCUM(softmax_time_us, t0);
608 }
609
610 // GEMM: VKQ_chunk = S × V_chunk
611 {
612 MKL_TAKE_TIME(t0);
613 vkq_done = gemm(*stream,
614 transpose::nontrans, transpose::nontrans,
615 DV, q_rows, this_chunk,
616 alpha,
617 V_chunk_f16_ptr, DV,
618 S_f16_ptr, this_chunk,
619 beta,
620 VKQ_chunk_ptr, DV,
621 std::vector<sycl::event>{*stream->ext_oneapi_get_last_event()});
622 MKL_ACCUM(gemm_vkq_time_us, t0);
623 }
624 // VKQ_accum[q0..] += VKQ_chunk
625 {
626 const int64_t n_total = (int64_t)q_rows * DV;
627 const int64_t wg = ((n_total + wg_size - 1) / wg_size)
628 * wg_size;
629 float * accum = VKQ_accum_ptr + (int64_t)q0 * DV;
630 stream->submit([&](sycl::handler & cgh) {
631 cgh.depends_on(vkq_done);
632 cgh.parallel_for(sycl::nd_range<1>(wg, wg_size),
633 [=](sycl::nd_item<1> item) {
634 int64_t i = item.get_global_id(0);
635 if (i < n_total) {
636 accum[i] += VKQ_chunk_ptr[i];
637 }
638 });
639 });
640 }
641 }
642 }
643
644 // 4. Normalize and scatter each GQA head to dst
645 for (int iqg = 0; iqg < gqa_ratio; iqg++) {
646 int iqh = kvh_base_head + iqg;
647 int64_t src_offset = (int64_t)iqg * n_queries * DV;
648 mkl_fa_normalize_head(stream,
649 dst_batch, VKQ_accum_ptr, KQ_sum_ptr,
650 iqh, n_queries, DV, n_q_heads,
651 src_offset, wg_size);
652 }
653 }
654 }
655
656#undef MKL_TAKE_TIME
657#undef MKL_ACCUM
658
659 if (do_print) {
660 const int64_t v_chunk_elems = V_is_K_view ? 0 : (int64_t)chunk_size * DV;
661 double total_mb = (double)(
662 (int64_t)q_tile_rows * chunk_size * sizeof(float) // KQ_f32
663 + (int64_t)q_tile_rows * chunk_size * sizeof(sycl::half) // S_f16
664 + (int64_t)q_tile_rows * DV * sizeof(float) // VKQ_chunk
665 + (int64_t)n_query_rows * DV * sizeof(float) // VKQ_accum
666 + (int64_t)n_query_rows * sizeof(float) // KQ_max
667 + (int64_t)n_query_rows * sizeof(float) // KQ_sum
668 + (int64_t)n_query_rows * DKQ * sizeof(sycl::half) // Q_head_f16
669 + (int64_t)chunk_size * DKQ * sizeof(sycl::half) // K_chunk_f16
670 + v_chunk_elems * (int64_t)sizeof(sycl::half) // V_chunk_f16
671 ) / (1024.0 * 1024.0);
672 GGML_LOG_INFO("[MKL-FA] #%d n_kv=%d n_q=%d q_tile=%d time_us: "
673 "dequant=%lld GEMM_KQ=%lld softmax=%lld GEMM_VKQ=%lld "
674 "buf_mb=%.1f\n",
675 mkl_call_count, n_kv, n_queries, q_tile_rows,
676 (long long)dequant_time_us,
677 (long long)gemm_kq_time_us,
678 (long long)softmax_time_us,
679 (long long)gemm_vkq_time_us,
680 total_mb);
681 }
682}