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 / ggml-metal-fusion.cpp

1214 lines · 46509 bytes Raw Blame History
1#include "ggml-metal-fusion.h"
2
3#include "ggml-metal-common.h"
4#include "ggml-metal-device.h"
5
6#include "ggml-backend-impl.h"
7
8#include <algorithm>
9#include <cstddef>
10#include <cstring>
11#include <set>
12#include <string>
13#include <vector>
14
15// derive the non-empty op sequence from the raw `ops_all` sequence
16static std::vector<ggml_op> ggml_metal_fusion_filter_ops(const std::vector<ggml_op> & ops_all) {
17 std::vector<ggml_op> ops;
18
19 for (ggml_op op : ops_all) {
20 if (!ggml_op_is_empty(op)) {
21 ops.push_back(op);
22 }
23 }
24
25 return ops;
26}
27
28struct ggml_metal_fusion {
29 ggml_metal_fusion_id id;
30
31 std::vector<ggml_op> ops; // non-empty op sequence, derived from ops_all
32 std::vector<ggml_op> ops_all; // full raw op sequence (may include empty RESHAPE/VIEW nodes)
33 std::vector<int> outs; // additional fused output nodes, relative to ops
34
35 // if unsafe: the generic chain/shape + ggml_can_fuse_subgraph checks are skipped and the
36 // check callback below is the sole validator (used for patterns that are not elision chains,
37 // e.g. the gdn + cache-cpy write-through fusion)
38 bool unsafe;
39
40 // extra backend constraints on top of ggml_can_fuse_subgraph
41 // nodes[j] is the j-th node of the pattern; node_idxs[idx + j] is its raw graph index
42 bool (*check)(const struct ggml_metal_fusion * fusion,
43 const struct ggml_tensor * const * nodes,
44 const struct ggml_cgraph * gf,
45 const int * node_idxs,
46 int idx,
47 ggml_metal_fusion_mode mode);
48
49 ggml_metal_fusion(
50 ggml_metal_fusion_id id,
51 const std::vector<ggml_op> & ops_all,
52 const std::vector<int> & outs,
53 bool unsafe,
54 bool (*check)(const struct ggml_metal_fusion * fusion,
55 const struct ggml_tensor * const * nodes,
56 const struct ggml_cgraph * gf,
57 const int * node_idxs,
58 int idx,
59 ggml_metal_fusion_mode mode))
60 : id(id),
61 ops(ggml_metal_fusion_filter_ops(ops_all)),
62 ops_all(ops_all),
63 outs(outs),
64 unsafe(unsafe),
65 check(check) {
66 }
67};
68
69ggml_metal_fusion_id ggml_metal_fusion_get_id(const ggml_metal_fusion * fusion) {
70 return fusion->id;
71}
72
73// ---- helpers -------------------------------------------------------------
74
75// true if two tensors live in the same Metal buffer
76static bool ggml_metal_fusion_same_buffer(const ggml_tensor * a, const ggml_tensor * b) {
77 if (!a || !b) {
78 return false;
79 }
80
81 ggml_backend_buffer_t ba = a->view_src ? a->view_src->buffer : a->buffer;
82 ggml_backend_buffer_t bb = b->view_src ? b->view_src->buffer : b->buffer;
83
84 ggml_metal_buffer_t ca = (ggml_metal_buffer_t) ba->context;
85 ggml_metal_buffer_t cb = (ggml_metal_buffer_t) bb->context;
86
87 return ggml_metal_buffer_get_id(ca, a).metal == ggml_metal_buffer_get_id(cb, b).metal;
88}
89
90// true if the memory of two tensors overlaps in the same Metal buffer
91static bool ggml_metal_fusion_overlap(const ggml_tensor * a, const ggml_tensor * b) {
92 ggml_backend_buffer_t ba = a->view_src ? a->view_src->buffer : a->buffer;
93 ggml_backend_buffer_t bb = b->view_src ? b->view_src->buffer : b->buffer;
94
95 const ggml_metal_buffer_id bid_a = ggml_metal_buffer_get_id((ggml_metal_buffer_t) ba->context, a);
96 const ggml_metal_buffer_id bid_b = ggml_metal_buffer_get_id((ggml_metal_buffer_t) bb->context, b);
97
98 if (bid_a.metal == nullptr || bid_a.metal != bid_b.metal) {
99 return false;
100 }
101
102 return bid_a.offs <= bid_b.offs
103 ? bid_b.offs - bid_a.offs < ggml_nbytes(a)
104 : bid_a.offs - bid_b.offs < ggml_nbytes(b);
105}
106
107// ---- pattern checks ------------------------------------------------------
108
109// NORM/RMS_NORM + MUL + ADD: the weight/bias of each fused step must match the norm input
110// width, be contiguous rows, and the fused outputs must stay F32
111static bool ggml_metal_fusion_check_norm(
112 const ggml_metal_fusion * fusion,
113 const ggml_tensor * const * nodes,
114 const ggml_cgraph * gf,
115 const int * node_idxs,
116 int idx,
117 ggml_metal_fusion_mode mode) {
118 GGML_UNUSED(mode);
119 GGML_UNUSED(gf);
120 GGML_UNUSED(node_idxs);
121 GGML_UNUSED(idx);
122
123 GGML_ASSERT(fusion->ops.size() >= 2);
124
125 if (fusion->id == GGML_METAL_FUSION_NORM_SCALE) {
126 GGML_ASSERT(fusion->ops.size() == 2);
127
128 const ggml_tensor * scale = nodes[1];
129 if (scale->op != GGML_OP_SCALE || scale->src[0] != nodes[0] || scale->src[1] ||
130 scale->type != GGML_TYPE_F32) {
131 return false;
132 }
133
134 return true;
135 }
136
137 for (int j = 1; j < (int) fusion->ops.size(); j++) {
138 // the fused MUL/ADD must read the previous node as src0
139 if (nodes[j]->src[0] != nodes[j - 1]) {
140 return false;
141 }
142
143 // the weight/bias must have the same row width as the norm input
144 if (nodes[j]->src[1]->ne[0] != nodes[0]->ne[0]) {
145 return false;
146 }
147
148 if (!ggml_is_contiguous_rows(nodes[j]->src[1])) {
149 return false;
150 }
151
152 if (nodes[j]->type != GGML_TYPE_F32) {
153 return false;
154 }
155 }
156
157 return true;
158}
159
160// SSM_CONV + UNARY (silu)
161static bool ggml_metal_fusion_check_ssm_conv_silu(
162 const ggml_metal_fusion * fusion,
163 const ggml_tensor * const * nodes,
164 const ggml_cgraph * gf,
165 const int * node_idxs,
166 int idx,
167 ggml_metal_fusion_mode mode) {
168 GGML_UNUSED(fusion);
169 GGML_UNUSED(gf);
170 GGML_UNUSED(node_idxs);
171 GGML_UNUSED(idx);
172 GGML_UNUSED(mode);
173
174 const ggml_tensor * conv = nodes[0];
175 const ggml_tensor * un = nodes[1];
176
177 if (conv->op != GGML_OP_SSM_CONV || un->op != GGML_OP_UNARY || un->src[0] != conv || un->src[1]) {
178 return false;
179 }
180
181 if (ggml_get_unary_op(un) != GGML_UNARY_OP_SILU) {
182 return false;
183 }
184
185 if (conv->type != GGML_TYPE_F32 || un->type != GGML_TYPE_F32 || !ggml_is_contiguous_rows(un)) {
186 return false;
187 }
188
189 return true;
190}
191
192// ADD x N: each ADD reads the previous ADD as src0, and all addends must share layout
193// (and, in FULL mode, live in the same Metal buffer)
194static bool ggml_metal_fusion_check_add_chain(
195 const ggml_metal_fusion * fusion,
196 const ggml_tensor * const * nodes,
197 const ggml_cgraph * gf,
198 const int * node_idxs,
199 int idx,
200 ggml_metal_fusion_mode mode) {
201 GGML_UNUSED(gf);
202 GGML_UNUSED(node_idxs);
203 GGML_UNUSED(idx);
204 GGML_ASSERT(fusion->ops.size() >= 2);
205
206 for (int j = 1; j < (int) fusion->ops.size(); j++) {
207 if (nodes[j]->src[0] != nodes[j - 1]) {
208 return false;
209 }
210
211 if (!ggml_are_same_layout(nodes[j]->src[1], nodes[j - 1]->src[1])) {
212 return false;
213 }
214
215 if (mode == GGML_METAL_FUSION_FULL) {
216 if (!ggml_metal_fusion_same_buffer(nodes[j]->src[1], nodes[0]->src[1])) {
217 return false;
218 }
219 }
220 }
221
222 return true;
223}
224
225// GATED_DELTA_NET + CPY: the trailing cpy scatters the gdn state snapshots into the recurrent
226// cache, so the gdn kernel writes them straight to the cache and the cpy is elided.
227// mirrors ggml_metal_op_can_fuse_gdn_cache (PR #25788). the gdn output has other consumers (the
228// attn scores view), so unlike the other patterns this is not an elision chain: the structural
229// checks live entirely in this callback (unsafe = true).
230static bool ggml_metal_fusion_check_gdn_cache(
231 const ggml_metal_fusion * fusion,
232 const ggml_tensor * const * nodes,
233 const ggml_cgraph * gf,
234 const int * node_idxs,
235 int idx,
236 ggml_metal_fusion_mode mode) {
237 GGML_UNUSED(fusion);
238 GGML_UNUSED(gf);
239 GGML_UNUSED(node_idxs);
240 GGML_UNUSED(idx);
241
242 const ggml_tensor * gdn = nodes[0];
243 const ggml_tensor * cpy = nodes[1];
244
245 // the kernel skips the snapshot tail, so the gdn output must not be a graph output
246 if (gdn->type != GGML_TYPE_F32 || (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) {
247 return false;
248 }
249
250 if (cpy->op != GGML_OP_CPY || (cpy->flags & GGML_TENSOR_FLAG_OUTPUT)) {
251 return false;
252 }
253
254 const int64_t S_v = gdn->src[2]->ne[0];
255 const int64_t H = gdn->src[2]->ne[1];
256 const int64_t n_tokens = gdn->src[2]->ne[2];
257 const int64_t n_seqs = gdn->src[2]->ne[3];
258 const int64_t K = ggml_get_op_params_i32(gdn, 0);
259 const size_t tail_off = ggml_row_size(GGML_TYPE_F32, S_v * H * n_tokens * n_seqs);
260
261 const int64_t D = S_v * S_v * H;
262 const int64_t n_written = std::min<int64_t>(n_tokens, K);
263
264 const ggml_tensor * src = cpy->src[0]; // gdn snapshot tail view
265 const ggml_tensor * dst = cpy->src[1]; // cache view
266
267 // src must be this gdn's snapshot tail (contiguous, at the tail offset)
268 if (src->op != GGML_OP_VIEW || src->view_src != gdn ||
269 src->view_offs != tail_off || !ggml_is_contiguous(src)) {
270 return false;
271 }
272
273 const int64_t expected_ne[GGML_MAX_DIMS] = { D, n_seqs, n_written, 1 };
274 if (dst->type != GGML_TYPE_F32 ||
275 !std::equal(expected_ne, expected_ne + GGML_MAX_DIMS, dst->ne) ||
276 dst->nb[0] != ggml_type_size(GGML_TYPE_F32) ||
277 dst->nb[1] != ggml_row_size(GGML_TYPE_F32, D)) {
278 return false;
279 }
280
281 if (mode == GGML_METAL_FUSION_FULL) {
282 // the cache must be allocated so the kernel can write straight to its buffer
283 if (dst->data == nullptr) {
284 return false;
285 }
286 }
287
288 return true;
289}
290
291// MUL + SIN + SQR + MUL + ADD (snake activation)
292static bool ggml_metal_fusion_check_snake(
293 const ggml_metal_fusion * fusion,
294 const ggml_tensor * const * nodes,
295 const ggml_cgraph * gf,
296 const int * node_idxs,
297 int idx,
298 ggml_metal_fusion_mode mode) {
299 GGML_UNUSED(fusion);
300 GGML_UNUSED(mode);
301 GGML_UNUSED(gf);
302 GGML_UNUSED(node_idxs);
303 GGML_UNUSED(idx);
304
305 const ggml_tensor * mul0 = nodes[0];
306 const ggml_tensor * sin_node = nodes[1];
307 const ggml_tensor * sqr = nodes[2];
308 const ggml_tensor * mul1 = nodes[3];
309 const ggml_tensor * add = nodes[4];
310
311 // x carries the full activation shape, a is the broadcast operand
312 const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1];
313 const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0];
314
315 // mul1 reads sqr and inv_b in either operand order
316 const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0];
317
318 // closure check: the trailing add reads the same x as the leading mul
319 const ggml_tensor * x_in_add = (add->src[0] == mul1) ? add->src[1] : add->src[0];
320
321 // x is in the supported whitelist and every chain intermediate shares x's type.
322 // a and inv_b bind as device const float * in the kernel, so they stay F32.
323 const bool types_ok =
324 (x->type == GGML_TYPE_F32 || x->type == GGML_TYPE_F16 || x->type == GGML_TYPE_BF16) &&
325 (a->type == GGML_TYPE_F32) && (inv_b->type == GGML_TYPE_F32) &&
326 (mul0->type == x->type) && (sin_node->type == x->type) &&
327 (sqr->type == x->type) && (mul1->type == x->type) &&
328 (add->type == x->type);
329
330 // a / inv_b collapse to [1, C, 1, 1], x and add stay 2D
331 const bool shape_ok = ggml_are_same_shape(a, inv_b) && a->ne[0] == 1 && a->ne[1] == x->ne[1];
332 const bool dim_ok =
333 (x->ne[2] == 1) && (x->ne[3] == 1) &&
334 (add->ne[2] == 1) && (add->ne[3] == 1) &&
335 (a->ne[2] == 1) && (a->ne[3] == 1) &&
336 (inv_b->ne[2] == 1) && (inv_b->ne[3] == 1);
337
338 // kernel reads x[idx] and a[c] / inv_b[c] linearly, so every operand is contiguous
339 const bool contig_ok =
340 ggml_is_contiguous(x) && ggml_is_contiguous(add) &&
341 ggml_is_contiguous(a) && ggml_is_contiguous(inv_b);
342
343 return types_ok && shape_ok && dim_ok && contig_ok && x_in_add == x;
344}
345
346#define GGML_METAL_TOPK_MOE_MAX_EXPERTS 1024
347
348// SOFT_MAX + ARGSORT + GET_ROWS (plus optional norm/scale) for MoE routing.
349// This is a multi-output elision chain: the fused kernel writes both the selected
350// expert ids and the gathered/normalized routing weights.
351static const std::vector<ggml_op> ops_topk_moe = {
352 GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS
353};
354static const std::vector<ggml_op> ops_topk_moe_scale = {
355 GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_SCALE
356};
357static const std::vector<ggml_op> ops_topk_moe_norm = {
358 GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS,
359 GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE
360};
361static const std::vector<ggml_op> ops_topk_moe_norm_scale = {
362 GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS,
363 GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE, GGML_OP_SCALE
364};
365
366static bool ggml_metal_fusion_check_topk_moe(
367 const ggml_metal_fusion * fusion,
368 const ggml_tensor * const * nodes,
369 const ggml_cgraph * gf,
370 const int * node_idxs,
371 int idx,
372 ggml_metal_fusion_mode mode) {
373 GGML_ASSERT(fusion->ops.size() >= 3);
374 GGML_UNUSED(nodes);
375
376 const int n_ops = (int) fusion->ops.size();
377
378 const bool with_norm = n_ops >= 6;
379 const bool with_scale = n_ops == 4 || n_ops == 7;
380
381 // the fusion table operates on the non-empty node sequence; the raw graph also
382 // contains the RESHAPE/VIEW nodes that the fused kernel elides.
383 const std::vector<ggml_op> & ops_all = fusion->ops_all;
384
385 const int raw_start = node_idxs[idx];
386 int raw_end = node_idxs[idx + n_ops - 1];
387
388 // the norm variant ends with a RESHAPE that the non-empty sequence filters out;
389 // include it so the output use-count check sees the real final routing tensor
390 if (with_norm && !with_scale) {
391 if (raw_end + 1 >= gf->n_nodes) {
392 return false;
393 }
394 const ggml_tensor * trailing_reshape = gf->nodes[raw_end + 1];
395 if (trailing_reshape->op != GGML_OP_RESHAPE || trailing_reshape->src[0] != gf->nodes[raw_end]) {
396 return false;
397 }
398 raw_end++;
399 }
400
401 const int raw_count = raw_end - raw_start + 1;
402 if (raw_count != (int) ops_all.size()) {
403 return false;
404 }
405
406 int raw_idxs[GGML_METAL_FUSION_MAX];
407 for (int i = 0; i < raw_count; ++i) {
408 raw_idxs[i] = raw_start + i;
409 if (gf->nodes[raw_start + i]->op != ops_all[i]) {
410 return false;
411 }
412 }
413
414 const ggml_tensor * softmax = gf->nodes[raw_start];
415 const ggml_tensor * probs_reshaped = gf->nodes[raw_start + 1];
416 const ggml_tensor * argsort = gf->nodes[raw_start + 2];
417 const ggml_tensor * ids = gf->nodes[raw_start + 3];
418 const ggml_tensor * get_rows = gf->nodes[raw_start + 4];
419 const ggml_tensor * out = gf->nodes[raw_end];
420 const ggml_tensor * logits = softmax->src[0];
421
422 // the fused kernel implements plain softmax only
423 float scale = 1.0f;
424 float max_bias = 0.0f;
425 memcpy(&scale, ((const int32_t *) softmax->op_params) + 0, sizeof(scale));
426 memcpy(&max_bias, ((const int32_t *) softmax->op_params) + 1, sizeof(max_bias));
427 if (scale != 1.0f || max_bias != 0.0f || softmax->src[1] || softmax->src[2]) {
428 return false;
429 }
430
431 if (logits->type != GGML_TYPE_F32 || softmax->type != GGML_TYPE_F32 ||
432 out->type != GGML_TYPE_F32 || ids->type != GGML_TYPE_I32) {
433 return false;
434 }
435
436 const int64_t n_expert = logits->ne[0];
437 const int64_t n_tokens = logits->ne[1];
438 const int64_t n_expert_used = ids->ne[0];
439
440 // note: n_tokens == 0 (no-output batch) must match so that the packing stays shape-independent
441 if (n_expert <= 0 || n_expert_used <= 0 || n_expert_used > n_expert ||
442 n_expert > GGML_METAL_TOPK_MOE_MAX_EXPERTS || n_expert_used > GGML_METAL_TOPK_MOE_MAX_EXPERTS) {
443 return false;
444 }
445
446 if (logits->ne[2] != 1 || logits->ne[3] != 1 ||
447 ids->ne[1] != n_tokens || ids->ne[2] != 1 || ids->ne[3] != 1 ||
448 out->ne[0] != 1 || out->ne[1] != n_expert_used || out->ne[2] != n_tokens || out->ne[3] != 1) {
449 return false;
450 }
451
452 if (!ggml_is_contiguous(logits) || !ggml_is_contiguous(out) ||
453 ids->nb[0] != ggml_type_size(GGML_TYPE_I32) ||
454 ids->nb[1] != ggml_type_size(GGML_TYPE_I32) * n_expert) {
455 return false;
456 }
457
458 if (probs_reshaped->src[0] != softmax || argsort->src[0] != softmax ||
459 ids->src[0] != argsort || get_rows->src[0] != probs_reshaped || get_rows->src[1] != ids) {
460 return false;
461 }
462
463 if (with_norm) {
464 const ggml_tensor * weights_reshaped = gf->nodes[raw_start + 5];
465 const ggml_tensor * sum_rows = gf->nodes[raw_start + 6];
466 const ggml_tensor * clamp = gf->nodes[raw_start + 7];
467 const ggml_tensor * div = gf->nodes[raw_start + 8];
468 const ggml_tensor * out_reshaped = gf->nodes[raw_start + 9];
469
470 if (weights_reshaped->src[0] != get_rows || sum_rows->src[0] != weights_reshaped ||
471 clamp->src[0] != sum_rows || div->src[0] != weights_reshaped || div->src[1] != clamp ||
472 out_reshaped->src[0] != div) {
473 return false;
474 }
475
476 if (with_scale) {
477 const ggml_tensor * scale_node = gf->nodes[raw_start + 10];
478 if (scale_node->src[0] != out_reshaped) {
479 return false;
480 }
481 }
482 } else if (with_scale) {
483 const ggml_tensor * scale_node = gf->nodes[raw_start + 5];
484 if (scale_node->src[0] != get_rows) {
485 return false;
486 }
487 }
488
489 const int outputs[2] = { raw_start + 3, raw_end };
490 if (!ggml_can_fuse_subgraph_ext(gf, raw_idxs, raw_count, ops_all.data(), outputs, 2)) {
491 return false;
492 }
493
494 if (mode == GGML_METAL_FUSION_FULL) {
495 if (!logits->data || !out->data || !ids->data) {
496 return false;
497 }
498 }
499
500 return true;
501}
502
503#define GGML_METAL_MOE_REDUCE_MAX_EXPERTS 8
504
505struct ggml_metal_moe_reduce_match {
506 const ggml_tensor * experts;
507 const ggml_tensor * weights;
508 const ggml_tensor * dst;
509 int node_count;
510};
511
512static bool ggml_metal_fusion_match_moe_reduce(
513 const ggml_cgraph * gf, int node_idx, const std::vector<ggml_op> & ops_all,
514 ggml_metal_moe_reduce_match * match) {
515 if (match == nullptr || node_idx < 0 || node_idx + (int) ops_all.size() > gf->n_nodes) {
516 return false;
517 }
518
519 const ggml_tensor * mul = gf->nodes[node_idx];
520 if (mul->op != GGML_OP_MUL || mul->type != GGML_TYPE_F32) {
521 return false;
522 }
523
524 // MUL, then one VIEW per expert, then one ADD per additional expert
525 const int raw_count = (int) ops_all.size();
526 const int n_expert_used = raw_count / 2;
527
528 if (n_expert_used < 2 || n_expert_used > GGML_METAL_MOE_REDUCE_MAX_EXPERTS ||
529 raw_count != 2 * n_expert_used) {
530 return false;
531 }
532
533 int n_views = 0;
534 while (node_idx + 1 + n_views < gf->n_nodes &&
535 gf->nodes[node_idx + 1 + n_views]->op == GGML_OP_VIEW) {
536 n_views++;
537 }
538
539 if (n_views != n_expert_used) {
540 return false;
541 }
542
543 for (int i = n_expert_used + 1; i < raw_count; ++i) {
544 if (gf->nodes[node_idx + i]->op != GGML_OP_ADD) {
545 return false;
546 }
547 }
548
549 int raw_idxs[GGML_METAL_FUSION_MAX];
550 for (int i = 0; i < raw_count; ++i) {
551 raw_idxs[i] = node_idx + i;
552 if (gf->nodes[node_idx + i]->op != ops_all[i]) {
553 return false;
554 }
555 }
556
557 const ggml_tensor * experts = mul->src[0];
558 const ggml_tensor * weights = mul->src[1];
559 const ggml_tensor * dst = gf->nodes[node_idx + raw_count - 1];
560
561 if (experts->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) {
562 return false;
563 }
564
565 const int64_t n_embd = experts->ne[0];
566 const int64_t n_tokens = experts->ne[2];
567
568 // note: n_tokens == 0 (no-output batch) must match so that the packing stays shape-independent
569 if (n_embd <= 0 || experts->ne[1] != n_expert_used || experts->ne[3] != 1 ||
570 weights->ne[0] != 1 || weights->ne[1] != n_expert_used || weights->ne[2] != n_tokens || weights->ne[3] != 1 ||
571 dst->ne[0] != n_embd || dst->ne[1] != n_tokens || dst->ne[2] != 1 || dst->ne[3] != 1) {
572 return false;
573 }
574
575 if (!ggml_is_contiguous(experts) || !ggml_is_contiguous(weights) || !ggml_is_contiguous(dst)) {
576 return false;
577 }
578
579 for (int i = 1; i <= n_expert_used; ++i) {
580 const ggml_tensor * view = gf->nodes[node_idx + i];
581 if (view->view_src != mul || view->src[0] != mul ||
582 view->view_offs != (size_t) (i - 1) * mul->nb[1] ||
583 view->ne[0] != n_embd || view->ne[1] != n_tokens ||
584 view->nb[1] != mul->nb[2]) {
585 return false;
586 }
587 }
588
589 const ggml_tensor * prev_add = nullptr;
590 for (int j = 1; j < n_expert_used; ++j) {
591 const ggml_tensor * add = gf->nodes[node_idx + n_expert_used + j];
592 const ggml_tensor * rhs = gf->nodes[node_idx + j + 1];
593 const ggml_tensor * lhs = j == 1 ? gf->nodes[node_idx + 1] : prev_add;
594 if (add->src[0] != lhs || add->src[1] != rhs) {
595 return false;
596 }
597 prev_add = add;
598 }
599
600 const int outputs[1] = { node_idx + raw_count - 1 };
601 if (!ggml_can_fuse_subgraph_ext(gf, raw_idxs, raw_count, ops_all.data(), outputs, 1)) {
602 return false;
603 }
604
605 match->experts = experts;
606 match->weights = weights;
607 match->dst = dst;
608 match->node_count = raw_count;
609 return true;
610}
611
612static bool ggml_metal_fusion_check_moe_reduce(
613 const ggml_metal_fusion * fusion,
614 const ggml_tensor * const * nodes,
615 const ggml_cgraph * gf,
616 const int * node_idxs,
617 int idx,
618 ggml_metal_fusion_mode mode) {
619 GGML_UNUSED(nodes);
620
621 ggml_metal_moe_reduce_match match;
622 if (!ggml_metal_fusion_match_moe_reduce(gf, node_idxs[idx], fusion->ops_all, &match)) {
623 return false;
624 }
625
626 if ((int) fusion->ops.size() != match.experts->ne[1]) {
627 return false;
628 }
629
630 const int raw_end = node_idxs[idx] + match.node_count - 1;
631 if (node_idxs[idx + (int) fusion->ops.size() - 1] != raw_end) {
632 return false;
633 }
634
635 if (mode == GGML_METAL_FUSION_FULL) {
636 if (!match.experts->data || !match.weights->data || !match.dst->data) {
637 return false;
638 }
639
640 // the fused kernel reads experts and weights while writing dst, so dst must not overlap either input
641 if (ggml_metal_fusion_overlap(match.dst, match.experts) || ggml_metal_fusion_overlap(match.dst, match.weights)) {
642 return false;
643 }
644 }
645
646 return true;
647}
648
649// true if t is or views a tensor in a buffer marked as weights, such as a bias; the model loader marks its buffers before
650// any graph is optimized, and tensors in unmarked or not yet allocated buffers count as non-weights in both phases
651static bool ggml_metal_tensor_is_weight(const struct ggml_tensor * t) {
652 const ggml_tensor * base = t->view_src != NULL ? t->view_src : t;
653
654 return base->buffer != NULL && ggml_backend_buffer_get_usage(base->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS;
655}
656
657static const struct ggml_tensor * ggml_metal_mul_mat_add_operand(const struct ggml_tensor * mm, const struct ggml_tensor * add) {
658 if (add->op != GGML_OP_ADD || (add->src[0] == mm) == (add->src[1] == mm)) {
659 return NULL;
660 }
661
662 const ggml_tensor * other = add->src[0] == mm ? add->src[1] : add->src[0];
663
664 const bool ok = other->type == GGML_TYPE_F32 && add->type == GGML_TYPE_F32 && !ggml_metal_tensor_is_weight(other);
665
666 return ok ? other : NULL;
667}
668
669static const struct ggml_tensor * ggml_metal_mul_mat_add_residual(const struct ggml_tensor * mm, const struct ggml_tensor * add) {
670 const ggml_tensor * res = ggml_metal_mul_mat_add_operand(mm, add);
671
672 const bool ok = res != NULL && ggml_are_same_shape(res, mm) &&
673 ggml_is_contiguous(res) && ggml_is_contiguous(mm) && ggml_is_contiguous(add);
674
675 return ok ? res : NULL;
676}
677
678// MUL_MAT + ADD of an f32 non-weight: the reorder packs it without reading row counts, so ubatch sizes share one order;
679// the encoder fuses only a same-shape residual in the few-row MMA store, which the sum may overlap only in place
680static bool ggml_metal_fusion_check_mul_mat_add(
681 const ggml_metal_fusion * fusion,
682 const ggml_tensor * const * nodes,
683 const ggml_cgraph * gf,
684 const int * node_idxs,
685 int idx,
686 ggml_metal_fusion_mode mode) {
687 GGML_UNUSED(gf);
688 GGML_UNUSED(node_idxs);
689 GGML_UNUSED(idx);
690 GGML_UNUSED(fusion);
691
692 const ggml_tensor * mm = nodes[0];
693 const ggml_tensor * add = nodes[1];
694
695 if (ggml_metal_mul_mat_add_operand(mm, add) == nullptr ||
696 !ggml_metal_op_mul_mat_may_use_mma(mm)) {
697 return false;
698 }
699
700 if (mode == GGML_METAL_FUSION_STRUCTURAL) {
701 return true;
702 }
703
704 const ggml_tensor * res = ggml_metal_mul_mat_add_residual(mm, add);
705
706 if (res == nullptr || !ggml_metal_op_mul_mat_use_mma(mm)) {
707 return false;
708 }
709
710 return !ggml_metal_fusion_overlap(add, mm->src[0]) && !ggml_metal_fusion_overlap(add, mm->src[1]) &&
711 (add->data == res->data || !ggml_metal_fusion_overlap(add, res));
712}
713
714// ---- patterns ------------------------------------------------------------
715
716static const std::vector<ggml_op> ops_norm_mul = { GGML_OP_NORM, GGML_OP_MUL };
717static const std::vector<ggml_op> ops_norm_mul_add = { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD };
718static const std::vector<ggml_op> ops_norm_scale = { GGML_OP_NORM, GGML_OP_SCALE };
719static const std::vector<ggml_op> ops_rms_norm_mul = { GGML_OP_RMS_NORM, GGML_OP_MUL };
720static const std::vector<ggml_op> ops_rms_norm_mul_add = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD };
721static const std::vector<ggml_op> ops_rms_norm_scale = { GGML_OP_RMS_NORM, GGML_OP_SCALE };
722
723static const std::vector<ggml_op> ops_add_2 = { GGML_OP_ADD, GGML_OP_ADD };
724static const std::vector<ggml_op> ops_add_3 = { GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD };
725static const std::vector<ggml_op> ops_add_4 = { GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD };
726static const std::vector<ggml_op> ops_add_5 = { GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD };
727static const std::vector<ggml_op> ops_add_6 = { GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD };
728static const std::vector<ggml_op> ops_add_7 = { GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD };
729static const std::vector<ggml_op> ops_snake = { GGML_OP_MUL, GGML_OP_SIN, GGML_OP_SQR, GGML_OP_MUL, GGML_OP_ADD };
730
731static const std::vector<ggml_op> ops_gdn_cache = { GGML_OP_GATED_DELTA_NET, GGML_OP_CPY };
732
733static const std::vector<ggml_op> ops_ssm_conv_silu = { GGML_OP_SSM_CONV, GGML_OP_UNARY };
734
735static const std::vector<ggml_op> ops_moe_reduce_2 = {
736 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_ADD
737};
738static const std::vector<ggml_op> ops_moe_reduce_3 = {
739 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_ADD, GGML_OP_ADD
740};
741static const std::vector<ggml_op> ops_moe_reduce_4 = {
742 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW,
743 GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD
744};
745static const std::vector<ggml_op> ops_moe_reduce_5 = {
746 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW,
747 GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD
748};
749static const std::vector<ggml_op> ops_moe_reduce_6 = {
750 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW,
751 GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD
752};
753static const std::vector<ggml_op> ops_moe_reduce_7 = {
754 GGML_OP_MUL, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW,
755 GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD
756};
757static const std::vector<ggml_op> ops_moe_reduce_8 = {
758 GGML_OP_MUL,
759 GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW, GGML_OP_VIEW,
760 GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD, GGML_OP_ADD
761};
762
763static const std::vector<ggml_op> ops_mul_mat_add = { GGML_OP_MUL_MAT, GGML_OP_ADD };
764
765static const std::vector<ggml_metal_fusion> ggml_metal_fusions = {
766 { GGML_METAL_FUSION_NORM_MUL, ops_norm_mul, {}, false, ggml_metal_fusion_check_norm },
767 { GGML_METAL_FUSION_NORM_MUL_ADD, ops_norm_mul_add, {}, false, ggml_metal_fusion_check_norm },
768 { GGML_METAL_FUSION_NORM_SCALE, ops_norm_scale, {}, false, ggml_metal_fusion_check_norm },
769 { GGML_METAL_FUSION_NORM_MUL, ops_rms_norm_mul, {}, false, ggml_metal_fusion_check_norm },
770 { GGML_METAL_FUSION_NORM_MUL_ADD, ops_rms_norm_mul_add, {}, false, ggml_metal_fusion_check_norm },
771 { GGML_METAL_FUSION_NORM_SCALE, ops_rms_norm_scale, {}, false, ggml_metal_fusion_check_norm },
772 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_2, {}, false, ggml_metal_fusion_check_add_chain },
773 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_3, {}, false, ggml_metal_fusion_check_add_chain },
774 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_4, {}, false, ggml_metal_fusion_check_add_chain },
775 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_5, {}, false, ggml_metal_fusion_check_add_chain },
776 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_6, {}, false, ggml_metal_fusion_check_add_chain },
777 { GGML_METAL_FUSION_ADD_CHAIN, ops_add_7, {}, false, ggml_metal_fusion_check_add_chain },
778 { GGML_METAL_FUSION_SNAKE, ops_snake, {}, false, ggml_metal_fusion_check_snake },
779 { GGML_METAL_FUSION_GDN_CACHE, ops_gdn_cache, {}, true, ggml_metal_fusion_check_gdn_cache },
780 { GGML_METAL_FUSION_TOPK_MOE, ops_topk_moe, {1}, true, ggml_metal_fusion_check_topk_moe },
781 { GGML_METAL_FUSION_TOPK_MOE, ops_topk_moe_scale, {1}, true, ggml_metal_fusion_check_topk_moe },
782 { GGML_METAL_FUSION_TOPK_MOE, ops_topk_moe_norm, {1}, true, ggml_metal_fusion_check_topk_moe },
783 { GGML_METAL_FUSION_TOPK_MOE, ops_topk_moe_norm_scale, {1}, true, ggml_metal_fusion_check_topk_moe },
784 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_2, {}, true, ggml_metal_fusion_check_moe_reduce },
785 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_3, {}, true, ggml_metal_fusion_check_moe_reduce },
786 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_4, {}, true, ggml_metal_fusion_check_moe_reduce },
787 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_5, {}, true, ggml_metal_fusion_check_moe_reduce },
788 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_6, {}, true, ggml_metal_fusion_check_moe_reduce },
789 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_7, {}, true, ggml_metal_fusion_check_moe_reduce },
790 { GGML_METAL_FUSION_MOE_REDUCE, ops_moe_reduce_8, {}, true, ggml_metal_fusion_check_moe_reduce },
791 { GGML_METAL_FUSION_SSM_CONV_SILU, ops_ssm_conv_silu, {}, false, ggml_metal_fusion_check_ssm_conv_silu },
792 { GGML_METAL_FUSION_MUL_MAT_ADD, ops_mul_mat_add, {}, false, ggml_metal_fusion_check_mul_mat_add },
793};
794
795// ---- alloc deps -----------------------------------------------------------
796
797static bool ggml_metal_fusion_match_raw_pattern(
798 const ggml_cgraph * gf, int node_idx, const std::vector<ggml_op> & ops) {
799 if (node_idx < 0 || node_idx + (int) ops.size() > gf->n_nodes) {
800 return false;
801 }
802
803 for (int i = 0; i < (int) ops.size(); ++i) {
804 if (gf->nodes[node_idx + i]->op != ops[i]) {
805 return false;
806 }
807 }
808
809 return true;
810}
811
812static void ggml_metal_fusion_add_pattern_alloc_deps(
813 void * user_data,
814 void (*add_alloc_dep)(void *, ggml_tensor *, ggml_tensor *),
815 ggml_cgraph * gf,
816 const ggml_metal_fusion * fusion,
817 int node_idx) {
818 const int last_node = node_idx + (int) fusion->ops_all.size() - 1;
819
820 // keep all external inputs alive until the fused output
821 std::set<ggml_tensor *> seen;
822 for (int j = 0; j < (int) fusion->ops_all.size(); ++j) {
823 ggml_tensor * node = gf->nodes[node_idx + j];
824 for (int s = 0; s < GGML_MAX_SRC; ++s) {
825 ggml_tensor * src = node->src[s];
826 if (src && seen.insert(src).second) {
827 add_alloc_dep(user_data, src, gf->nodes[last_node]);
828 }
829 }
830 seen.insert(node);
831 }
832}
833
834void ggml_metal_fusion_add_alloc_deps(
835 void * user_data,
836 void (*add_alloc_dep)(void *, ggml_tensor *, ggml_tensor *),
837 ggml_cgraph * gf) {
838 for (int i = 0; i < gf->n_nodes; ++i) {
839 const ggml_metal_fusion * best = nullptr;
840 int best_raw = 0;
841
842 for (const ggml_metal_fusion & fusion : ggml_metal_fusions) {
843 if ((int) fusion.ops_all.size() <= best_raw) {
844 continue;
845 }
846 if (ggml_metal_fusion_match_raw_pattern(gf, i, fusion.ops_all)) {
847 best = &fusion;
848 best_raw = (int) fusion.ops_all.size();
849 }
850 }
851
852 if (best) {
853 ggml_metal_fusion_add_pattern_alloc_deps(user_data, add_alloc_dep, gf, best, i);
854 i += best_raw - 1;
855 }
856 }
857}
858
859// ---- shared fusion info ---------------------------------------------------
860
861static std::string ggml_metal_fusion_label(const ggml_metal_fusion * fusion) {
862 GGML_ASSERT(fusion != nullptr);
863
864 std::string label;
865 for (int j = 0; j < (int) fusion->ops.size(); j++) {
866 if (j > 0) {
867 label += '+';
868 }
869 label += ggml_op_name(fusion->ops[j]);
870 }
871 return label;
872}
873
874struct ggml_metal_fusion_info {
875 std::vector<std::string> labels;
876 std::vector<uint64_t> counts;
877 bool enabled;
878 bool stats;
879 bool labels_set;
880 int debug;
881};
882
883struct ggml_metal_fusion_info * ggml_metal_fusion_info_init(bool enabled, int debug) {
884 ggml_metal_fusion_info * finfo = new ggml_metal_fusion_info;
885 finfo->enabled = enabled;
886 finfo->stats = debug > 0;
887 finfo->labels_set = false;
888 finfo->debug = debug;
889
890 if (finfo->stats) {
891 ggml_metal_fusion_info_labels_init(finfo);
892 }
893
894 return finfo;
895}
896
897void ggml_metal_fusion_info_free(ggml_metal_fusion_info * finfo) {
898 delete finfo;
899}
900
901bool ggml_metal_fusion_info_enabled(const ggml_metal_fusion_info * finfo) {
902 return finfo->enabled;
903}
904
905bool ggml_metal_fusion_info_stats(const ggml_metal_fusion_info * finfo) {
906 return finfo->stats;
907}
908
909int ggml_metal_fusion_info_debug(const ggml_metal_fusion_info * finfo) {
910 return finfo->debug;
911}
912
913int ggml_metal_fusion_info_n_fusions(const ggml_metal_fusion_info * finfo) {
914 return (int) finfo->labels.size();
915}
916
917const char * ggml_metal_fusion_info_label(const ggml_metal_fusion_info * finfo, int idx) {
918 GGML_ASSERT(idx >= 0 && idx < (int) finfo->labels.size());
919 return finfo->labels[idx].c_str();
920}
921
922uint64_t ggml_metal_fusion_info_count(const ggml_metal_fusion_info * finfo, int idx) {
923 GGML_ASSERT(idx >= 0 && idx < (int) finfo->counts.size());
924 return finfo->counts[idx];
925}
926
927void ggml_metal_fusion_info_count_fusion(ggml_metal_fusion_info * finfo, const ggml_metal_fusion * fusion) {
928 if (!finfo->stats || fusion == nullptr) {
929 return;
930 }
931
932 const ptrdiff_t idx = fusion - ggml_metal_fusions.data();
933 if (idx >= 0 && idx < (ptrdiff_t) finfo->counts.size()) {
934 finfo->counts[idx]++;
935 }
936}
937
938void ggml_metal_fusion_info_set_enabled(ggml_metal_fusion_info * finfo, bool enabled) {
939 finfo->enabled = enabled;
940}
941
942void ggml_metal_fusion_info_labels_init(ggml_metal_fusion_info * finfo) {
943 if (finfo->labels_set) {
944 return;
945 }
946
947 finfo->labels.clear();
948 finfo->counts.assign(ggml_metal_fusions.size(), 0);
949 finfo->labels.reserve(ggml_metal_fusions.size());
950
951 for (const ggml_metal_fusion & fusion : ggml_metal_fusions) {
952 finfo->labels.emplace_back(ggml_metal_fusion_label(&fusion));
953 }
954
955 finfo->labels_set = true;
956}
957
958void ggml_metal_fusion_info_stats_init(ggml_metal_fusion_info * finfo) {
959 finfo->stats = true;
960 ggml_metal_fusion_info_labels_init(finfo);
961}
962
963void ggml_metal_fusion_info_stats_reset(ggml_metal_fusion_info * finfo) {
964 std::fill(finfo->counts.begin(), finfo->counts.end(), 0);
965}
966
967int ggml_metal_fusion_info_stats_get(const ggml_metal_fusion_info * finfo, const char ** labels, uint64_t * counts, int n) {
968 const int n_fusions = (int) finfo->labels.size();
969
970 if (labels == nullptr) {
971 return n_fusions;
972 }
973
974 const int n_fill = std::min(n, n_fusions);
975 for (int i = 0; i < n_fill; i++) {
976 labels[i] = finfo->labels[i].c_str();
977 if (counts != nullptr) {
978 counts[i] = finfo->counts[i];
979 }
980 }
981
982 return n_fill;
983}
984
985// ---- memory-range checks -------------------------------------------------
986
987// reject fusions where an external source overlaps any fused output. the fused
988// kernels elide intermediate nodes, so only sources that are not part of the
989// fused subgraph can cause read/write races with the output.
990static bool ggml_metal_fusion_check_memory_ranges(
991 const ggml_metal_fusion * fusion,
992 const ggml_tensor * const * nodes,
993 int node_count) {
994 // some fused kernels write through a tensor that also appears as a source (e.g. the gdn
995 // cache cpy), so a source that is the same memory as the output is not an external read
996 // source
997 auto same_memory = [](const ggml_tensor * a, const ggml_tensor * b) {
998 if (a->data && b->data && a->data == b->data) {
999 return true;
1000 }
1001 for (const ggml_tensor * v = a; v; v = v->view_src) {
1002 if (v == b) {
1003 return true;
1004 }
1005 }
1006 for (const ggml_tensor * v = b; v; v = v->view_src) {
1007 if (v == a) {
1008 return true;
1009 }
1010 }
1011 return false;
1012 };
1013
1014 auto nodes_overlap = [](const ggml_tensor * a, const ggml_tensor * b) {
1015 if (!a || !b || !a->data || !b->data || !a->buffer || !b->buffer) {
1016 return false;
1017 }
1018
1019 if (a->buffer != b->buffer) {
1020 return false;
1021 }
1022
1023 const int64_t a_start = (int64_t) a->data;
1024 const int64_t a_end = a_start + ggml_backend_buft_get_alloc_size(a->buffer->buft, a);
1025 const int64_t b_start = (int64_t) b->data;
1026 const int64_t b_end = b_start + ggml_backend_buft_get_alloc_size(b->buffer->buft, b);
1027
1028 return (b_start <= a_start && a_start < b_end) ||
1029 (a_start <= b_start && b_start < a_end);
1030 };
1031
1032 auto is_intermediate = [](const ggml_tensor * src, const ggml_tensor * const * nodes, int j) {
1033 for (int k = 0; k < j; ++k) {
1034 if (src == nodes[k]) {
1035 return true;
1036 }
1037 for (const ggml_tensor * view_src = src->view_src; view_src; view_src = view_src->view_src) {
1038 if (view_src == nodes[k]) {
1039 return true;
1040 }
1041 }
1042 }
1043 return false;
1044 };
1045
1046 auto check_dst = [&](const ggml_tensor * dst) {
1047 for (int j = 0; j < node_count; ++j) {
1048 for (int s = 0; s < GGML_MAX_SRC; ++s) {
1049 const ggml_tensor * src = nodes[j]->src[s];
1050 if (!src || src->op == GGML_OP_NONE || same_memory(src, dst)) {
1051 continue;
1052 }
1053
1054 if (nodes_overlap(dst, src) && !is_intermediate(src, nodes, j)) {
1055 return false;
1056 }
1057 }
1058 }
1059 return true;
1060 };
1061
1062 if (!check_dst(nodes[node_count - 1])) {
1063 return false;
1064 }
1065
1066 for (int offset : fusion->outs) {
1067 GGML_ASSERT(offset >= 0 && offset < node_count);
1068 if (!check_dst(nodes[offset])) {
1069 return false;
1070 }
1071 }
1072
1073 return true;
1074}
1075
1076// ---- queries -------------------------------------------------------------
1077
1078// find the longest pattern matching the node sequence starting at idx
1079// (idx is a position in node_idxs, which maps to graph node indices)
1080const ggml_metal_fusion * ggml_metal_fusion_next(
1081 const ggml_cgraph * gf,
1082 const int * node_idxs,
1083 int n_idxs,
1084 int idx,
1085 ggml_metal_fusion_mode mode,
1086 int * n_out) {
1087 const ggml_metal_fusion * res = nullptr;
1088 int best = 1;
1089
1090 for (const ggml_metal_fusion & fusion : ggml_metal_fusions) {
1091 const int n_ops = (int) fusion.ops.size();
1092
1093 // only look for a longer match than the current best
1094 if (n_ops <= best) {
1095 continue;
1096 }
1097 if (idx + n_ops > n_idxs) {
1098 continue;
1099 }
1100
1101 const ggml_tensor * nodes[GGML_METAL_FUSION_MAX];
1102
1103 // the op sequence must match exactly
1104 bool ok = true;
1105 for (int j = 0; j < n_ops; j++) {
1106 nodes[j] = gf->nodes[node_idxs[idx + j]];
1107 if (nodes[j]->op != fusion.ops[j]) {
1108 ok = false;
1109 break;
1110 }
1111 }
1112 if (!ok) {
1113 continue;
1114 }
1115
1116 if (!fusion.unsafe) {
1117 // common element-wise chain constraints: each node reads the previous one,
1118 // and all nodes have the same shape
1119 for (int j = 1; j < n_ops && ok; j++) {
1120 if (nodes[j]->src[0] != nodes[j - 1] && nodes[j]->src[1] != nodes[j - 1]) {
1121 ok = false;
1122 break;
1123 }
1124 if (!ggml_are_same_shape(nodes[j], nodes[j - 1])) {
1125 ok = false;
1126 break;
1127 }
1128 }
1129 if (!ok) {
1130 continue;
1131 }
1132
1133 // primary output is the last node; additional outputs come from fusion.outs
1134 int outputs_buf[GGML_METAL_FUSION_MAX];
1135 outputs_buf[0] = node_idxs[idx + n_ops - 1];
1136 for (size_t i = 0; i < fusion.outs.size(); ++i) {
1137 const int out_offset = fusion.outs[i];
1138 GGML_ASSERT(out_offset >= 0 && out_offset < n_ops);
1139 outputs_buf[i + 1] = node_idxs[idx + out_offset];
1140 }
1141
1142 const int n_outputs = 1 + (int) fusion.outs.size();
1143
1144 // structural subgraph checks (op sequence, elidable uses, view containment)
1145 if (!ggml_can_fuse_subgraph_ext(gf, node_idxs + idx, n_ops, fusion.ops.data(), outputs_buf, n_outputs)) {
1146 continue;
1147 }
1148 }
1149
1150 // pattern-specific checks (the sole validator for unsafe patterns)
1151 if (fusion.check && !fusion.check(&fusion, nodes, gf, node_idxs, idx, mode)) {
1152 continue;
1153 }
1154
1155 // the compute phase has allocated tensors and can detect aliasing between
1156 // external sources and fused outputs; the optimizer phase cannot do this yet
1157 if (mode == GGML_METAL_FUSION_FULL &&
1158 !ggml_metal_fusion_check_memory_ranges(&fusion, nodes, n_ops)) {
1159 continue;
1160 }
1161
1162 best = n_ops;
1163 res = &fusion;
1164 }
1165
1166 *n_out = best;
1167
1168 return res;
1169}
1170
1171// optimize phase: maximum number of nodes starting at idx (a raw sequential graph index) that
1172// could be fused, chaining patterns back-to-back. matching runs on the same filtered (view
1173// transparent) node sequence that the compute phase uses, so the returned count is the raw index
1174// span from idx to the last matched node (intermediate views are packed along).
1175int ggml_metal_fusion_max(const ggml_cgraph * gf, int idx) {
1176 // a view node cannot start a pattern - pack it alone
1177 if (ggml_op_is_empty(gf->nodes[idx]->op)) {
1178 return 1;
1179 }
1180
1181 // collect the non-view node indices starting at idx; 0-element tensors are included so
1182 // that empty graphs pack like their non-empty counterparts (see ggml_metal_fusion_filter_ops)
1183 int idxs[GGML_METAL_FUSION_MAX];
1184 int n_idxs = 0;
1185 for (int i = idx; i < gf->n_nodes && n_idxs < GGML_METAL_FUSION_MAX; i++) {
1186 if (!ggml_op_is_empty(gf->nodes[i]->op)) {
1187 idxs[n_idxs++] = i;
1188 }
1189 }
1190 if (n_idxs == 0) {
1191 return 1;
1192 }
1193
1194 int total = 0;
1195 int i_f = 0;
1196
1197 while (i_f < n_idxs && total < GGML_METAL_FUSION_MAX) {
1198 int len = 1;
1199 const ggml_metal_fusion * fusion = ggml_metal_fusion_next(gf, idxs, n_idxs, i_f, GGML_METAL_FUSION_STRUCTURAL, &len);
1200 if (!fusion || total + len > GGML_METAL_FUSION_MAX) {
1201 break;
1202 }
1203
1204 total += len;
1205 i_f += len;
1206 }
1207
1208 if (i_f == 0) {
1209 return 1;
1210 }
1211
1212 // map the matched non-empty nodes back to the raw index span (views are included)
1213 return std::min(GGML_METAL_FUSION_MAX, idxs[i_f - 1] - idx + 1);
1214}