okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#include "ggml-metal-common.h" 2#include "ggml-metal-fusion.h" 3 4#include "ggml.h" 5#include "ggml-impl.h" 6#include "ggml-backend-impl.h" 7 8#include <vector> 9 10// must stay in sync with the kernel_fwht_<type>_<N> templates in misc.metal 11static bool ggml_metal_fwht_supported_size (int64_t n ) { 12return n == 64 || n == 128 || n == 256 || n == 512 ; 13} 14 15// the FWHT kernels handle a Hadamard-hinted MUL_MAT only under these conditions. supports_op 16// and the dispatch must ask the same question: an F16 src1 that is admitted but then falls 17// through reaches the generic path, which has no F32 src0 by F16 src1 kernel. 18bool ggml_metal_op_mul_mat_use_fwht (const struct ggml_tensor * op ) { 19return ggml_get_op_params_i32 (op ,1 )== GGML_HINT_SRC0_IS_HADAMARD && 20op -> type == GGML_TYPE_F32 && 21 (op -> src [1 ]-> type == GGML_TYPE_F32 || op -> src [1 ]-> type == GGML_TYPE_F16 )&& 22ggml_is_contiguous (op -> src [1 ])&& 23ggml_is_contiguous (op )&& 24ggml_are_same_shape (op -> src [1 ],op )&& 25ggml_metal_fwht_supported_size (op -> src [1 ]-> ne [0 ]); 26} 27 28bool ggml_metal_op_mul_mat_use_mm (const struct ggml_tensor * op ,bool has_simdgroup_mm ) { 29const int64_t ne00 = op -> src [0 ]-> ne [0 ]; 30const int64_t ne11 = op -> src [1 ]-> ne [1 ]; 31 32return !ggml_is_transposed (op -> src [0 ])&& 33 !ggml_is_transposed (op -> src [1 ])&& 34has_simdgroup_mm && ne00 >=64 && ne11 > 8 ; 35} 36 37bool ggml_metal_op_mul_mat_id_use_mm (const struct ggml_tensor * op ,bool has_simdgroup_mm ) { 38const int64_t ne00 = op -> src [0 ]-> ne [0 ]; 39const int64_t ne21 = op -> src [2 ]-> ne [1 ]; 40 41return has_simdgroup_mm && ne00 >=64 && ne21 >=32 ; 42} 43 44// represents a memory range (i.e. an interval from a starting address p0 to an ending address p1 in a given buffer pb) 45// the type indicates whether it is a source range (i.e. ops read data from it) or a destination range (i.e. ops write data to it) 46struct ggml_mem_range { 47uint64_t pb ;// buffer id 48 49uint64_t p0 ;// begin 50uint64_t p1 ;// end 51 52ggml_mem_range_type pt ; 53}; 54 55struct ggml_mem_ranges { 56 std::vector < ggml_mem_range > ranges ; 57 58int debug = 0 ; 59}; 60 61ggml_mem_ranges_t ggml_mem_ranges_init (int debug ) { 62auto * res = new ggml_mem_ranges ; 63 64res -> ranges .reserve (256 ); 65res -> debug = debug ; 66 67return res ; 68} 69 70void ggml_mem_ranges_free (ggml_mem_ranges_t mrs ) { 71delete mrs ; 72} 73 74void ggml_mem_ranges_reset (ggml_mem_ranges_t mrs ) { 75mrs -> ranges .clear (); 76} 77 78static bool ggml_mem_ranges_add (ggml_mem_ranges_t mrs ,ggml_mem_range mr ) { 79mrs -> ranges .push_back (mr ); 80 81return true; 82} 83 84static ggml_mem_range ggml_mem_range_from_tensor (const ggml_tensor * tensor ,ggml_mem_range_type pt ) { 85// always use the base tensor 86tensor = tensor -> view_src ?tensor -> view_src :tensor ; 87 88GGML_ASSERT (!tensor -> view_src ); 89 90ggml_mem_range mr ; 91 92if (tensor -> buffer ) { 93// when the tensor is allocated, use the actual memory address range in the buffer 94// 95// take the actual allocated size with ggml_backend_buft_get_alloc_size() 96// this can be larger than the tensor size if the buffer type allocates extra memory 97// ref: https://github.com/ggml-org/llama.cpp/pull/15966 98mr = { 99/*.pb =*/ (uint64_t )tensor -> buffer , 100/*.p0 =*/ (uint64_t )tensor -> data , 101/*.p1 =*/ (uint64_t )tensor -> data + ggml_backend_buft_get_alloc_size (tensor -> buffer -> buft ,tensor ), 102/*.pt =*/ pt , 103 }; 104 }else { 105// otherwise, the pointer address is used as an unique id of the memory ranges 106// that the tensor will be using when it is allocated 107mr = { 108/*.pb =*/ (uint64_t )tensor , 109/*.p0 =*/ 0 ,// 110/*.p1 =*/ 1024 ,// [0, 1024) is a dummy range, not used 111/*.pt =*/ pt , 112 }; 113 }; 114 115return mr ; 116} 117 118static ggml_mem_range ggml_mem_range_from_tensor_src (const ggml_tensor * tensor ) { 119return ggml_mem_range_from_tensor (tensor ,MEM_RANGE_TYPE_SRC ); 120} 121 122static ggml_mem_range ggml_mem_range_from_tensor_dst (const ggml_tensor * tensor ) { 123return ggml_mem_range_from_tensor (tensor ,MEM_RANGE_TYPE_DST ); 124} 125 126static bool ggml_mem_ranges_add_src (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 127GGML_ASSERT (tensor ); 128 129ggml_mem_range mr = ggml_mem_range_from_tensor_src (tensor ); 130 131if (mrs -> debug > 2 ) { 132GGML_LOG_DEBUG ("%s: add src range buf=%lld, [%lld, %lld)\n" ,__func__ ,mr .pb ,mr .p0 ,mr .p1 ); 133 } 134 135return ggml_mem_ranges_add (mrs ,mr ); 136} 137 138static bool ggml_mem_ranges_add_dst (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 139GGML_ASSERT (tensor ); 140 141ggml_mem_range mr = ggml_mem_range_from_tensor_dst (tensor ); 142 143if (mrs -> debug > 2 ) { 144GGML_LOG_DEBUG ("%s: add dst range buf=%lld, [%lld, %lld)\n" ,__func__ ,mr .pb ,mr .p0 ,mr .p1 ); 145 } 146 147return ggml_mem_ranges_add (mrs ,mr ); 148} 149 150bool ggml_mem_ranges_add (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 151for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 152if (tensor -> src [i ]) { 153ggml_mem_ranges_add_src (mrs ,tensor -> src [i ]); 154 } 155 } 156 157return ggml_mem_ranges_add_dst (mrs ,tensor ); 158} 159 160static bool ggml_mem_ranges_check (ggml_mem_ranges_t mrs ,ggml_mem_range mr ) { 161for (size_t i = 0 ;i < mrs -> ranges .size ();i ++ ) { 162const auto & cmp = mrs -> ranges [i ]; 163 164// two memory ranges cannot intersect if they are in different buffers 165if (mr .pb != cmp .pb ) { 166continue ; 167 } 168 169// intersecting source ranges are allowed 170if (mr .pt == MEM_RANGE_TYPE_SRC && cmp .pt == MEM_RANGE_TYPE_SRC ) { 171continue ; 172 } 173 174if (mr .p0 < cmp .p1 && mr .p1 >=cmp .p0 ) { 175if (mrs -> debug > 2 ) { 176GGML_LOG_DEBUG ("%s: the %s range buf=%lld, [%lld, %lld) overlaps with a previous %s range buf=%lld, [%lld, %lld)\n" , 177__func__ , 178mr .pt == MEM_RANGE_TYPE_SRC ?"src" :"dst" , 179mr .pb ,mr .p0 ,mr .p1 , 180cmp .pt == MEM_RANGE_TYPE_SRC ?"src" :"dst" , 181cmp .pb ,cmp .p0 ,cmp .p1 ); 182 } 183 184return false; 185 } 186 } 187 188return true; 189} 190 191static bool ggml_mem_ranges_check_src (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 192GGML_ASSERT (tensor ); 193 194ggml_mem_range mr = ggml_mem_range_from_tensor_src (tensor ); 195 196const bool res = ggml_mem_ranges_check (mrs ,mr ); 197 198return res ; 199} 200 201static bool ggml_mem_ranges_check_dst (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 202GGML_ASSERT (tensor ); 203 204ggml_mem_range mr = ggml_mem_range_from_tensor_dst (tensor ); 205 206const bool res = ggml_mem_ranges_check (mrs ,mr ); 207 208return res ; 209} 210 211bool ggml_mem_ranges_check (ggml_mem_ranges_t mrs ,const ggml_tensor * tensor ) { 212for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 213if (tensor -> src [i ]) { 214if (!ggml_mem_ranges_check_src (mrs ,tensor -> src [i ])) { 215return false; 216 } 217 } 218 } 219 220return ggml_mem_ranges_check_dst (mrs ,tensor ); 221} 222 223struct node_info { 224ggml_tensor * node ; 225 226 std::vector < ggml_tensor *> fused ; 227 228ggml_op op ()const { 229return node -> op ; 230 } 231 232const ggml_tensor * dst ()const { 233return fused .empty () ?node :fused .back (); 234 } 235 236bool is_empty ()const { 237return ggml_op_is_empty (node -> op ); 238 } 239 240void add_fused (ggml_tensor * t ) { 241fused .push_back (t ); 242 } 243 244bool is_output (const ggml_tensor * t )const { 245if (t == node ) { 246return true; 247 } 248for (const auto * f :fused ) { 249if (t == f ) { 250return true; 251 } 252 } 253return false; 254 } 255}; 256 257static std::vector < int > ggml_metal_graph_optimize_reorder (const std::vector < node_info > & nodes ) { 258// helper to add node src and dst ranges 259const auto & h_add = [](ggml_mem_ranges_t mrs ,const node_info & node ) { 260// only external sources matter: sources produced by the fused group are internal 261for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 262const ggml_tensor * src = node .node -> src [i ]; 263if (src && !node .is_output (src )) { 264if (!ggml_mem_ranges_add_src (mrs ,src )) { 265return false; 266 } 267 } 268 } 269 270for (const auto * fused :node .fused ) { 271for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 272const ggml_tensor * src = fused -> src [i ]; 273if (src && !node .is_output (src )) { 274if (!ggml_mem_ranges_add_src (mrs ,src )) { 275return false; 276 } 277 } 278 } 279 } 280 281// all fused tensors are produced by the fused kernel 282if (!ggml_mem_ranges_add_dst (mrs ,node .node )) { 283return false; 284 } 285for (const auto * fused :node .fused ) { 286if (!ggml_mem_ranges_add_dst (mrs ,fused )) { 287return false; 288 } 289 } 290 291return true; 292 }; 293 294// helper to check if a node can run concurrently with the existing set of nodes 295const auto & h_check = [](ggml_mem_ranges_t mrs ,const node_info & node ) { 296for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 297const ggml_tensor * src = node .node -> src [i ]; 298if (src && !node .is_output (src )) { 299if (!ggml_mem_ranges_check_src (mrs ,src )) { 300return false; 301 } 302 } 303 } 304 305for (const auto * fused :node .fused ) { 306for (int i = 0 ;i < GGML_MAX_SRC ;i ++ ) { 307const ggml_tensor * src = fused -> src [i ]; 308if (src && !node .is_output (src )) { 309if (!ggml_mem_ranges_check_src (mrs ,src )) { 310return false; 311 } 312 } 313 } 314 } 315 316if (!ggml_mem_ranges_check_dst (mrs ,node .node )) { 317return false; 318 } 319for (const auto * fused :node .fused ) { 320if (!ggml_mem_ranges_check_dst (mrs ,fused )) { 321return false; 322 } 323 } 324 325return true; 326 }; 327 328// perform reorders only across these types of ops 329// can be expanded when needed 330const auto & h_safe = [](ggml_op op ) { 331switch (op ) { 332case GGML_OP_MUL_MAT : 333case GGML_OP_MUL_MAT_ID : 334case GGML_OP_ROPE : 335case GGML_OP_NORM : 336case GGML_OP_RMS_NORM : 337case GGML_OP_GROUP_NORM : 338case GGML_OP_L2_NORM : 339case GGML_OP_SUM_ROWS : 340case GGML_OP_SSM_CONV : 341case GGML_OP_SSM_SCAN : 342case GGML_OP_CLAMP : 343case GGML_OP_TRI : 344case GGML_OP_DIAG : 345case GGML_OP_MUL : 346case GGML_OP_ADD : 347case GGML_OP_SUB : 348case GGML_OP_DIV : 349case GGML_OP_GLU : 350case GGML_OP_SCALE : 351case GGML_OP_UNARY : 352case GGML_OP_GET_ROWS : 353case GGML_OP_SET_ROWS : 354case GGML_OP_SET : 355case GGML_OP_CPY : 356case GGML_OP_CONT : 357case GGML_OP_REPEAT : 358return true; 359default : 360return ggml_op_is_empty (op ); 361 } 362 }; 363 364const int n = nodes .size (); 365 366 std::vector < int > res ; 367res .reserve (n ); 368 369 std::vector < bool > used (n ,false ); 370 371// the memory ranges for the set of currently concurrent nodes 372ggml_mem_ranges_t mrs0 = ggml_mem_ranges_init (0 ); 373 374// the memory ranges for the set of nodes that haven't been processed yet, when looking forward for a node to reorder 375ggml_mem_ranges_t mrs1 = ggml_mem_ranges_init (0 ); 376 377for (int i0 = 0 ;i0 < n ;i0 ++ ) { 378if (used [i0 ]) { 379continue ; 380 } 381 382const auto & node0 = nodes [i0 ]; 383 384// the node is not concurrent with the existing concurrent set, so we have to "put a barrier" (i.e reset mrs0) 385// but before we do that, look forward for some other nodes that can be added to the concurrent set mrs0 386// 387// note: we can always add empty nodes to the concurrent set as they don't read nor write anything 388if (!node0 .is_empty ()&& !h_check (mrs0 ,node0 )) { 389// this will hold the set of memory ranges from the nodes that haven't been processed yet 390// if a node is not concurrent with this set, we cannot reorder it 391ggml_mem_ranges_reset (mrs1 ); 392 393// initialize it with the current node 394h_add (mrs1 ,node0 ); 395 396// that many nodes forward to search for a concurrent node 397constexpr int N_FORWARD = 64 ; 398 399for (int i1 = i0 + 1 ;i1 < i0 + N_FORWARD && i1 < n ;i1 ++ ) { 400if (used [i1 ]) { 401continue ; 402 } 403 404const auto & node1 = nodes [i1 ]; 405 406// disallow reordering of certain ops 407if (!h_safe (node1 .op ())) { 408break ; 409 } 410 411const bool is_empty = node1 .is_empty (); 412 413// to reorder a node and add it to the concurrent set, it has to be: 414// + empty or concurrent with all nodes in the existing concurrent set (mrs0) 415// + concurrent with all nodes prior to it that haven't been processed yet (mrs1) 416if ((is_empty || h_check (mrs0 ,node1 ))&& h_check (mrs1 ,node1 )) { 417// add the node to the existing concurrent set (i.e. reorder it for early execution) 418h_add (mrs0 ,node1 ); 419res .push_back (i1 ); 420 421// mark as used, so we skip re-processing it later 422used [i1 ]= true; 423 }else { 424// expand the set of nodes that haven't been processed yet 425h_add (mrs1 ,node1 ); 426 } 427 } 428 429// finalize the concurrent set and begin a new one 430ggml_mem_ranges_reset (mrs0 ); 431 } 432 433// expand the concurrent set with the current node 434 { 435h_add (mrs0 ,node0 ); 436res .push_back (i0 ); 437 } 438 } 439 440ggml_mem_ranges_free (mrs0 ); 441ggml_mem_ranges_free (mrs1 ); 442 443return res ; 444} 445 446void ggml_graph_optimize (ggml_cgraph * gf ) { 447const int n = gf -> n_nodes ; 448 449 std::vector < node_info > nodes ; 450nodes .reserve (gf -> n_nodes ); 451 452// fuse nodes: 453// we don't want to make reorders that break fusing, so we first pack all fusable tensors 454// and perform the reorder over the fused nodes. after the reorder is done, we unfuse 455// 456// the fusable sequences are declared in the fusion table (ggml-metal-fuse.cpp), so the 457// packing here is driven by the same patterns that the op encoders will later use 458for (int i = 0 ;i < n ;i ++ ) { 459node_info node = { 460/*.node =*/ gf -> nodes [i ], 461/*.fused =*/ {}, 462 }; 463 464const int f = ggml_metal_fusion_max (gf ,i ); 465 466// add the fused tensors into the node info so we can unfuse them later 467for (int k = 1 ;k < f ;k ++ ) { 468++ i ; 469 470// the .dst() becomes the last fused tensor 471node .add_fused (gf -> nodes [i ]); 472 } 473 474nodes .push_back (std::move (node )); 475 } 476 477#if 1 478// reorder to improve concurrency 479const auto order = ggml_metal_graph_optimize_reorder (nodes ); 480#else 481 std::vector < int > order (nodes .size ()); 482for (size_t i = 0 ;i < nodes .size ();i ++ ) { 483order [i ]= i ; 484 } 485#endif 486 487// unfuse 488 { 489int j = 0 ; 490for (const auto i :order ) { 491const auto & node = nodes [i ]; 492 493gf -> nodes [j ++ ]= node .node ; 494 495for (auto * fused :node .fused ) { 496gf -> nodes [j ++ ]= fused ; 497 } 498 } 499 } 500}