okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
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 { 14ggml_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) 23bool 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 27bool (* check )(const struct ggml_metal_fusion * fusion , 28const struct ggml_tensor * const * nodes , 29const struct ggml_cgraph * gf , 30const int * node_idxs , 31int idx , 32ggml_metal_fusion_mode mode ); 33}; 34 35ggml_metal_fusion_id ggml_metal_fusion_get_id (const ggml_metal_fusion * fusion ) { 36return 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 ) { 43if (!a || !b ) { 44return false; 45 } 46 47ggml_backend_buffer_t ba = a -> view_src ?a -> view_src -> buffer :a -> buffer ; 48ggml_backend_buffer_t bb = b -> view_src ?b -> view_src -> buffer :b -> buffer ; 49 50ggml_metal_buffer_t ca = (ggml_metal_buffer_t )ba -> context ; 51ggml_metal_buffer_t cb = (ggml_metal_buffer_t )bb -> context ; 52 53return 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 ( 61const ggml_metal_fusion * fusion , 62const ggml_tensor * const * nodes , 63const ggml_cgraph * gf , 64const int * node_idxs , 65int idx , 66ggml_metal_fusion_mode mode ) { 67GGML_UNUSED (mode ); 68GGML_UNUSED (gf ); 69GGML_UNUSED (node_idxs ); 70GGML_UNUSED (idx ); 71 72GGML_ASSERT (fusion -> ops .size () >=2 ); 73 74if (fusion -> id == GGML_METAL_FUSION_NORM_SCALE ) { 75GGML_ASSERT (fusion -> ops .size ()== 2 ); 76 77const ggml_tensor * scale = nodes [1 ]; 78if (scale -> op != GGML_OP_SCALE || scale -> src [0 ]!= nodes [0 ]|| scale -> src [1 ]|| 79scale -> type != GGML_TYPE_F32 ) { 80return false; 81 } 82 83return true; 84 } 85 86for (int j = 1 ;j < (int )fusion -> ops .size ();j ++ ) { 87// the fused MUL/ADD must read the previous node as src0 88if (nodes [j ]-> src [0 ]!= nodes [j - 1 ]) { 89return false; 90 } 91 92// the weight/bias must have the same row width as the norm input 93if (nodes [j ]-> src [1 ]-> ne [0 ]!= nodes [0 ]-> ne [0 ]) { 94return false; 95 } 96 97if (!ggml_is_contiguous_rows (nodes [j ]-> src [1 ])) { 98return false; 99 } 100 101if (nodes [j ]-> type != GGML_TYPE_F32 ) { 102return false; 103 } 104 } 105 106return true; 107} 108 109// SSM_CONV + UNARY (silu) 110static bool ggml_metal_fusion_check_ssm_conv_silu ( 111const ggml_metal_fusion * fusion , 112const ggml_tensor * const * nodes , 113const ggml_cgraph * gf , 114const int * node_idxs , 115int idx , 116ggml_metal_fusion_mode mode ) { 117GGML_UNUSED (fusion ); 118GGML_UNUSED (gf ); 119GGML_UNUSED (node_idxs ); 120GGML_UNUSED (idx ); 121GGML_UNUSED (mode ); 122 123const ggml_tensor * conv = nodes [0 ]; 124const ggml_tensor * un = nodes [1 ]; 125 126if (conv -> op != GGML_OP_SSM_CONV || un -> op != GGML_OP_UNARY || un -> src [0 ]!= conv || un -> src [1 ]) { 127return false; 128 } 129 130if (ggml_get_unary_op (un )!= GGML_UNARY_OP_SILU ) { 131return false; 132 } 133 134if (conv -> type != GGML_TYPE_F32 || un -> type != GGML_TYPE_F32 || !ggml_is_contiguous_rows (un )) { 135return false; 136 } 137 138return 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 ( 144const ggml_metal_fusion * fusion , 145const ggml_tensor * const * nodes , 146const ggml_cgraph * gf , 147const int * node_idxs , 148int idx , 149ggml_metal_fusion_mode mode ) { 150GGML_UNUSED (gf ); 151GGML_UNUSED (node_idxs ); 152GGML_UNUSED (idx ); 153GGML_ASSERT (fusion -> ops .size () >=2 ); 154 155for (int j = 1 ;j < (int )fusion -> ops .size ();j ++ ) { 156if (nodes [j ]-> src [0 ]!= nodes [j - 1 ]) { 157return false; 158 } 159 160if (!ggml_are_same_layout (nodes [j ]-> src [1 ],nodes [j - 1 ]-> src [1 ])) { 161return false; 162 } 163 164if (mode == GGML_METAL_FUSION_FULL ) { 165if (!ggml_metal_fusion_same_buffer (nodes [j ]-> src [1 ],nodes [0 ]-> src [1 ])) { 166return false; 167 } 168 } 169 } 170 171return 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 ( 180const ggml_metal_fusion * fusion , 181const ggml_tensor * const * nodes , 182const ggml_cgraph * gf , 183const int * node_idxs , 184int idx , 185ggml_metal_fusion_mode mode ) { 186GGML_UNUSED (fusion ); 187GGML_UNUSED (gf ); 188GGML_UNUSED (node_idxs ); 189GGML_UNUSED (idx ); 190 191const ggml_tensor * gdn = nodes [0 ]; 192const ggml_tensor * cpy = nodes [1 ]; 193 194// the kernel skips the snapshot tail, so the gdn output must not be a graph output 195if (gdn -> type != GGML_TYPE_F32 || (gdn -> flags & GGML_TENSOR_FLAG_OUTPUT )) { 196return false; 197 } 198 199if (cpy -> op != GGML_OP_CPY || (cpy -> flags & GGML_TENSOR_FLAG_OUTPUT )) { 200return false; 201 } 202 203const int64_t S_v = gdn -> src [2 ]-> ne [0 ]; 204const int64_t H = gdn -> src [2 ]-> ne [1 ]; 205const int64_t n_tokens = gdn -> src [2 ]-> ne [2 ]; 206const int64_t n_seqs = gdn -> src [2 ]-> ne [3 ]; 207const int64_t K = ggml_get_op_params_i32 (gdn ,0 ); 208const size_t tail_off = ggml_row_size (GGML_TYPE_F32 ,S_v * H * n_tokens * n_seqs ); 209 210const int64_t D = S_v * S_v * H ; 211const int64_t n_written = std::min < int64_t > (n_tokens ,K ); 212 213const ggml_tensor * src = cpy -> src [0 ];// gdn snapshot tail view 214const ggml_tensor * dst = cpy -> src [1 ];// cache view 215 216// src must be this gdn's snapshot tail (contiguous, at the tail offset) 217if (src -> op != GGML_OP_VIEW || src -> view_src != gdn || 218src -> view_offs != tail_off || !ggml_is_contiguous (src )) { 219return false; 220 } 221 222const int64_t expected_ne [GGML_MAX_DIMS ]= {D ,n_seqs ,n_written ,1 }; 223if (dst -> type != GGML_TYPE_F32 || 224 !std::equal (expected_ne ,expected_ne + GGML_MAX_DIMS ,dst -> ne )|| 225dst -> nb [0 ]!= ggml_type_size (GGML_TYPE_F32 )|| 226dst -> nb [1 ]!= ggml_row_size (GGML_TYPE_F32 ,D )) { 227return false; 228 } 229 230if (mode == GGML_METAL_FUSION_FULL ) { 231// the cache must be allocated so the kernel can write straight to its buffer 232if (dst -> data == nullptr ) { 233return false; 234 } 235 } 236 237return true; 238} 239 240// MUL + SIN + SQR + MUL + ADD (snake activation) 241static bool ggml_metal_fusion_check_snake ( 242const ggml_metal_fusion * fusion , 243const ggml_tensor * const * nodes , 244const ggml_cgraph * gf , 245const int * node_idxs , 246int idx , 247ggml_metal_fusion_mode mode ) { 248GGML_UNUSED (fusion ); 249GGML_UNUSED (mode ); 250GGML_UNUSED (gf ); 251GGML_UNUSED (node_idxs ); 252GGML_UNUSED (idx ); 253 254const ggml_tensor * mul0 = nodes [0 ]; 255const ggml_tensor * sin_node = nodes [1 ]; 256const ggml_tensor * sqr = nodes [2 ]; 257const ggml_tensor * mul1 = nodes [3 ]; 258const ggml_tensor * add = nodes [4 ]; 259 260// x carries the full activation shape, a is the broadcast operand 261const ggml_tensor * x = ggml_are_same_shape (mul0 ,mul0 -> src [0 ]) ?mul0 -> src [0 ] :mul0 -> src [1 ]; 262const 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 265const 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 268const 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. 272const 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 280const bool shape_ok = ggml_are_same_shape (a ,inv_b )&& a -> ne [0 ]== 1 && a -> ne [1 ]== x -> ne [1 ]; 281const 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 288const bool contig_ok = 289ggml_is_contiguous (x )&& ggml_is_contiguous (add )&& 290ggml_is_contiguous (a )&& ggml_is_contiguous (inv_b ); 291 292return 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 = { 301GGML_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 = { 304GGML_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 = { 307GGML_OP_SOFT_MAX ,GGML_OP_RESHAPE ,GGML_OP_ARGSORT ,GGML_OP_VIEW ,GGML_OP_GET_ROWS , 308GGML_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 = { 311GGML_OP_SOFT_MAX ,GGML_OP_RESHAPE ,GGML_OP_ARGSORT ,GGML_OP_VIEW ,GGML_OP_GET_ROWS , 312GGML_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 ( 316const ggml_metal_fusion * fusion , 317const ggml_tensor * const * nodes , 318const ggml_cgraph * gf , 319const int * node_idxs , 320int idx , 321ggml_metal_fusion_mode mode ) { 322GGML_ASSERT (fusion -> ops .size () >=3 ); 323GGML_UNUSED (nodes ); 324 325const int n_ops = (int )fusion -> ops .size (); 326 327const bool with_norm = n_ops >=6 ; 328const 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. 332const std::vector < ggml_op > & ops_all = fusion -> ops_all ; 333 334const int raw_start = node_idxs [idx ]; 335int 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 339if (with_norm && !with_scale ) { 340if (raw_end + 1 >=gf -> n_nodes ) { 341return false; 342 } 343const ggml_tensor * trailing_reshape = gf -> nodes [raw_end + 1 ]; 344if (trailing_reshape -> op != GGML_OP_RESHAPE || trailing_reshape -> src [0 ]!= gf -> nodes [raw_end ]) { 345return false; 346 } 347raw_end ++ ; 348 } 349 350const int raw_count = raw_end - raw_start + 1 ; 351if (raw_count != (int )ops_all .size ()) { 352return false; 353 } 354 355int raw_idxs [GGML_METAL_FUSION_MAX ]; 356for (int i = 0 ;i < raw_count ;++ i ) { 357raw_idxs [i ]= raw_start + i ; 358if (gf -> nodes [raw_start + i ]-> op != ops_all [i ]) { 359return false; 360 } 361 } 362 363const ggml_tensor * softmax = gf -> nodes [raw_start ]; 364const ggml_tensor * probs_reshaped = gf -> nodes [raw_start + 1 ]; 365const ggml_tensor * argsort = gf -> nodes [raw_start + 2 ]; 366const ggml_tensor * ids = gf -> nodes [raw_start + 3 ]; 367const ggml_tensor * get_rows = gf -> nodes [raw_start + 4 ]; 368const ggml_tensor * out = gf -> nodes [raw_end ]; 369const ggml_tensor * logits = softmax -> src [0 ]; 370 371// the fused kernel implements plain softmax only 372float scale = 1.0f ; 373float max_bias = 0.0f ; 374memcpy (& scale , ((const int32_t * )softmax -> op_params )+ 0 ,sizeof (scale )); 375memcpy (& max_bias , ((const int32_t * )softmax -> op_params )+ 1 ,sizeof (max_bias )); 376if (scale != 1.0f || max_bias != 0.0f || softmax -> src [1 ]|| softmax -> src [2 ]) { 377return false; 378 } 379 380if (logits -> type != GGML_TYPE_F32 || softmax -> type != GGML_TYPE_F32 || 381out -> type != GGML_TYPE_F32 || ids -> type != GGML_TYPE_I32 ) { 382return false; 383 } 384 385const int64_t n_expert = logits -> ne [0 ]; 386const int64_t n_tokens = logits -> ne [1 ]; 387const int64_t n_expert_used = ids -> ne [0 ]; 388 389if (n_expert <=0 || n_tokens <=0 || n_expert_used <=0 || n_expert_used > n_expert || 390n_expert > GGML_METAL_TOPK_MOE_MAX_EXPERTS || n_expert_used > GGML_METAL_TOPK_MOE_MAX_EXPERTS ) { 391return false; 392 } 393 394if (logits -> ne [2 ]!= 1 || logits -> ne [3 ]!= 1 || 395ids -> ne [1 ]!= n_tokens || ids -> ne [2 ]!= 1 || ids -> ne [3 ]!= 1 || 396out -> ne [0 ]!= 1 || out -> ne [1 ]!= n_expert_used || out -> ne [2 ]!= n_tokens || out -> ne [3 ]!= 1 ) { 397return false; 398 } 399 400if (!ggml_is_contiguous (logits )|| !ggml_is_contiguous (out )|| 401ids -> nb [0 ]!= ggml_type_size (GGML_TYPE_I32 )|| 402ids -> nb [1 ]!= ggml_type_size (GGML_TYPE_I32 )* n_expert ) { 403return false; 404 } 405 406if (probs_reshaped -> src [0 ]!= softmax || argsort -> src [0 ]!= softmax || 407ids -> src [0 ]!= argsort || get_rows -> src [0 ]!= probs_reshaped || get_rows -> src [1 ]!= ids ) { 408return false; 409 } 410 411if (with_norm ) { 412const ggml_tensor * weights_reshaped = gf -> nodes [raw_start + 5 ]; 413const ggml_tensor * sum_rows = gf -> nodes [raw_start + 6 ]; 414const ggml_tensor * clamp = gf -> nodes [raw_start + 7 ]; 415const ggml_tensor * div = gf -> nodes [raw_start + 8 ]; 416const ggml_tensor * out_reshaped = gf -> nodes [raw_start + 9 ]; 417 418if (weights_reshaped -> src [0 ]!= get_rows || sum_rows -> src [0 ]!= weights_reshaped || 419clamp -> src [0 ]!= sum_rows || div -> src [0 ]!= weights_reshaped || div -> src [1 ]!= clamp || 420out_reshaped -> src [0 ]!= div ) { 421return false; 422 } 423 424if (with_scale ) { 425const ggml_tensor * scale_node = gf -> nodes [raw_start + 10 ]; 426if (scale_node -> src [0 ]!= out_reshaped ) { 427return false; 428 } 429 } 430 }else if (with_scale ) { 431const ggml_tensor * scale_node = gf -> nodes [raw_start + 5 ]; 432if (scale_node -> src [0 ]!= get_rows ) { 433return false; 434 } 435 } 436 437const int outputs [2 ]= {raw_start + 3 ,raw_end }; 438if (!ggml_can_fuse_subgraph_ext (gf ,raw_idxs ,raw_count ,ops_all .data (),outputs ,2 )) { 439return false; 440 } 441 442if (mode == GGML_METAL_FUSION_FULL ) { 443if (!logits -> data || !out -> data || !ids -> data ) { 444return false; 445 } 446 } 447 448return true; 449} 450 451#define GGML_METAL_MOE_REDUCE_MAX_EXPERTS 8 452 453struct ggml_metal_moe_reduce_match { 454const ggml_tensor * experts ; 455const ggml_tensor * weights ; 456const ggml_tensor * dst ; 457int node_count ; 458}; 459 460static bool ggml_metal_fusion_match_moe_reduce ( 461const ggml_cgraph * gf ,int node_idx ,const std::vector < ggml_op > & ops_all , 462ggml_metal_moe_reduce_match * match ) { 463if (match == nullptr || node_idx < 0 || node_idx + (int )ops_all .size ()> gf -> n_nodes ) { 464return false; 465 } 466 467const ggml_tensor * mul = gf -> nodes [node_idx ]; 468if (mul -> op != GGML_OP_MUL || mul -> type != GGML_TYPE_F32 ) { 469return false; 470 } 471 472// MUL, then one VIEW per expert, then one ADD per additional expert 473const int raw_count = (int )ops_all .size (); 474const int n_expert_used = raw_count /2 ; 475 476if (n_expert_used < 2 || n_expert_used > GGML_METAL_MOE_REDUCE_MAX_EXPERTS || 477raw_count != 2 * n_expert_used ) { 478return false; 479 } 480 481int n_views = 0 ; 482while (node_idx + 1 + n_views < gf -> n_nodes && 483gf -> nodes [node_idx + 1 + n_views ]-> op == GGML_OP_VIEW ) { 484n_views ++ ; 485 } 486 487if (n_views != n_expert_used ) { 488return false; 489 } 490 491for (int i = n_expert_used + 1 ;i < raw_count ;++ i ) { 492if (gf -> nodes [node_idx + i ]-> op != GGML_OP_ADD ) { 493return false; 494 } 495 } 496 497int raw_idxs [GGML_METAL_FUSION_MAX ]; 498for (int i = 0 ;i < raw_count ;++ i ) { 499raw_idxs [i ]= node_idx + i ; 500if (gf -> nodes [node_idx + i ]-> op != ops_all [i ]) { 501return false; 502 } 503 } 504 505const ggml_tensor * experts = mul -> src [0 ]; 506const ggml_tensor * weights = mul -> src [1 ]; 507const ggml_tensor * dst = gf -> nodes [node_idx + raw_count - 1 ]; 508 509if (experts -> type != GGML_TYPE_F32 || weights -> type != GGML_TYPE_F32 || dst -> type != GGML_TYPE_F32 ) { 510return false; 511 } 512 513const int64_t n_embd = experts -> ne [0 ]; 514const int64_t n_tokens = experts -> ne [2 ]; 515 516if (n_embd <=0 || n_tokens <=0 || experts -> ne [1 ]!= n_expert_used || experts -> ne [3 ]!= 1 || 517weights -> ne [0 ]!= 1 || weights -> ne [1 ]!= n_expert_used || weights -> ne [2 ]!= n_tokens || weights -> ne [3 ]!= 1 || 518dst -> ne [0 ]!= n_embd || dst -> ne [1 ]!= n_tokens || dst -> ne [2 ]!= 1 || dst -> ne [3 ]!= 1 ) { 519return false; 520 } 521 522if (!ggml_is_contiguous (experts )|| !ggml_is_contiguous (weights )|| !ggml_is_contiguous (dst )) { 523return false; 524 } 525 526for (int i = 1 ;i <=n_expert_used ;++ i ) { 527const ggml_tensor * view = gf -> nodes [node_idx + i ]; 528if (view -> view_src != mul || view -> src [0 ]!= mul || 529view -> view_offs != (size_t ) (i - 1 )* mul -> nb [1 ]|| 530view -> ne [0 ]!= n_embd || view -> ne [1 ]!= n_tokens || 531view -> nb [1 ]!= mul -> nb [2 ]) { 532return false; 533 } 534 } 535 536const ggml_tensor * prev_add = nullptr ; 537for (int j = 1 ;j < n_expert_used ;++ j ) { 538const ggml_tensor * add = gf -> nodes [node_idx + n_expert_used + j ]; 539const ggml_tensor * rhs = gf -> nodes [node_idx + j + 1 ]; 540const ggml_tensor * lhs = j == 1 ?gf -> nodes [node_idx + 1 ] :prev_add ; 541if (add -> src [0 ]!= lhs || add -> src [1 ]!= rhs ) { 542return false; 543 } 544prev_add = add ; 545 } 546 547const int outputs [1 ]= {node_idx + raw_count - 1 }; 548if (!ggml_can_fuse_subgraph_ext (gf ,raw_idxs ,raw_count ,ops_all .data (),outputs ,1 )) { 549return false; 550 } 551 552match -> experts = experts ; 553match -> weights = weights ; 554match -> dst = dst ; 555match -> node_count = raw_count ; 556return true; 557} 558 559static bool ggml_metal_fusion_check_moe_reduce ( 560const ggml_metal_fusion * fusion , 561const ggml_tensor * const * nodes , 562const ggml_cgraph * gf , 563const int * node_idxs , 564int idx , 565ggml_metal_fusion_mode mode ) { 566GGML_UNUSED (nodes ); 567 568ggml_metal_moe_reduce_match match ; 569if (!ggml_metal_fusion_match_moe_reduce (gf ,node_idxs [idx ],fusion -> ops_all ,& match )) { 570return false; 571 } 572 573if ((int )fusion -> ops .size ()!= match .experts -> ne [1 ]) { 574return false; 575 } 576 577const int raw_end = node_idxs [idx ]+ match .node_count - 1 ; 578if (node_idxs [idx + (int )fusion -> ops .size ()- 1 ]!= raw_end ) { 579return false; 580 } 581 582if (mode == GGML_METAL_FUSION_FULL ) { 583if (!match .experts -> data || !match .weights -> data || !match .dst -> data ) { 584return false; 585 } 586 } 587 588return 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 = { 611GGML_OP_SOFT_MAX ,GGML_OP_ARGSORT ,GGML_OP_GET_ROWS 612}; 613static const std::vector < ggml_op > ops_topk_moe_scale = { 614GGML_OP_SOFT_MAX ,GGML_OP_ARGSORT ,GGML_OP_GET_ROWS ,GGML_OP_SCALE 615}; 616static const std::vector < ggml_op > ops_topk_moe_norm = { 617GGML_OP_SOFT_MAX ,GGML_OP_ARGSORT ,GGML_OP_GET_ROWS , 618GGML_OP_SUM_ROWS ,GGML_OP_CLAMP ,GGML_OP_DIV 619}; 620static const std::vector < ggml_op > ops_topk_moe_norm_scale = { 621GGML_OP_SOFT_MAX ,GGML_OP_ARGSORT ,GGML_OP_GET_ROWS , 622GGML_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 = { 636GGML_OP_MUL ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_ADD 637}; 638static const std::vector < ggml_op > ops_moe_reduce_all_3 = { 639GGML_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 = { 642GGML_OP_MUL ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW , 643GGML_OP_ADD ,GGML_OP_ADD ,GGML_OP_ADD 644}; 645static const std::vector < ggml_op > ops_moe_reduce_all_5 = { 646GGML_OP_MUL ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW , 647GGML_OP_ADD ,GGML_OP_ADD ,GGML_OP_ADD ,GGML_OP_ADD 648}; 649static const std::vector < ggml_op > ops_moe_reduce_all_6 = { 650GGML_OP_MUL ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW , 651GGML_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 = { 654GGML_OP_MUL ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW , 655GGML_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 = { 658GGML_OP_MUL , 659GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW ,GGML_OP_VIEW , 660GGML_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 ( 695const ggml_cgraph * gf ,int node_idx ,const std::vector < ggml_op > & ops ) { 696if (node_idx < 0 || node_idx + (int )ops .size ()> gf -> n_nodes ) { 697return false; 698 } 699 700for (int i = 0 ;i < (int )ops .size ();++ i ) { 701if (gf -> nodes [node_idx + i ]-> op != ops [i ]) { 702return false; 703 } 704 } 705 706return true; 707} 708 709static void ggml_metal_fusion_add_pattern_alloc_deps ( 710void * user_data , 711void (* add_alloc_dep )(void * ,ggml_tensor * ,ggml_tensor * ), 712ggml_cgraph * gf , 713const ggml_metal_fusion * fusion , 714int node_idx ) { 715const 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 ; 719for (int j = 0 ;j < (int )fusion -> ops_all .size ();++ j ) { 720ggml_tensor * node = gf -> nodes [node_idx + j ]; 721for (int s = 0 ;s < GGML_MAX_SRC ;++ s ) { 722ggml_tensor * src = node -> src [s ]; 723if (src && seen .insert (src ).second ) { 724add_alloc_dep (user_data ,src ,gf -> nodes [last_node ]); 725 } 726 } 727seen .insert (node ); 728 } 729} 730 731void ggml_metal_fusion_add_alloc_deps ( 732void * user_data , 733void (* add_alloc_dep )(void * ,ggml_tensor * ,ggml_tensor * ), 734ggml_cgraph * gf ) { 735for (int i = 0 ;i < gf -> n_nodes ;++ i ) { 736const ggml_metal_fusion * best = nullptr ; 737int best_raw = 0 ; 738 739for (const ggml_metal_fusion & fusion :ggml_metal_fusions ) { 740if ((int )fusion .ops_all .size () <=best_raw ) { 741continue ; 742 } 743if (ggml_metal_fusion_match_raw_pattern (gf ,i ,fusion .ops_all )) { 744best = & fusion ; 745best_raw = (int )fusion .ops_all .size (); 746 } 747 } 748 749if (best ) { 750ggml_metal_fusion_add_pattern_alloc_deps (user_data ,add_alloc_dep ,gf ,best ,i ); 751i += best_raw - 1 ; 752 } 753 } 754} 755 756// ---- shared fusion info --------------------------------------------------- 757 758static std::string ggml_metal_fusion_label (const ggml_metal_fusion * fusion ) { 759GGML_ASSERT (fusion != nullptr ); 760 761 std::string label ; 762for (int j = 0 ;j < (int )fusion -> ops .size ();j ++ ) { 763if (j > 0 ) { 764label += '+' ; 765 } 766label += ggml_op_name (fusion -> ops [j ]); 767 } 768return label ; 769} 770 771struct ggml_metal_fusion_info { 772 std::vector < std::string > labels ; 773 std::vector < uint64_t > counts ; 774bool enabled ; 775bool stats ; 776bool labels_set ; 777int debug ; 778}; 779 780struct ggml_metal_fusion_info * ggml_metal_fusion_info_init (bool enabled ,int debug ) { 781ggml_metal_fusion_info * finfo = new ggml_metal_fusion_info ; 782finfo -> enabled = enabled ; 783finfo -> stats = debug > 0 ; 784finfo -> labels_set = false; 785finfo -> debug = debug ; 786 787if (finfo -> stats ) { 788ggml_metal_fusion_info_labels_init (finfo ); 789 } 790 791return finfo ; 792} 793 794void ggml_metal_fusion_info_free (ggml_metal_fusion_info * finfo ) { 795delete finfo ; 796} 797 798bool ggml_metal_fusion_info_enabled (const ggml_metal_fusion_info * finfo ) { 799return finfo -> enabled ; 800} 801 802bool ggml_metal_fusion_info_stats (const ggml_metal_fusion_info * finfo ) { 803return finfo -> stats ; 804} 805 806int ggml_metal_fusion_info_debug (const ggml_metal_fusion_info * finfo ) { 807return finfo -> debug ; 808} 809 810int ggml_metal_fusion_info_n_fusions (const ggml_metal_fusion_info * finfo ) { 811return (int )finfo -> labels .size (); 812} 813 814const char * ggml_metal_fusion_info_label (const ggml_metal_fusion_info * finfo ,int idx ) { 815GGML_ASSERT (idx >=0 && idx < (int )finfo -> labels .size ()); 816return finfo -> labels [idx ].c_str (); 817} 818 819uint64_t ggml_metal_fusion_info_count (const ggml_metal_fusion_info * finfo ,int idx ) { 820GGML_ASSERT (idx >=0 && idx < (int )finfo -> counts .size ()); 821return finfo -> counts [idx ]; 822} 823 824void ggml_metal_fusion_info_count_fusion (ggml_metal_fusion_info * finfo ,const ggml_metal_fusion * fusion ) { 825if (!finfo -> stats || fusion == nullptr ) { 826return ; 827 } 828 829const ptrdiff_t idx = fusion - ggml_metal_fusions .data (); 830if (idx >=0 && idx < (ptrdiff_t )finfo -> counts .size ()) { 831finfo -> counts [idx ]++ ; 832 } 833} 834 835void ggml_metal_fusion_info_set_enabled (ggml_metal_fusion_info * finfo ,bool enabled ) { 836finfo -> enabled = enabled ; 837} 838 839void ggml_metal_fusion_info_labels_init (ggml_metal_fusion_info * finfo ) { 840if (finfo -> labels_set ) { 841return ; 842 } 843 844finfo -> labels .clear (); 845finfo -> counts .assign (ggml_metal_fusions .size (),0 ); 846finfo -> labels .reserve (ggml_metal_fusions .size ()); 847 848for (const ggml_metal_fusion & fusion :ggml_metal_fusions ) { 849finfo -> labels .emplace_back (ggml_metal_fusion_label (& fusion )); 850 } 851 852finfo -> labels_set = true; 853} 854 855void ggml_metal_fusion_info_stats_init (ggml_metal_fusion_info * finfo ) { 856finfo -> stats = true; 857ggml_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 ) { 865const int n_fusions = (int )finfo -> labels .size (); 866 867if (labels == nullptr ) { 868return n_fusions ; 869 } 870 871const int n_fill = std::min (n ,n_fusions ); 872for (int i = 0 ;i < n_fill ;i ++ ) { 873labels [i ]= finfo -> labels [i ].c_str (); 874if (counts != nullptr ) { 875counts [i ]= finfo -> counts [i ]; 876 } 877 } 878 879return 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 ( 888const ggml_metal_fusion * fusion , 889const ggml_tensor * const * nodes , 890int 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 894auto same_memory = [](const ggml_tensor * a ,const ggml_tensor * b ) { 895if (a -> data && b -> data && a -> data == b -> data ) { 896return true; 897 } 898for (const ggml_tensor * v = a ;v ;v = v -> view_src ) { 899if (v == b ) { 900return true; 901 } 902 } 903for (const ggml_tensor * v = b ;v ;v = v -> view_src ) { 904if (v == a ) { 905return true; 906 } 907 } 908return false; 909 }; 910 911auto nodes_overlap = [](const ggml_tensor * a ,const ggml_tensor * b ) { 912if (!a || !b || !a -> data || !b -> data || !a -> buffer || !b -> buffer ) { 913return false; 914 } 915 916if (a -> buffer != b -> buffer ) { 917return false; 918 } 919 920const int64_t a_start = (int64_t )a -> data ; 921const int64_t a_end = a_start + ggml_backend_buft_get_alloc_size (a -> buffer -> buft ,a ); 922const int64_t b_start = (int64_t )b -> data ; 923const int64_t b_end = b_start + ggml_backend_buft_get_alloc_size (b -> buffer -> buft ,b ); 924 925return (b_start <=a_start && a_start < b_end )|| 926 (a_start <=b_start && b_start < a_end ); 927 }; 928 929auto is_intermediate = [](const ggml_tensor * src ,const ggml_tensor * const * nodes ,int j ) { 930for (int k = 0 ;k < j ;++ k ) { 931if (src == nodes [k ]) { 932return true; 933 } 934for (const ggml_tensor * view_src = src -> view_src ;view_src ;view_src = view_src -> view_src ) { 935if (view_src == nodes [k ]) { 936return true; 937 } 938 } 939 } 940return false; 941 }; 942 943auto check_dst = [& ](const ggml_tensor * dst ) { 944for (int j = 0 ;j < node_count ;++ j ) { 945for (int s = 0 ;s < GGML_MAX_SRC ;++ s ) { 946const ggml_tensor * src = nodes [j ]-> src [s ]; 947if (!src || src -> op == GGML_OP_NONE || same_memory (src ,dst )) { 948continue ; 949 } 950 951if (nodes_overlap (dst ,src )&& !is_intermediate (src ,nodes ,j )) { 952return false; 953 } 954 } 955 } 956return true; 957 }; 958 959if (!check_dst (nodes [node_count - 1 ])) { 960return false; 961 } 962 963for (int offset :fusion -> outs ) { 964GGML_ASSERT (offset >=0 && offset < node_count ); 965if (!check_dst (nodes [offset ])) { 966return false; 967 } 968 } 969 970return 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 ( 978const ggml_cgraph * gf , 979const int * node_idxs , 980int n_idxs , 981int idx , 982ggml_metal_fusion_mode mode , 983int * n_out ) { 984const ggml_metal_fusion * res = nullptr ; 985int best = 1 ; 986 987for (const ggml_metal_fusion & fusion :ggml_metal_fusions ) { 988const int n_ops = (int )fusion .ops .size (); 989 990// only look for a longer match than the current best 991if (n_ops <=best ) { 992continue ; 993 } 994if (idx + n_ops > n_idxs ) { 995continue ; 996 } 997 998const ggml_tensor * nodes [GGML_METAL_FUSION_MAX ]; 999 1000// the op sequence must match exactly 1001bool ok = true; 1002for (int j = 0 ;j < n_ops ;j ++ ) { 1003nodes [j ]= gf -> nodes [node_idxs [idx + j ]]; 1004if (nodes [j ]-> op != fusion .ops [j ]) { 1005ok = false; 1006break ; 1007 } 1008 } 1009if (!ok ) { 1010continue ; 1011 } 1012 1013if (!fusion .unsafe ) { 1014// common element-wise chain constraints: each node reads the previous one, 1015// and all nodes have the same shape 1016for (int j = 1 ;j < n_ops && ok ;j ++ ) { 1017if (nodes [j ]-> src [0 ]!= nodes [j - 1 ]&& nodes [j ]-> src [1 ]!= nodes [j - 1 ]) { 1018ok = false; 1019break ; 1020 } 1021if (!ggml_are_same_shape (nodes [j ],nodes [j - 1 ])) { 1022ok = false; 1023break ; 1024 } 1025 } 1026if (!ok ) { 1027continue ; 1028 } 1029 1030// primary output is the last node; additional outputs come from fusion.outs 1031int outputs_buf [GGML_METAL_FUSION_MAX ]; 1032outputs_buf [0 ]= node_idxs [idx + n_ops - 1 ]; 1033for (size_t i = 0 ;i < fusion .outs .size ();++ i ) { 1034const int out_offset = fusion .outs [i ]; 1035GGML_ASSERT (out_offset >=0 && out_offset < n_ops ); 1036outputs_buf [i + 1 ]= node_idxs [idx + out_offset ]; 1037 } 1038 1039const int n_outputs = 1 + (int )fusion .outs .size (); 1040 1041// structural subgraph checks (op sequence, elidable uses, view containment) 1042if (!ggml_can_fuse_subgraph_ext (gf ,node_idxs + idx ,n_ops ,fusion .ops .data (),outputs_buf ,n_outputs )) { 1043continue ; 1044 } 1045 } 1046 1047// pattern-specific checks (the sole validator for unsafe patterns) 1048if (fusion .check && !fusion .check (& fusion ,nodes ,gf ,node_idxs ,idx ,mode )) { 1049continue ; 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 1054if (mode == GGML_METAL_FUSION_FULL && 1055 !ggml_metal_fusion_check_memory_ranges (& fusion ,nodes ,n_ops )) { 1056continue ; 1057 } 1058 1059best = n_ops ; 1060res = & fusion ; 1061 } 1062 1063* n_out = best ; 1064 1065return 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 1074if (ggml_op_is_empty (gf -> nodes [idx ]-> op )|| ggml_is_empty (gf -> nodes [idx ])) { 1075return 1 ; 1076 } 1077 1078// collect the non-empty node indices starting at idx 1079int idxs [GGML_METAL_FUSION_MAX ]; 1080int n_idxs = 0 ; 1081for (int i = idx ;i < gf -> n_nodes && n_idxs < GGML_METAL_FUSION_MAX ;i ++ ) { 1082if (!ggml_op_is_empty (gf -> nodes [i ]-> op )&& !ggml_is_empty (gf -> nodes [i ])) { 1083idxs [n_idxs ++ ]= i ; 1084 } 1085 } 1086if (n_idxs == 0 ) { 1087return 1 ; 1088 } 1089 1090int total = 0 ; 1091int i_f = 0 ; 1092 1093while (i_f < n_idxs && total < GGML_METAL_FUSION_MAX ) { 1094int len = 1 ; 1095const ggml_metal_fusion * fusion = ggml_metal_fusion_next (gf ,idxs ,n_idxs ,i_f ,GGML_METAL_FUSION_STRUCTURAL ,& len ); 1096if (!fusion || total + len > GGML_METAL_FUSION_MAX ) { 1097break ; 1098 } 1099 1100total += len ; 1101i_f += len ; 1102 } 1103 1104if (i_f == 0 ) { 1105return 1 ; 1106 } 1107 1108// map the matched non-empty nodes back to the raw index span (views are included) 1109return std::min (GGML_METAL_FUSION_MAX ,idxs [i_f - 1 ]- idx + 1 ); 1110}