okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

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