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 / fused-gemm.cpp

1099 lines · 53575 bytes Raw Blame History
1#include "fused-gemm.hpp"
2
3#include <sycl/ext/oneapi/matrix/matrix.hpp>
4
5#include <algorithm>
6#include <string>
7#include <tuple>
8#include <mutex>
9#include <set>
10#include <unordered_map>
11
12namespace mx = sycl::ext::oneapi::experimental::matrix;
13
14// FG_ / fg_ is short for fused GEMM: the weights are dequantized inside the GEMM, into the XMX tiles.
15
16// A k step is one 32-value weight sub-block; iq3_s and the other superblock formats split their
17// superblock into steps of this width. The sub-groups of a work-group each walk their own K range
18// and are summed at the end.
19static constexpr int FG_BK = QK4_NL;
20static constexpr int FG_KSPLIT = 4;
21
22// Element traits of one joint_matrix operand type. The A stage and the B pack compute in f32 and
23// convert once, in registers, when they write the element, so any type costs the same one pass.
24// store: storage in SLM (A) and in the packed B buffer
25// mtype: matrix_type in matrix_combinations
26// mode: GGML_SYCL_DYNAMIC_PRECISION value that selects this type
27// src: ggml type that needs no conversion into this type (GGML_TYPE_COUNT: none)
28// slow: XMX throughput class, 0 is fastest. f16 and bf16 share the DPAS rate; tf32 does half the
29// K per instruction. B60, Qwen3-30B-A3B pp512: f16 1108, bf16 1000, tf32 751 t/s
30template <typename T> struct fg_elem;
31
32template <> struct fg_elem<sycl::half> {
33 using store = sycl::half;
34 using pair = sycl::half2;
35 static constexpr mx::matrix_type mtype = mx::matrix_type::fp16;
36 static constexpr int mode = GGML_SYCL_DYNAMIC_PRECISION_F16;
37 static constexpr ggml_type src = GGML_TYPE_F16;
38 static constexpr int mant = 10;
39 static constexpr int slow = 0;
40 static store cvt(float x) { return (store) x; }
41 static pair make(float x, float y) { return pair((store) x, (store) y); }
42};
43
44// tf32 rounds to nearest even with plain bit ops: round_to_tf32 needs a SPIR-V extension that the
45// DG2 AOT target rejects
46static inline uint32_t fg_round_bits(float x, int drop) {
47 const uint32_t u = sycl::bit_cast<uint32_t>(x);
48 if ((u & 0x7f800000u) == 0x7f800000u) {
49 return (u & 0x7fffffu) ? u | (1u << drop) : u; // nan stays nan
50 }
51 return u + ((1u << (drop - 1)) - 1) + ((u >> drop) & 1);
52}
53
54struct alignas(4) fg_bf16x2 {
55 sycl::ext::oneapi::bfloat16 x, y;
56};
57
58template <> struct fg_elem<sycl::ext::oneapi::bfloat16> {
59 using store = sycl::ext::oneapi::bfloat16;
60 using pair = fg_bf16x2;
61 static constexpr mx::matrix_type mtype = mx::matrix_type::bf16;
62 static constexpr int mode = GGML_SYCL_DYNAMIC_PRECISION_BF16;
63 static constexpr ggml_type src = GGML_TYPE_BF16;
64 static constexpr int mant = 7;
65 static constexpr int slow = 0;
66 static store cvt(float x) { return store(x); }
67 static pair make(float x, float y) { return { cvt(x), cvt(y) }; }
68};
69
70// tf32 keeps f32 range and f16 mantissa, in f32 storage
71template <> struct fg_elem<mx::precision::tf32> {
72 using store = float;
73 using pair = sycl::float2;
74 static constexpr mx::matrix_type mtype = mx::matrix_type::tf32;
75 static constexpr int mode = GGML_SYCL_DYNAMIC_PRECISION_TF32;
76 static constexpr ggml_type src = GGML_TYPE_COUNT;
77 static constexpr int mant = 10;
78 static constexpr int slow = 1;
79 static store cvt(float x) { return sycl::bit_cast<float>(fg_round_bits(x, 13) & ~0x1fffu); }
80 static pair make(float x, float y) { return pair(cvt(x), cvt(y)); }
81};
82
83// One joint_matrix combination (A type, B type, TM x TN x TK, sub-group size; C and D are f32) and
84// the tiling built on it. A sub-group owns SG_ROWS rows of A (at least 16) and BN (at least 32)
85// columns of B. A and B may differ: the device lists the pairs it supports.
86template <typename TA, typename TB, int TM_, int TN_, int TK_, int SG_> struct fg_combo {
87 using ta = TA;
88 using tb = TB;
89 using EA = fg_elem<TA>;
90 using EB = fg_elem<TB>;
91 using tsa = typename EA::store;
92 using tsb = typename EB::store;
93 static constexpr int TM = TM_;
94 static constexpr int TN = TN_;
95 static constexpr int TK = TK_;
96 static constexpr int SG = SG_;
97 static constexpr int VNNI = 4 / sizeof(tsb); // K rows of B packed in one 32-bit word
98 static constexpr int SG_ROWS = TM > 16 ? TM : 16;
99 static constexpr int RPL = SG_ROWS / SG; // A rows one lane decodes per k step
100 static constexpr int MT = SG_ROWS / TM;
101 static constexpr int BN = TN > 32 ? TN : 32;
102 static constexpr int NT = BN / TN;
103 static constexpr int WG_SIZE = FG_KSPLIT * SG;
104 static constexpr mx::layout b_layout = VNNI == 1 ? mx::layout::row_major : mx::layout::ext_intel_packed;
105 // a 64-wide N is mostly padding here and a 32x64 f32 accumulator needs 128 registers per lane,
106 // so it spills: 13x slower on B60
107 static constexpr bool efficient = TN <= 32;
108 static_assert(SG_ROWS % SG == 0 && SG_ROWS % TM == 0 && BN % TN == 0 && FG_BK % TK == 0, "bad tile");
109 static_assert(BN <= GGML_SYCL_FG_MAX_N, "header gate must cover the tile width");
110};
111
112using fg_half = sycl::half;
113using fg_bf16 = sycl::ext::oneapi::bfloat16;
114using fg_tf32 = mx::precision::tf32;
115
116// One bit of GGML_SYCL_XMX_GATHER_SHAPES per combination. Only combinations some device lists in
117// matrix_combinations are built (appendix of sycl_ext_oneapi_matrix and the runtime's own list).
118template <typename F> static void fg_visit_combo(int idx, F && f);
119static constexpr int FG_N_COMBOS = 8;
120
121// A spir64_gen AOT build (GGML_SYCL_XMX_AOT_SG) drops the combinations of the other sub-group size
122// entirely: ocloc rejects even an empty kernel that asks for a sub-group size it lacks.
123template <int SG> static constexpr bool fg_listed() {
124#if defined(GGML_SYCL_XMX_AOT_SG)
125 return SG == GGML_SYCL_XMX_AOT_SG;
126#else
127 return true;
128#endif
129}
130
131template <typename S, typename F> static void fg_call_combo(F && f) {
132 if constexpr (fg_listed<S::SG>()) {
133 f(S{});
134 }
135}
136
137template <typename F> static void fg_visit_combo(int idx, F && f) {
138 switch (idx) {
139 case 0: fg_call_combo<fg_combo<fg_half, fg_half, 8, 16, 16, 16>>(f); break; // Xe2, Xe3, Xe-HPC
140 case 1: fg_call_combo<fg_combo<fg_half, fg_half, 16, 16, 16, 16>>(f); break; // Xe2, Xe3, Xe-HPC
141 case 2: fg_call_combo<fg_combo<fg_half, fg_half, 32, 64, 16, 16>>(f); break; // Xe2, Xe3, Xe-HPC
142 case 3: fg_call_combo<fg_combo<fg_half, fg_half, 32, 64, 32, 16>>(f); break; // Xe2, Xe3, Xe-HPC
143 case 4: fg_call_combo<fg_combo<fg_half, fg_half, 8, 8, 16, 8>>(f); break; // Xe-HPG (Arc A), ARL-H
144 case 5: fg_call_combo<fg_combo<fg_tf32, fg_tf32, 8, 16, 8, 16>>(f); break; // Xe2, Xe3, Xe-HPC
145 case 6: fg_call_combo<fg_combo<fg_bf16, fg_bf16, 8, 16, 16, 16>>(f); break; // Xe2, Xe3, Xe-HPC
146 case 7: fg_call_combo<fg_combo<fg_bf16, fg_bf16, 8, 8, 16, 8>>(f); break; // Xe-HPG (Arc A), ARL-H
147 default: GGML_ABORT("bad XMX combination %d", idx);
148 }
149}
150
151// AOT with -fsycl-targets=intel_gpu_*: compile each tile body only for targets with its sub-group
152// size, since IGC fails on the other ones. A JIT build keeps them all, but each combination lands in
153// its own device image (joint_matrix is an optional kernel feature) and only a combination the
154// device reports is launched, so the runtime never asks IGC for the others.
155#if defined(__SYCL_DEVICE_ONLY__)
156# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \
157 __SYCL_TARGET_INTEL_GPU_ARL_H__
158# define FG_AOT_SG 8
159# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \
160 __SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \
161 __SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \
162 __SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__
163# define FG_AOT_SG 16
164# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \
165 __SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \
166 __SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__
167# define FG_AOT_SG 0 // no XMX
168# endif
169#endif
170
171template <int SG> static constexpr bool fg_built() {
172#if defined(FG_AOT_SG)
173 return SG == FG_AOT_SG;
174#else
175 return true;
176#endif
177}
178
179// Upper bound on the tile count when total_rows rows are routed to n_as experts: the worst case gives
180// each expert one row and fills whole tiles with the rest. The bound depends only on the shape, not
181// on the routing, so the pool reuses one buffer every ubatch instead of keeping one per size seen.
182static constexpr int64_t grouped_gemm_max_tiles(int64_t total_rows, int64_t n_as, int64_t BN) {
183 return total_rows <= n_as ? total_rows : n_as + (total_rows - n_as) / BN;
184}
185// Tiles do not cross experts, so the bound is not ceil(total_rows / BN): 34 rows over 2 experts with
186// BN = 16 split 17 + 17 need 2 + 2 tiles, where the ceil gives 3.
187static_assert(grouped_gemm_max_tiles(34, 2, 16) == 4);
188
189// the device lists S with an f32 accumulator and output
190template <typename S> static bool fg_device_has_combo(const std::vector<mx::combination> & combinations) {
191 for (const auto & c : combinations) {
192 if (c.atype == S::EA::mtype && c.btype == S::EB::mtype && c.ctype == mx::matrix_type::fp32 &&
193 c.dtype == mx::matrix_type::fp32 &&
194 (c.max_msize >= (size_t) S::TM || c.msize == (size_t) S::TM) &&
195 (c.max_nsize >= (size_t) S::TN || c.nsize == (size_t) S::TN) &&
196 (c.max_ksize >= (size_t) S::TK || c.ksize == (size_t) S::TK)) {
197 return true;
198 }
199 }
200 return false;
201}
202
203template <typename T> static const char * fg_type_name() {
204 return std::is_same_v<T, fg_half> ? "f16" : std::is_same_v<T, fg_bf16> ? "bf16" : "tf32";
205}
206
207static std::string fg_combo_name(int idx) {
208 std::string name;
209 fg_visit_combo(idx, [&](auto s) {
210 using S = decltype(s);
211 name = std::string(fg_type_name<typename S::ta>()) + "x" + fg_type_name<typename S::tb>() + " " +
212 std::to_string(S::TM) + "x" + std::to_string(S::TN) + "x" + std::to_string(S::TK) + " sg" +
213 std::to_string(S::SG);
214 });
215 return name;
216}
217
218// Combinations this build has kernels for and the device lists, one bit each. Cached per device:
219// on a mixed box the first caller's verdict is not the others'.
220static int fg_device_combos(const sycl::device & dev) {
221 static std::mutex mtx;
222 static std::unordered_map<sycl::device, int> known;
223 std::lock_guard<std::mutex> lock(mtx);
224 const auto it = known.find(dev);
225 if (it != known.end()) {
226 return it->second;
227 }
228 int available = 0;
229 try {
230 const auto combinations = dev.get_info<sycl::ext::oneapi::experimental::info::device::matrix_combinations>();
231 const auto sg_sizes = dev.get_info<sycl::info::device::sub_group_sizes>();
232 for (int idx = 0; idx < FG_N_COMBOS; ++idx) {
233 fg_visit_combo(idx, [&](auto s) {
234 using S = decltype(s);
235 const bool sg_ok = std::find(sg_sizes.begin(), sg_sizes.end(), (size_t) S::SG) != sg_sizes.end();
236 if (sg_ok && fg_device_has_combo<S>(combinations)) {
237 available |= 1 << idx;
238 }
239 });
240 }
241 } catch (const sycl::exception &) {
242 available = 0;
243 }
244 GGML_LOG_INFO("%s: %s: XMX dequant-GEMM combinations available 0x%x, allowed 0x%x\n", __func__,
245 dev.get_info<sycl::info::device::name>().c_str(), available, g_ggml_sycl_xmx_gather_shapes);
246 known.emplace(dev, available);
247 return available;
248}
249
250// Rank of combination S for a src1 of type src1_type, lower is better. Order:
251// 1. throughput: a tile that does not spill, then the fastest type class of A and B
252// 2. B type equal to the src1 type, so the pack is a plain copy
253// 3. B at least as precise as f16
254// 4. the device's native DPAS tile (8 x SG x 32 bytes of K), then the largest M x K
255// A costs nothing to convert: the A stage emits any type at the same cost.
256template <typename S> static int64_t fg_rank(ggml_type src1_type) {
257 const int64_t spills = !S::efficient;
258 const int64_t slow = std::max(S::EA::slow, S::EB::slow);
259 const int64_t convert = S::EB::src != src1_type;
260 const int64_t lossy = S::EB::mant < 10;
261 const int64_t foreign = !(S::TM == 8 && S::TN == S::SG);
262 const int64_t mk = 1024 - S::TM * S::TK;
263 return ((((spills * 2 + slow) * 2 + convert) * 2 + lossy) * 2 + foreign) * 2048 + mk;
264}
265
266// whether XMX operands of type mode (a GGML_SYCL_DYNAMIC_PRECISION value) meet the src1 request
267// [TAG_GGML_PREC]. f16 lacks the f32 range that BF16 and F32 ask for; an F32 request goes only as far
268// down as GGML_SYCL_DYNAMIC_REQUIRED_PRECISION allows.
269static bool fg_mode_meets(int mode, int32_t src1_prec) {
270 if (src1_prec == GGML_PREC_UNDEFINED || src1_prec >= GGML_PREC_F16) {
271 return true;
272 }
273 if (src1_prec >= GGML_PREC_BF16) {
274 return mode != GGML_SYCL_DYNAMIC_PRECISION_F16;
275 }
276 switch (g_ggml_sycl_dynamic_required_precision) {
277 case GGML_SYCL_DYNAMIC_PRECISION_TF32: return mode == GGML_SYCL_DYNAMIC_PRECISION_TF32;
278 case GGML_SYCL_DYNAMIC_PRECISION_BF16: return mode != GGML_SYCL_DYNAMIC_PRECISION_F16;
279 default: return false;
280 }
281}
282
283// Best allowed combination for this call, or -1 if none. The type is GGML_SYCL_DYNAMIC_PRECISION if it
284// meets the src1 request; if not, bf16 then tf32 for a BF16 request (fastest first) and tf32 then bf16
285// for an F32 request (most mantissa first).
286static int fg_pick_combo(dpct::queue_ptr stream, ggml_type src1_type, int32_t src1_prec) {
287 const sycl::device dev = stream->get_device();
288 const int allowed = fg_device_combos(dev) & g_ggml_sycl_xmx_gather_shapes;
289 const bool f32_req = src1_prec != GGML_PREC_UNDEFINED && src1_prec < GGML_PREC_BF16;
290 const int modes[] = {
291 g_ggml_sycl_dynamic_precision,
292 f32_req ? GGML_SYCL_DYNAMIC_PRECISION_TF32 : GGML_SYCL_DYNAMIC_PRECISION_BF16,
293 f32_req ? GGML_SYCL_DYNAMIC_PRECISION_BF16 : GGML_SYCL_DYNAMIC_PRECISION_TF32,
294 };
295 int best = -1;
296 int64_t best_rank = 0;
297 for (int i = 0; i < 3 && best < 0; ++i) {
298 const int mode = modes[i];
299 if (!fg_mode_meets(mode, src1_prec)) {
300 continue;
301 }
302 for (int idx = 0; idx < FG_N_COMBOS; ++idx) {
303 if (!(allowed & (1 << idx))) {
304 continue;
305 }
306 fg_visit_combo(idx, [&](auto s) {
307 using S = decltype(s);
308 if (S::EA::mode != mode || S::EB::mode != mode) {
309 return;
310 }
311 const int64_t rank = fg_rank<S>(src1_type);
312 if (best < 0 || rank < best_rank) {
313 best = idx;
314 best_rank = rank;
315 }
316 });
317 }
318 }
319 // log each distinct decision once
320 static std::mutex mtx;
321 static std::set<std::tuple<size_t, int, int32_t, int>> seen;
322 std::lock_guard<std::mutex> lock(mtx);
323 if (seen.emplace(std::hash<sycl::device>{}(dev), (int) src1_type, src1_prec, best).second) {
324 GGML_LOG_INFO("%s: src1 %s, src1 prec %d -> %s\n", __func__, ggml_type_name(src1_type), src1_prec,
325 best >= 0 ? fg_combo_name(best).c_str() : "none (library GEMM)");
326 }
327 return best;
328}
329
330// src1 [N][K] -> packed [K/V][Npad][V] so B tiles load straight from global memory
331template <typename E, typename T_src>
332static void fused_gemm_pack_b(const T_src * y, typename E::store * packed, int N, int Npad, int K,
333 dpct::queue_ptr stream) {
334 constexpr int V = 4 / sizeof(typename E::store);
335 const int kqs = K / V;
336 stream->parallel_for(sycl::range<1>((size_t) Npad * kqs), [=](sycl::id<1> id) {
337 const int idx = id[0];
338 const int n = idx / kqs;
339 const int kq = idx - n * kqs;
340 typename E::store vals[V] = {};
341 if (n < N) {
342 const T_src * src = y + (size_t) n * K + V * kq;
343#pragma unroll
344 for (int v = 0; v < V; ++v) {
345 vals[v] = E::cvt((float) src[v]);
346 }
347 }
348 typename E::store * out = packed + ((size_t) kq * Npad + n) * V;
349#pragma unroll
350 for (int v = 0; v < V; ++v) {
351 out[v] = vals[v];
352 }
353 });
354}
355
356// A stage: one lane owns one row and decodes FG_BK values of it per k step, with every scale
357// folded into the value so the mad below sees plain A elements. One overload per weight format.
358template <typename E>
359static __dpct_inline__ void fg_stage_a(const block_iq4_nl * __restrict__ xrow, const int kb, typename E::pair * a) {
360 const block_iq4_nl blk = xrow[kb];
361 const float d = (float) blk.d;
362#pragma unroll
363 for (int j = 0; j < QK4_NL / 2; j += 2) {
364 const uint8_t q0 = blk.qs[j];
365 const uint8_t q1 = blk.qs[j + 1];
366 a[j / 2] = E::make(d * kvalues_iq4nl[q0 & 0xf], d * kvalues_iq4nl[q1 & 0xf]);
367 a[j / 2 + 8] = E::make(d * kvalues_iq4nl[q0 >> 4], d * kvalues_iq4nl[q1 >> 4]);
368 }
369}
370
371// iq3_s: k step kb is sub-block kb % 8 of superblock kb / 8. The superblock is 110 bytes, so read
372// only the fields of that sub-block instead of copying the block. Same decode as
373// dequantize_block_iq3_s: grid entries are taken as dwords and the sign bit is a plain shift.
374template <typename E>
375static __dpct_inline__ void fg_stage_a(const block_iq3_s * __restrict__ xrow, const int kb, typename E::pair * a) {
376 static_assert(QK_K == 256, "the iq3_s A stage assumes 8 sub-blocks per superblock");
377 const block_iq3_s * blk = xrow + kb / (QK_K / 32);
378 const int ib8 = kb % (QK_K / 32);
379 const uint8_t * qs = blk->qs + 8 * ib8;
380 const int qh = blk->qh[ib8];
381 const float d = (float) blk->d * (1 + 2 * ((blk->scales[ib8 / 2] >> (4 * (ib8 % 2))) & 0xf));
382#pragma unroll
383 for (int il = 0; il < 4; ++il) {
384 const uint32_t grid1 = iq3s_grid[qs[2 * il + 0] | ((qh << (8 - 2 * il)) & 256)];
385 const uint32_t grid2 = iq3s_grid[qs[2 * il + 1] | ((qh << (7 - 2 * il)) & 256)];
386 const int signs = blk->signs[4 * ib8 + il];
387#pragma unroll
388 for (int j = 0; j < 2; ++j) {
389 const float g1a = (float) ((grid1 >> (16 * j + 0)) & 0xff);
390 const float g1b = (float) ((grid1 >> (16 * j + 8)) & 0xff);
391 const float g2a = (float) ((grid2 >> (16 * j + 0)) & 0xff);
392 const float g2b = (float) ((grid2 >> (16 * j + 8)) & 0xff);
393 const int s = 2 * j;
394 a[4 * il + j] = E::make(d * ((signs & (1 << (s + 0))) ? -g1a : g1a),
395 d * ((signs & (1 << (s + 1))) ? -g1b : g1b));
396 a[4 * il + j + 2] = E::make(d * ((signs & (1 << (s + 4))) ? -g2a : g2a),
397 d * ((signs & (1 << (s + 5))) ? -g2b : g2b));
398 }
399 }
400}
401
402// values per stored block, so a row of K values is K/qk blocks
403template <typename block_q_t> struct fg_block_traits;
404template <> struct fg_block_traits<block_iq4_nl> { static constexpr int qk = QK4_NL; };
405template <> struct fg_block_traits<block_iq3_s> { static constexpr int qk = QK_K; };
406template <> struct fg_block_traits<block_iq3_xxs> { static constexpr int qk = QK_K; };
407template <> struct fg_block_traits<block_iq4_xs> { static constexpr int qk = QK_K; };
408template <> struct fg_block_traits<block_iq2_xxs> { static constexpr int qk = QK_K; };
409template <> struct fg_block_traits<block_iq2_xs> { static constexpr int qk = QK_K; };
410template <> struct fg_block_traits<block_iq2_s> { static constexpr int qk = QK_K; };
411template <> struct fg_block_traits<block_iq1_s> { static constexpr int qk = QK_K; };
412template <> struct fg_block_traits<block_iq1_m> { static constexpr int qk = QK_K; };
413template <> struct fg_block_traits<block_q8_0> { static constexpr int qk = QK8_0; };
414template <> struct fg_block_traits<block_q4_K> { static constexpr int qk = QK_K; };
415template <> struct fg_block_traits<block_q5_K> { static constexpr int qk = QK_K; };
416template <> struct fg_block_traits<block_q6_K> { static constexpr int qk = QK_K; };
417
418// The A stages below are the dequantize_block_iq* kernels rewritten for one k step. There a
419// work-item handled one quarter (il) of one 32-wide sub-block (ib); here one lane produces the
420// whole step, so il becomes a loop and ib is kb inside the superblock. Each quarter yields 8
421// consecutive values, i.e. 4 pairs at a[4*il], so nothing larger than 8 floats is ever live.
422#define FG_SUPERBLOCK(T) \
423 static_assert(QK_K == 256, "the " #T " A stage assumes 8 sub-blocks per superblock"); \
424 const T * blk = xrow + kb / (QK_K / 32); \
425 const int ib = kb % (QK_K / 32)
426
427template <typename E>
428static __dpct_inline__ void fg_pack_quarter(const float * __restrict__ t, typename E::pair * a, int il) {
429#pragma unroll
430 for (int j = 0; j < 4; ++j) {
431 a[4 * il + j] = E::make(t[2 * j], t[2 * j + 1]);
432 }
433}
434
435template <typename E>
436static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) {
437 FG_SUPERBLOCK(block_iq4_xs);
438 // low nibbles fill the first half of the step, high nibbles the second, so the two halves
439 // land at a[0..7] and a[8..15] and no quarter loop is needed
440 const float d = (float) blk->d *
441 ((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32);
442 const uint8_t * q4 = blk->qs + 16 * ib;
443#pragma unroll
444 for (int j = 0; j < 8; ++j) {
445 a[j] = E::make(d * kvalues_iq4nl[q4[2 * j] & 0xf], d * kvalues_iq4nl[q4[2 * j + 1] & 0xf]);
446 a[8 + j] = E::make(d * kvalues_iq4nl[q4[2 * j] >> 4], d * kvalues_iq4nl[q4[2 * j + 1] >> 4]);
447 }
448}
449
450template <typename E>
451static __dpct_inline__ void fg_stage_a(const block_iq3_xxs * __restrict__ xrow, const int kb, typename E::pair * a) {
452 FG_SUPERBLOCK(block_iq3_xxs);
453 const uint8_t * q3 = blk->qs + 8 * ib;
454 const uint16_t * gas = (const uint16_t *) (blk->qs + QK_K / 4) + 2 * ib;
455 const uint32_t aux32 = gas[0] | (gas[1] << 16);
456 const float d = (float) blk->d * (0.5f + (aux32 >> 28)) * 0.5f;
457#pragma unroll
458 for (int il = 0; il < 4; ++il) {
459 const uint8_t * grid1 = (const uint8_t *) (iq3xxs_grid + q3[2 * il + 0]);
460 const uint8_t * grid2 = (const uint8_t *) (iq3xxs_grid + q3[2 * il + 1]);
461 const uint8_t signs = ksigns_iq2xs[(aux32 >> (7 * il)) & 127];
462 float t[8];
463#pragma unroll
464 for (int j = 0; j < 4; ++j) {
465 t[j + 0] = d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f);
466 t[j + 4] = d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f);
467 }
468 fg_pack_quarter<E>(t, a, il);
469 }
470}
471
472template <typename E>
473static __dpct_inline__ void fg_stage_a(const block_iq2_xxs * __restrict__ xrow, const int kb, typename E::pair * a) {
474 FG_SUPERBLOCK(block_iq2_xxs);
475 const uint16_t * q2 = blk->qs + 4 * ib;
476 const uint8_t * aux8 = (const uint8_t *) q2;
477 const uint32_t aux32 = q2[2] | (q2[3] << 16);
478 const float d = (float) blk->d * (0.5f + (aux32 >> 28)) * 0.25f;
479#pragma unroll
480 for (int il = 0; il < 4; ++il) {
481 const uint8_t * grid = (const uint8_t *) (iq2xxs_grid + aux8[il]);
482 const uint8_t signs = ksigns_iq2xs[(aux32 >> (7 * il)) & 127];
483 float t[8];
484#pragma unroll
485 for (int j = 0; j < 8; ++j) {
486 t[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
487 }
488 fg_pack_quarter<E>(t, a, il);
489 }
490}
491
492template <typename E>
493static __dpct_inline__ void fg_stage_a(const block_iq2_xs * __restrict__ xrow, const int kb, typename E::pair * a) {
494 FG_SUPERBLOCK(block_iq2_xs);
495 const uint16_t * q2 = blk->qs + 4 * ib;
496#pragma unroll
497 for (int il = 0; il < 4; ++il) {
498 const uint8_t * grid = (const uint8_t *) (iq2xs_grid + (q2[il] & 511));
499 const float d = (float) blk->d * (0.5f + ((blk->scales[ib] >> (4 * (il / 2))) & 0xf)) * 0.25f;
500 const uint8_t signs = ksigns_iq2xs[q2[il] >> 9];
501 float t[8];
502#pragma unroll
503 for (int j = 0; j < 8; ++j) {
504 t[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
505 }
506 fg_pack_quarter<E>(t, a, il);
507 }
508}
509
510template <typename E>
511static __dpct_inline__ void fg_stage_a(const block_iq2_s * __restrict__ xrow, const int kb, typename E::pair * a) {
512 FG_SUPERBLOCK(block_iq2_s);
513#pragma unroll
514 for (int il = 0; il < 4; ++il) {
515 const uint8_t * grid =
516 (const uint8_t *) (iq2s_grid + (blk->qs[4 * ib + il] | ((blk->qh[ib] << (8 - 2 * il)) & 0x300)));
517 const float d = (float) blk->d * (0.5f + ((blk->scales[ib] >> (4 * (il / 2))) & 0xf)) * 0.25f;
518 const uint8_t signs = blk->qs[QK_K / 8 + 4 * ib + il];
519 float t[8];
520#pragma unroll
521 for (int j = 0; j < 8; ++j) {
522 t[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);
523 }
524 fg_pack_quarter<E>(t, a, il);
525 }
526}
527
528template <typename E>
529static __dpct_inline__ void fg_stage_a(const block_iq1_s * __restrict__ xrow, const int kb, typename E::pair * a) {
530 FG_SUPERBLOCK(block_iq1_s);
531 const float delta = blk->qh[ib] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA;
532 const float d = (float) blk->d * (2 * ((blk->qh[ib] >> 12) & 7) + 1);
533#pragma unroll
534 for (int il = 0; il < 4; ++il) {
535 uint32_t grid32[2];
536 const int8_t * q = (const int8_t *) grid32;
537 grid32[0] = iq1s_grid_gpu[blk->qs[4 * ib + il] | (((blk->qh[ib] >> (3 * il)) & 7) << 8)];
538 grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f;
539 grid32[0] &= 0x0f0f0f0f;
540 float t[8];
541#pragma unroll
542 for (int j = 0; j < 8; ++j) {
543 t[j] = d * (q[j] + delta);
544 }
545 fg_pack_quarter<E>(t, a, il);
546 }
547}
548
549template <typename E>
550static __dpct_inline__ void fg_stage_a(const block_iq1_m * __restrict__ xrow, const int kb, typename E::pair * a) {
551 FG_SUPERBLOCK(block_iq1_m);
552 const uint16_t * sc = (const uint16_t *) blk->scales;
553 iq1m_scale_t scale;
554 scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
555#pragma unroll
556 for (int il = 0; il < 4; ++il) {
557 const int ib16 = 2 * ib + il / 2;
558 const float d = (float) scale.f16 * (2 * ((sc[ib16 / 4] >> (3 * (ib16 % 4))) & 0x7) + 1);
559 const float delta = blk->qh[2 * ib + il / 2] & (0x08 << (4 * (il % 2))) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA;
560 uint32_t grid32[2];
561 const int8_t * q = (const int8_t *) grid32;
562 grid32[0] = iq1s_grid_gpu[blk->qs[4 * ib + il] |
563 (((blk->qh[2 * ib + il / 2] >> (4 * (il % 2))) & 7) << 8)];
564 grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f;
565 grid32[0] &= 0x0f0f0f0f;
566 float t[8];
567#pragma unroll
568 for (int j = 0; j < 8; ++j) {
569 t[j] = d * (q[j] + delta);
570 }
571 fg_pack_quarter<E>(t, a, il);
572 }
573}
574
575
576// q8_0 and the k-quants. Each decode takes the fields of one 32-value sub-block, so the canonical
577// layout and the reorder (SoA) layout of reorder_qw() share it and differ only in where the fields
578// live, as in dequantize.hpp.
579template <typename E>
580static __dpct_inline__ void fg_decode_q8_0(const int8_t * __restrict__ qs, const float d, typename E::pair * a) {
581#pragma unroll
582 for (int j = 0; j < QK8_0 / 2; ++j) {
583 a[j] = E::make(d * qs[2 * j], d * qs[2 * j + 1]);
584 }
585}
586
587// same unpack as get_scale_min_k4() in dequantize.hpp
588static __dpct_inline__ void fg_scale_min_k4(const int j, const uint8_t * __restrict__ q, uint8_t & d, uint8_t & m) {
589 if (j < 4) {
590 d = q[j] & 63;
591 m = q[j + 4] & 63;
592 } else {
593 d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
594 m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
595 }
596}
597
598// q4_K sub-block ib (0..7) uses scale/min pair ib and the low (even ib) or high (odd ib) nibbles of
599// qs[32 * (ib / 2) ...], as in dequantize_row_q4_K
600template <typename E>
601static __dpct_inline__ void fg_decode_q4_K(const uint8_t * __restrict__ qs, const uint8_t * __restrict__ scales,
602 const sycl::half2 dm, const int ib, typename E::pair * a) {
603 uint8_t sc, mb;
604 fg_scale_min_k4(ib, scales, sc, mb);
605 const float d = (float) dm[0] * sc;
606 const float m = (float) dm[1] * mb;
607 const uint8_t * q = qs + 32 * (ib / 2);
608 const int shift = 4 * (ib % 2);
609#pragma unroll
610 for (int j = 0; j < 16; ++j) {
611 a[j] = E::make(d * ((q[2 * j] >> shift) & 0xF) - m, d * ((q[2 * j + 1] >> shift) & 0xF) - m);
612 }
613}
614
615// q5_K: q4_K plus one high bit per value, bit ib of qh[l]
616template <typename E>
617static __dpct_inline__ void fg_decode_q5_K(const uint8_t * __restrict__ qs, const uint8_t * __restrict__ qh,
618 const uint8_t * __restrict__ scales, const sycl::half2 dm, const int ib,
619 typename E::pair * a) {
620 uint8_t sc, mb;
621 fg_scale_min_k4(ib, scales, sc, mb);
622 const float d = (float) dm[0] * sc;
623 const float m = (float) dm[1] * mb;
624 const uint8_t * q = qs + 32 * (ib / 2);
625 const int shift = 4 * (ib % 2);
626#pragma unroll
627 for (int j = 0; j < 16; ++j) {
628 const int l = 2 * j;
629 a[j] = E::make(d * (((q[l] >> shift) & 0xF) | (((qh[l] >> ib) & 1) << 4)) - m,
630 d * (((q[l + 1] >> shift) & 0xF) | (((qh[l + 1] >> ib) & 1) << 4)) - m);
631 }
632}
633
634// q6_K: sub-block ib is quarter r = ib % 4 of half h = ib / 4. The half selects ql + 64h, qh + 32h
635// and scales + 8h; the quarter selects ql + 32(r & 1), the ql nibble r / 2, the qh bit pair r and
636// scales + 2r, as in dequantize_row_q6_K. The scale changes at value 16 of the sub-block.
637template <typename E>
638static __dpct_inline__ void fg_decode_q6_K(const uint8_t * __restrict__ ql, const uint8_t * __restrict__ qh,
639 const int8_t * __restrict__ scales, const float d, const int ib,
640 typename E::pair * a) {
641 const int h = ib / 4;
642 const int r = ib % 4;
643 const uint8_t * q = ql + 64 * h + 32 * (r & 1);
644 const uint8_t * hb = qh + 32 * h;
645 const int8_t * sc = scales + 8 * h + 2 * r;
646#pragma unroll
647 for (int j = 0; j < 16; ++j) {
648 const int l = 2 * j;
649 const float dl = d * sc[j / 8];
650 const int q0 = (((q[l] >> (4 * (r / 2))) & 0xF) | (((hb[l] >> (2 * r)) & 3) << 4)) - 32;
651 const int q1 = (((q[l + 1] >> (4 * (r / 2))) & 0xF) | (((hb[l + 1] >> (2 * r)) & 3) << 4)) - 32;
652 a[j] = E::make(dl * q0, dl * q1);
653 }
654}
655
656template <typename E>
657static __dpct_inline__ void fg_stage_a(const block_q8_0 * __restrict__ xrow, const int kb, typename E::pair * a) {
658 fg_decode_q8_0<E>(xrow[kb].qs, (float) xrow[kb].d, a);
659}
660
661template <typename E>
662static __dpct_inline__ void fg_stage_a(const block_q4_K * __restrict__ xrow, const int kb, typename E::pair * a) {
663 FG_SUPERBLOCK(block_q4_K);
664 fg_decode_q4_K<E>(blk->qs, blk->scales, blk->dm, ib, a);
665}
666
667template <typename E>
668static __dpct_inline__ void fg_stage_a(const block_q5_K * __restrict__ xrow, const int kb, typename E::pair * a) {
669 FG_SUPERBLOCK(block_q5_K);
670 fg_decode_q5_K<E>(blk->qs, blk->qh, blk->scales, blk->dm, ib, a);
671}
672
673template <typename E>
674static __dpct_inline__ void fg_stage_a(const block_q6_K * __restrict__ xrow, const int kb, typename E::pair * a) {
675 FG_SUPERBLOCK(block_q6_K);
676 fg_decode_q6_K<E>(blk->ql, blk->qh, blk->scales, (float) blk->d, ib, a);
677}
678
679// Reorder (SoA) layout: each block field is one stream over the nblocks of the matrix (of the expert
680// slice for MUL_MAT_ID), in the order reorder_qw() writes them. Block ib holds k step kb.
681template <typename block_q_t> struct fg_soa {
682 static constexpr bool supported = false;
683};
684
685template <> struct fg_soa<block_q8_0> {
686 static constexpr bool supported = true;
687 // [qs][d]
688 template <typename E>
689 static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int,
690 typename E::pair * a) {
691 const float d = (float) ((const sycl::half *) (x + nblocks * QK8_0))[ib];
692 fg_decode_q8_0<E>((const int8_t *) x + ib * QK8_0, d, a);
693 }
694};
695
696template <> struct fg_soa<block_q4_K> {
697 static constexpr bool supported = true;
698 // [qs][scales][dm]
699 template <typename E>
700 static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb,
701 typename E::pair * a) {
702 const uint8_t * scales = x + nblocks * (QK_K / 2);
703 const sycl::half2 dm = ((const sycl::half2 *) (scales + nblocks * K_SCALE_SIZE))[ib];
704 fg_decode_q4_K<E>(x + ib * (QK_K / 2), scales + ib * K_SCALE_SIZE, dm, kb % (QK_K / 32), a);
705 }
706};
707
708template <> struct fg_soa<block_q5_K> {
709 static constexpr bool supported = true;
710 // [qs][qh][scales][dm]
711 template <typename E>
712 static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb,
713 typename E::pair * a) {
714 const uint8_t * qh = x + nblocks * (QK_K / 2);
715 const uint8_t * scales = qh + nblocks * (QK_K / 8);
716 const sycl::half2 dm = ((const sycl::half2 *) (scales + nblocks * K_SCALE_SIZE))[ib];
717 fg_decode_q5_K<E>(x + ib * (QK_K / 2), qh + ib * (QK_K / 8), scales + ib * K_SCALE_SIZE, dm,
718 kb % (QK_K / 32), a);
719 }
720};
721
722template <> struct fg_soa<block_q6_K> {
723 static constexpr bool supported = true;
724 // [ql][qh][scales][d]
725 template <typename E>
726 static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb,
727 typename E::pair * a) {
728 const uint8_t * qh = x + nblocks * (QK_K / 2);
729 const uint8_t * scales = qh + nblocks * (QK_K / 4);
730 const float d = (float) ((const sycl::half *) (scales + nblocks * (QK_K / 16)))[ib];
731 fg_decode_q6_K<E>(x + ib * (QK_K / 2), qh + ib * (QK_K / 4), (const int8_t *) scales + ib * (QK_K / 16), d,
732 kb % (QK_K / 32), a);
733 }
734};
735
736
737// one SG_ROWS x BN output tile: B columns [b0, b0 + BN) of packed_b go to dst columns [n0, n1),
738// n1 - n0 <= BN
739template <typename S, typename block_q_t, bool reordered>
740static void fused_dequant_gemm_tile(
741 const block_q_t * __restrict__ x,
742 const typename S::tsb * __restrict__ packed_b,
743 float * __restrict__ dst,
744 const int M, const int Npad, const int K, const int ldd,
745 const int b0, const int n0, const int n1,
746 sycl::local_accessor<typename S::tsa, 1> tile_a,
747 sycl::local_accessor<float, 1> tile_c,
748 const sycl::nd_item<2> & item) {
749 if constexpr (fg_built<S::SG>()) {
750 using EA = typename S::EA;
751 using TA = typename S::ta;
752 using TB = typename S::tb;
753 const auto sg = item.get_sub_group();
754 const int sg_id = sg.get_group_id()[0];
755 const int lane = sg.get_local_id()[0];
756 const int m0 = item.get_group(1) * S::SG_ROWS;
757 const int nstep = K / FG_BK;
758 const int a_base = sg_id * S::SG_ROWS * FG_BK;
759 const int c_base = sg_id * S::SG_ROWS * S::BN;
760
761 mx::joint_matrix<sycl::sub_group, float, mx::use::accumulator, S::TM, S::TN> acc[S::MT][S::NT];
762#pragma unroll
763 for (int mt = 0; mt < S::MT; ++mt) {
764#pragma unroll
765 for (int nt = 0; nt < S::NT; ++nt) {
766 mx::joint_matrix_fill(sg, acc[mt][nt], 0.0f);
767 }
768 }
769
770 // lane decodes rows lane, lane + SG, ... of the sub-group's SG_ROWS
771 constexpr int KPB = fg_block_traits<block_q_t>::qk / FG_BK; // k steps per block
772 const size_t bpr = K / fg_block_traits<block_q_t>::qk;
773 const size_t nblocks = (size_t) M * bpr;
774 size_t row_blk[S::RPL];
775 bool row_ok[S::RPL];
776 typename EA::pair * a[S::RPL];
777#pragma unroll
778 for (int r = 0; r < S::RPL; ++r) {
779 const int row = m0 + r * S::SG + lane;
780 row_ok[r] = row < M;
781 row_blk[r] = (size_t) (row_ok[r] ? row : 0) * bpr;
782 a[r] = (typename EA::pair *) &tile_a[a_base + (r * S::SG + lane) * FG_BK];
783 }
784
785 const auto b_ptr = sycl::address_space_cast<sycl::access::address_space::global_space,
786 sycl::access::decorated::no>(packed_b);
787 const int b_stride = Npad * S::VNNI;
788
789 const int kb_begin = (sg_id * nstep) / FG_KSPLIT;
790 const int kb_end = ((sg_id + 1) * nstep) / FG_KSPLIT;
791 for (int kb = kb_begin; kb < kb_end; ++kb) {
792#pragma unroll
793 for (int r = 0; r < S::RPL; ++r) {
794 if (row_ok[r]) {
795 if constexpr (reordered) {
796 fg_soa<block_q_t>::template stage<EA>((const uint8_t *) x, nblocks, row_blk[r] + kb / KPB, kb,
797 a[r]);
798 } else {
799 fg_stage_a<EA>(x + row_blk[r], kb, a[r]);
800 }
801 } else {
802#pragma unroll
803 for (int j = 0; j < FG_BK / 2; ++j) {
804 a[r][j] = EA::make(0.0f, 0.0f);
805 }
806 }
807 }
808 sycl::group_barrier(sg);
809
810#pragma unroll
811 for (int kt = 0; kt < FG_BK / S::TK; ++kt) {
812 const int kq0 = (kb * FG_BK + kt * S::TK) / S::VNNI;
813 mx::joint_matrix<sycl::sub_group, TB, mx::use::b, S::TK, S::TN, S::b_layout> sub_b[S::NT];
814#pragma unroll
815 for (int nt = 0; nt < S::NT; ++nt) {
816 mx::joint_matrix_load(sg, sub_b[nt], b_ptr + (size_t) kq0 * b_stride + (b0 + nt * S::TN) * S::VNNI, b_stride);
817 }
818#pragma unroll
819 for (int mt = 0; mt < S::MT; ++mt) {
820 mx::joint_matrix<sycl::sub_group, TA, mx::use::a, S::TM, S::TK, mx::layout::row_major> sub_a;
821 mx::joint_matrix_load(sg, sub_a,
822 tile_a.template get_multi_ptr<sycl::access::decorated::no>() + a_base + (mt * S::TM) * FG_BK + kt * S::TK,
823 FG_BK);
824#pragma unroll
825 for (int nt = 0; nt < S::NT; ++nt) {
826 mx::joint_matrix_mad(sg, acc[mt][nt], sub_a, sub_b[nt], acc[mt][nt]);
827 }
828 }
829 }
830 // the next step overwrites tile_a
831 sycl::group_barrier(sg);
832 }
833
834#pragma unroll
835 for (int mt = 0; mt < S::MT; ++mt) {
836#pragma unroll
837 for (int nt = 0; nt < S::NT; ++nt) {
838 mx::joint_matrix_store(sg, acc[mt][nt],
839 tile_c.template get_multi_ptr<sycl::access::decorated::no>() + c_base + (mt * S::TM) * S::BN + nt * S::TN,
840 S::BN, mx::layout::row_major);
841 }
842 }
843 sycl::group_barrier(item.get_group());
844
845 // sum the K splits; consecutive lanes write consecutive rows of one dst column
846 for (int idx = item.get_local_linear_id(); idx < S::SG_ROWS * S::BN; idx += S::WG_SIZE) {
847 const int r = idx % S::SG_ROWS;
848 const int c = idx / S::SG_ROWS;
849 const int m = m0 + r;
850 const int n = n0 + c;
851 if (m < M && n < n1) {
852 float sum = 0.0f;
853#pragma unroll
854 for (int s = 0; s < FG_KSPLIT; ++s) {
855 sum += tile_c[s * S::SG_ROWS * S::BN + r * S::BN + c];
856 }
857 dst[(size_t) n * ldd + m] = sum;
858 }
859 }
860 }
861}
862
863template <typename S, typename block_q_t, bool reordered = false>
864static void fused_dequant_gemm_launch(const void * src0, const typename S::tsb * packed, float * dst, const int M,
865 const int N, const int Npad, const int K, const int ldd,
866 const int64_t groups_n, const int64_t groups_m, dpct::queue_ptr stream) {
867 stream->submit([&](sycl::handler & cgh) {
868 sycl::local_accessor<typename S::tsa, 1> tile_a(FG_KSPLIT * S::SG_ROWS * FG_BK, cgh);
869 sycl::local_accessor<float, 1> tile_c(FG_KSPLIT * S::SG_ROWS * S::BN, cgh);
870 cgh.parallel_for(
871 sycl::nd_range<2>(sycl::range<2>(groups_n, groups_m * S::WG_SIZE), sycl::range<2>(1, S::WG_SIZE)),
872 [=](sycl::nd_item<2> item) [[sycl::reqd_sub_group_size(S::SG)]] {
873 const int n0 = item.get_group(0) * S::BN;
874 fused_dequant_gemm_tile<S, block_q_t, reordered>((const block_q_t *) src0, packed, dst, M, Npad, K,
875 ldd, n0, n0, N, tile_a, tile_c, item);
876 });
877 });
878}
879
880// grouped: work-group (t, mt) is tile t of the schedule; its B columns sit at t * BN
881template <typename S, typename block_q_t, bool reordered>
882static void grouped_dequant_gemm_launch(const char * src0_dd, const size_t expert_stride,
883 const ggml_sycl_gg_tile * tiles_ptr, const typename S::tsb * packed, float * dst,
884 const int M, const int Npad, const int K, const int64_t n_tiles,
885 const int64_t groups_m, dpct::queue_ptr stream) {
886 stream->submit([&](sycl::handler & cgh) {
887 sycl::local_accessor<typename S::tsa, 1> tile_a(FG_KSPLIT * S::SG_ROWS * FG_BK, cgh);
888 sycl::local_accessor<float, 1> tile_c(FG_KSPLIT * S::SG_ROWS * S::BN, cgh);
889 cgh.parallel_for(
890 sycl::nd_range<2>(sycl::range<2>(n_tiles, groups_m * S::WG_SIZE), sycl::range<2>(1, S::WG_SIZE)),
891 [=](sycl::nd_item<2> item) [[sycl::reqd_sub_group_size(S::SG)]] {
892 const int t = item.get_group(0);
893 const ggml_sycl_gg_tile tile = tiles_ptr[t];
894 const block_q_t * x = (const block_q_t *) (src0_dd + (size_t) tile.expert * expert_stride);
895 fused_dequant_gemm_tile<S, block_q_t, reordered>(x, packed, dst, M, Npad, K, M, t * S::BN, tile.n0,
896 tile.n1, tile_a, tile_c, item);
897 });
898 });
899}
900
901// src1 f32 rows -> packed [K/V][n_tiles*BN][V], tile t holds its rows [n0, n1) at columns t*BN..,
902// zero past n1. The column runs fastest so a sub-group writes one contiguous run.
903template <typename S>
904static void grouped_gemm_pack_b(const float * y, typename S::tsb * packed, const ggml_sycl_gg_tile * tiles, int Npad,
905 int K, dpct::queue_ptr stream) {
906 using E = typename S::EB;
907 constexpr int V = S::VNNI;
908 const int kqs = K / V;
909 stream->parallel_for(sycl::range<1>((size_t) Npad * kqs), [=](sycl::id<1> id) {
910 const size_t idx = id[0];
911 const int kq = idx / Npad;
912 const int n = idx - (size_t) kq * Npad;
913 const ggml_sycl_gg_tile tile = tiles[n / S::BN];
914 const int row = tile.n0 + n % S::BN;
915 // one guarded load run per work-item, as a per-element select costs ~1.5% prefill
916 typename S::tsb vals[V] = {};
917 if (row < tile.n1) {
918 const float * src = y + (size_t) row * K + V * kq;
919#pragma unroll
920 for (int v = 0; v < V; ++v) {
921 vals[v] = E::cvt(src[v]);
922 }
923 }
924 typename S::tsb * out = packed + ((size_t) kq * Npad + n) * V;
925#pragma unroll
926 for (int v = 0; v < V; ++v) {
927 out[v] = vals[v];
928 }
929 });
930}
931
932// q8_0 and the k-quants take only the grouped path. The plain kernel decodes A again for every BN columns
933// of a dense batch, and for these formats that costs more than the one dequantization of the library GEMM.
934template <typename T> static constexpr bool fg_plain_ok() {
935 return !std::is_same_v<T, block_q8_0> && !std::is_same_v<T, block_q4_K> && !std::is_same_v<T, block_q5_K> &&
936 !std::is_same_v<T, block_q6_K>;
937}
938
939template <typename T, bool R> struct fg_tag {
940 using type = T;
941 static constexpr bool reordered = R;
942};
943
944// calls f(fg_tag<block_q_t, reordered>{}) for the weight format and layout; false if it has no A stage
945template <typename T, typename F> static bool fg_visit_layout(bool reordered, F && f) {
946 if (!reordered) {
947 f(fg_tag<T, false>{});
948 return true;
949 }
950 if constexpr (fg_soa<T>::supported) {
951 f(fg_tag<T, true>{});
952 return true;
953 }
954 return false;
955}
956
957template <typename F> static bool fg_visit_type(ggml_type type, bool reordered, F && f) {
958 switch (type) {
959 case GGML_TYPE_IQ4_NL: return fg_visit_layout<block_iq4_nl>(reordered, f);
960 case GGML_TYPE_IQ3_S: return fg_visit_layout<block_iq3_s>(reordered, f);
961 case GGML_TYPE_IQ4_XS: return fg_visit_layout<block_iq4_xs>(reordered, f);
962 case GGML_TYPE_IQ3_XXS: return fg_visit_layout<block_iq3_xxs>(reordered, f);
963 case GGML_TYPE_IQ2_XXS: return fg_visit_layout<block_iq2_xxs>(reordered, f);
964 case GGML_TYPE_IQ2_XS: return fg_visit_layout<block_iq2_xs>(reordered, f);
965 case GGML_TYPE_IQ2_S: return fg_visit_layout<block_iq2_s>(reordered, f);
966 case GGML_TYPE_IQ1_S: return fg_visit_layout<block_iq1_s>(reordered, f);
967 case GGML_TYPE_IQ1_M: return fg_visit_layout<block_iq1_m>(reordered, f);
968 case GGML_TYPE_Q8_0: return fg_visit_layout<block_q8_0>(reordered, f);
969 case GGML_TYPE_Q4_K: return fg_visit_layout<block_q4_K>(reordered, f);
970 case GGML_TYPE_Q5_K: return fg_visit_layout<block_q5_K>(reordered, f);
971 case GGML_TYPE_Q6_K: return fg_visit_layout<block_q6_K>(reordered, f);
972 default: return false;
973 }
974}
975
976template <typename S>
977static bool fg_fused_run(ggml_type src0_type, bool src0_reordered, const void * src0, const void * src1, ggml_type src1_type,
978 float * dst, int64_t M, int64_t N, int64_t K, int64_t ldd, ggml_sycl_pool & pool,
979 dpct::queue_ptr stream) {
980 const int64_t groups_n = (N + S::BN - 1) / S::BN;
981 const int64_t groups_m = (M + S::SG_ROWS - 1) / S::SG_ROWS;
982 const int Npad = (int) (groups_n * S::BN);
983
984 // src1 is read in its own type: one pass, converted in registers only if B differs
985 ggml_sycl_pool_alloc<typename S::tsb> packed_b(pool, (size_t) K * Npad);
986 if (src1_type == GGML_TYPE_F16) {
987 fused_gemm_pack_b<typename S::EB>((const sycl::half *) src1, packed_b.get(), (int) N, Npad, (int) K, stream);
988 } else if (src1_type == GGML_TYPE_BF16) {
989 fused_gemm_pack_b<typename S::EB>((const fg_bf16 *) src1, packed_b.get(), (int) N, Npad, (int) K, stream);
990 } else {
991 fused_gemm_pack_b<typename S::EB>((const float *) src1, packed_b.get(), (int) N, Npad, (int) K, stream);
992 }
993
994 const typename S::tsb * packed = packed_b.get();
995 return fg_visit_type(src0_type, src0_reordered, [&](auto tag) {
996 using block_q_t = typename decltype(tag)::type;
997 if constexpr (fg_plain_ok<block_q_t>()) {
998 fused_dequant_gemm_launch<S, block_q_t, decltype(tag)::reordered>(src0, packed, dst, (int) M, (int) N,
999 Npad, (int) K, (int) ldd, groups_n,
1000 groups_m, stream);
1001 }
1002 });
1003}
1004
1005bool ggml_sycl_fused_dequant_gemm(ggml_type src0_type, bool src0_reordered, const void * src0, const void * src1, ggml_type src1_type,
1006 int32_t src1_prec, float * dst, int64_t M, int64_t N, int64_t K, int64_t ldd,
1007 ggml_sycl_pool & pool, dpct::queue_ptr stream) {
1008 // every BN columns dequantize A again, so wide N is left to the library GEMM.
1009 // src0_reordered: the persistent weight reorder may have been installed on this
1010 // tensor by an earlier small-batch mul_mat; the A stage then has to decode the
1011 // SoA layout. Types without an SoA stage (fg_soa<T>::supported == false)
1012 // decline via fg_visit_layout and the caller falls through to the
1013 // reorder-aware conversion route.
1014 bool plain_ok = false;
1015 fg_visit_type(src0_type, src0_reordered, [&](auto tag) { plain_ok = fg_plain_ok<typename decltype(tag)::type>(); });
1016 if (g_ggml_sycl_dynamic_precision == GGML_SYCL_DYNAMIC_PRECISION_F32 ||
1017 !ggml_sycl_xmx_gather_type_enabled(src0_type) || !plain_ok) {
1018 return false;
1019 }
1020 if (src1_type != GGML_TYPE_F32 && src1_type != GGML_TYPE_F16 && src1_type != GGML_TYPE_BF16) {
1021 return false;
1022 }
1023 if (!ggml_sycl_fused_dequant_gemm_shape_ok(src0_type, M, N, K, ldd)) {
1024 return false;
1025 }
1026 const int combo = fg_pick_combo(stream, src1_type, src1_prec);
1027 if (combo < 0) {
1028 return false;
1029 }
1030 bool launched = false;
1031 fg_visit_combo(combo, [&](auto s) {
1032 launched = fg_fused_run<decltype(s)>(src0_type, src0_reordered, src0, src1, src1_type, dst, M, N, K, ldd, pool, stream);
1033 });
1034 return launched;
1035}
1036
1037template <typename S>
1038static bool fg_grouped_run(ggml_type src0_type, bool reordered, const void * src0_base, size_t expert_stride,
1039 const float * src1, float * dst, const int64_t * expert_row_offsets, int64_t n_as, int64_t M,
1040 int64_t K, std::vector<ggml_sycl_gg_tile> & tiles, ggml_sycl_pool & pool,
1041 dpct::queue_ptr stream) {
1042 // the host knows every slice, so it lays out the work-groups: no search on the device
1043 tiles.clear();
1044 for (int64_t e = 0; e < n_as; ++e) {
1045 const int64_t end = expert_row_offsets[e + 1];
1046 for (int64_t n0 = expert_row_offsets[e]; n0 < end; n0 += S::BN) {
1047 tiles.push_back({ (int32_t) e, (int32_t) n0, (int32_t) std::min<int64_t>(n0 + S::BN, end) });
1048 }
1049 }
1050 const int64_t n_tiles = tiles.size();
1051 const int64_t groups_m = (M + S::SG_ROWS - 1) / S::SG_ROWS;
1052 const int Npad = (int) (n_tiles * S::BN);
1053
1054 const int64_t max_tiles = grouped_gemm_max_tiles(expert_row_offsets[n_as], n_as, S::BN);
1055 GGML_ASSERT(n_tiles <= max_tiles);
1056 ggml_sycl_pool_alloc<ggml_sycl_gg_tile> tiles_dev(pool, max_tiles);
1057 SYCL_CHECK(CHECK_TRY_ERROR(stream->memcpy(tiles_dev.get(), tiles.data(), n_tiles * sizeof(ggml_sycl_gg_tile))));
1058
1059 ggml_sycl_pool_alloc<typename S::tsb> packed_b(pool, (size_t) K * max_tiles * S::BN);
1060 grouped_gemm_pack_b<S>(src1, packed_b.get(), tiles_dev.get(), Npad, (int) K, stream);
1061
1062 const typename S::tsb * packed = packed_b.get();
1063 const ggml_sycl_gg_tile * tiles_ptr = tiles_dev.get();
1064 const char * src0_dd = (const char *) src0_base;
1065 return fg_visit_type(src0_type, reordered, [&](auto tag) {
1066 using T = decltype(tag);
1067 grouped_dequant_gemm_launch<S, typename T::type, T::reordered>(src0_dd, expert_stride, tiles_ptr, packed, dst,
1068 (int) M, Npad, (int) K, n_tiles, groups_m,
1069 stream);
1070 });
1071}
1072
1073bool ggml_sycl_grouped_dequant_gemm(ggml_type src0_type, bool reordered, const void * src0_base, size_t expert_stride,
1074 const float * src1, int32_t src1_prec, float * dst,
1075 const int64_t * expert_row_offsets, int64_t n_as, int64_t M, int64_t K,
1076 int64_t total_rows, std::vector<ggml_sycl_gg_tile> & tiles,
1077 ggml_sycl_pool & pool, dpct::queue_ptr stream) {
1078 int64_t n_active = 0;
1079 for (int64_t e = 0; e < n_as; ++e) {
1080 n_active += expert_row_offsets[e + 1] > expert_row_offsets[e];
1081 }
1082 if (g_ggml_sycl_dynamic_precision == GGML_SYCL_DYNAMIC_PRECISION_F32 ||
1083 !ggml_sycl_xmx_gather_type_enabled(src0_type) || !fg_visit_type(src0_type, reordered, [](auto) {})) {
1084 return false;
1085 }
1086 if (!ggml_sycl_grouped_dequant_gemm_shape_ok(src0_type, M, K, total_rows, n_active)) {
1087 return false;
1088 }
1089 const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec);
1090 if (combo < 0) {
1091 return false;
1092 }
1093 bool launched = false;
1094 fg_visit_combo(combo, [&](auto s) {
1095 launched = fg_grouped_run<decltype(s)>(src0_type, reordered, src0_base, expert_stride, src1, dst,
1096 expert_row_offsets, n_as, M, K, tiles, pool, stream);
1097 });
1098 return launched;
1099}