okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#import "ggml-metal-context.h" 2 3#import "ggml-impl.h" 4#import "ggml-backend-impl.h" 5 6#import "ggml-metal-impl.h" 7#import "ggml-metal-common.h" 8#import "ggml-metal-ops.h" 9#import "ggml-metal-fusion.h" 10 11#import <Foundation/Foundation.h> 12 13#import <Metal/Metal.h> 14 15#undef MIN 16#undef MAX 17#define MIN(a, b) ((a) < (b) ? (a) : (b)) 18#define MAX(a, b) ((a) > (b) ? (a) : (b)) 19 20// max number of MTLCommandBuffer used to submit a graph for processing 21# define GGML_METAL_MAX_COMMAND_BUFFERS 8 22 23struct ggml_metal_command_buffer { 24id < MTLCommandBuffer > obj ; 25}; 26 27struct ggml_metal { 28char name[128]; 29 30ggml_metal_device_t dev; 31ggml_metal_library_t lib; 32 33ggml_metal_event_t ev_cpy; // for async copies 34g gml_metal_event_t ev_sync; // destination completion signal 35 36d ispatch_queue_t d_queue; 37 38// additional, inference - time compiled pipelines 39ggml_metal_pipelines_t pipelines_ext; 40 41bool use_concurrency; 42bool use_graph_optimize; 43 44int debug_graph; 45 46struct ggml_metal_fusion_info * finfo; 47 48// capture state 49int capture_compute; 50bool capture_started; 51 52id < MTLCaptureScope > capture_scope ; 53 54// command buffer state 55int n_cb; // number of extra threads used to submit the command buffers 56int n_nodes_0; // number of nodes submitted by the main thread 57int n_nodes_1; // remaining number of nodes submitted by the n_cb threads 58int n_nodes_per_cb; 59 60struct ggml_cgraph * gf; 61 62// the callback given to the thread pool 63void ( ^ encode_async )( size_t ith); 64 65// n_cb command buffers + 1 used by the main thread 66struct ggml_metal_command_buffer cmd_bufs[GGML_METAL_MAX_COMMAND_BUFFERS + 1]; 67 68// extra command buffers for things like getting, setting and copying tensors 69NSMutableArray * cmd_bufs_ext ; 70 71// buffers to release after async Metal operations complete 72// if Metal released them, it would do so on a Metal-internal thread without an autorelease pool, which could cause leaks 73NSMutableArray * buf_refs ; 74 75// the last command buffer queued into the Metal queue with operations relevant to the current Metal backend 76id < MTLCommandBuffer > cmd_buf_last ; 77 78// abort ggml_metal_graph_compute if callback returns true 79ggml_abort_callback abort_callback; 80void * abort_callback_data ; 81 82// error state - set when a command buffer fails during synchronize 83// once set, graph_compute will return GGML_STATUS_FAILED until the backend is recreated 84bool has_error; 85}; 86 87ggml_metal_t ggml_metal_init(ggml_metal_device_t dev) { 88GGML_LOG_INFO ( "%s: allocating\n" , __func__ ); 89 90@ autoreleasepool { 91# if TARGET_OS_OSX && ! GGML_METAL_NDEBUG 92// Show all the Metal device instances in the system 93NSArray * devices = MTLCopyAllDevices(); 94for ( id <MTLDevice> device in devices) { 95GGML_LOG_INFO ( "%s: found device: %s\n" , __func__ , [[ device name] UTF8String]); 96} 97[ devices release]; // since it was created by a *Copy* C method 98# endif 99 100// init context 101ggml_metal_t res = calloc(1, sizeof(struct ggml_metal)); 102 103id < MTLDevice > device = ggml_metal_device_get_obj( dev ); 104 105GGML_LOG_INFO ( "%s: picking default device: %s\n" , __func__ , [[ device name] UTF8String]); 106 107// TODO : would it be better to have one queue for the backend and one queue for the device? 108// the graph encoders and async ops would use the backend queue while the sync ops would use the device queue? 109// res - > queue = [ device newCommandQueue]; [ TAG_QUEUE_PER_BACKEND ] 110id < MTLCommandQueue > queue = ggml_metal_device_get_queue( dev ); 111if ( queue == nil ) { 112GGML_LOG_ERROR ( "%s: error: failed to create command queue\n" , __func__ ); 113free ( res ); 114return NULL; 115} 116 117res - > dev = dev; 118res - > lib = ggml_metal_device_get_library( dev ); 119if ( res - > lib == NULL ) { 120GGML_LOG_WARN ( "%s: the device does not have a precompiled Metal library - this is unexpected\n" , __func__ ); 121GGML_LOG_WARN ( "%s: will try to compile it on the fly\n" , __func__ ); 122 123res - > lib = ggml_metal_library_init( dev ); 124if ( res - > lib == NULL ) { 125GGML_LOG_ERROR ( "%s: error: failed to initialize the Metal library\n" , __func__ ); 126 127free ( res ); 128 129return NULL; 130} 131} 132 133res - > ev_cpy = ggml_metal_device_event_init( dev ); 134res - > ev_sync = ggml_metal_device_event_init( dev ); 135 136const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev); 137 138snprintf ( res - > name , sizeof ( res - > name ), "%s" , props_dev - > name ); 139 140res - > d_queue = dispatch_queue_create( "ggml-metal" , DISPATCH_QUEUE_CONCURRENT ); 141 142res - > use_concurrency = getenv( "GGML_METAL_CONCURRENCY_DISABLE" ) == nil ; 143 144{ 145const char * val = getenv( "GGML_METAL_GRAPH_DEBUG" ); 146res - > debug_graph = val ? atoi ( val ) : 0 ; 147} 148 149res - > use_graph_optimize = true; 150 151if ( getenv ( "GGML_METAL_GRAPH_OPTIMIZE_DISABLE" ) ! = NULL) { 152res - > use_graph_optimize = false; 153} 154 155res - > finfo = ggml_metal_device_get_fusion_info( dev ); 156if ( ggml_metal_fusion_info_stats ( res - > finfo )) { 157ggml_metal_fusion_info_labels_init ( res - > finfo ); 158res - > n_cb = 0; 159} 160 161GGML_LOG_INFO ( "%s: use fusion = %s\n" , __func__ , ggml_metal_fusion_info_enabled ( res - > finfo ) ? "true" : "false" ); 162GGML_LOG_INFO ( "%s: use concurrency = %s\n" , __func__ , res - > use_concurrency ? "true" : "false" ); 163GGML_LOG_INFO ( "%s: use graph optimize = %s\n" , __func__ , res - > use_graph_optimize ? "true" : "false" ); 164 165res - > capture_compute = 0; 166res - > capture_started = false; 167res - > capture_scope = nil; 168 169{ 170const char * val = getenv( "GGML_METAL_CAPTURE_COMPUTE" ); 171if ( val ) { 172res - > capture_compute = atoi( val ); 173} 174} 175 176res - > has_error = false; 177 178res - > gf = nil; 179res - > encode_async = nil; 180for ( int i = 0 ; i < GGML_METAL_MAX_COMMAND_BUFFERS ; ++ i ) { 181res - > cmd_bufs [ i ].obj = nil; 182} 183 184res - > cmd_bufs_ext = [[ NSMutableArray alloc] init]; 185res - > buf_refs = [[ NSMutableArray alloc] init]; 186 187res - > cmd_buf_last = nil; 188 189res - > pipelines_ext = ggml_metal_pipelines_init(); 190 191return res; 192} 193} 194 195v oid ggml_metal_free(ggml_metal_t ctx) { 196GGML_LOG_INFO ( "%s: deallocating\n" , __func__ ); 197 198for ( int i = 0 ; i < GGML_METAL_MAX_COMMAND_BUFFERS ; ++ i ) { 199if ( ctx - > cmd_bufs [ i ]. obj ) { 200[ ctx - > cmd_bufs [ i ].obj release]; 201} 202} 203 204for ( int i = 0 ; i < ( int ) ctx - > cmd_bufs_ext . count ; ++ i ) { 205if ( ctx - > cmd_bufs_ext [ i ]) { 206[ ctx - > cmd_bufs_ext [ i ] release]; 207} 208} 209 210[ ctx - > cmd_bufs_ext removeAllObjects]; 211[ ctx - > cmd_bufs_ext release]; 212 213@ autoreleasepool { 214[ ctx - > buf_refs removeAllObjects]; 215[ ctx - > buf_refs release]; 216} 217 218if ( ctx - > pipelines_ext ) { 219ggml_metal_pipelines_free ( ctx - > pipelines_ext ); 220ctx - > pipelines_ext = nil; 221} 222 223if ( ggml_metal_fusion_info_debug ( ctx - > finfo ) > 0 ) { 224GGML_LOG_DEBUG ( "%s: fusion stats:\n" , __func__ ); 225 226const int n_fusions = ggml_metal_fusion_info_n_fusions( ctx - > finfo ); 227for ( int i = 0; i < n_fusions ; i ++ ) { 228const uint64_t count = ggml_metal_fusion_info_count( ctx - > finfo , i ); 229if ( count == 0 ) { 230continue; 231} 232 233// note : cannot use ggml_log here 234GGML_LOG_DEBUG ( "%s: - %s: %" PRIu64 "\n", __func__ , ggml_metal_fusion_info_label ( ctx - > finfo , i ), count ); 235} 236} 237 238Block_release ( ctx - > encode_async ); 239 240// [ ctx - > queue release]; // [ TAG_QUEUE_PER_BACKEND ] 241 242dispatch_release ( ctx - > d_queue ); 243 244ggml_metal_device_event_free ( ctx - > dev , ctx - > ev_cpy ); 245ggml_metal_device_event_free ( ctx - > dev , ctx - > ev_sync ); 246 247free ( ctx ); 248} 249 250con st char * ggml_metal_get_name(ggml_metal_t ctx) { 251return ctx - >name; 252} 253 254v oid ggml_metal_synchronize(ggml_metal_t ctx) { 255// wait for any backend operations to finish 256if ( ctx - > cmd_buf_last ) { 257[ ctx - > cmd_buf_last waitUntilCompleted]; 258ctx - > cmd_buf_last = nil; 259} 260 261// check status of all command buffers 262{ 263const int n_cb = ctx - > n_cb ; 264 265for ( int cb_idx = 0; cb_idx <= n_cb ; ++ cb_idx ) { 266id < MTLCommandBuffer > cmd_buf = ctx - > cmd_bufs [ cb_idx ]. obj ; 267if (! cmd_buf ) { 268continue; 269} 270 271MTLCommandBufferStatus status = [ cmd_buf status]; 272if ( status ! = MTLCommandBufferStatusCompleted) { 273GGML_LOG_ERROR ( "%s: error: command buffer %d failed with status %d\n" , __func__ , cb_idx , ( int ) status); 274if ( status == MTLCommandBufferStatusError ) { 275GGML_LOG_ERROR ( "error: %s\n" , [[ cmd_buf error].localizedDescription UTF8String]); 276} 277ctx - > has_error = true; 278return; 279} 280} 281} 282 283// release any completed extra command buffers 284if ( ctx - > cmd_bufs_ext . count > 0 ) { 285for ( size_t i = 0 ; i < ctx - > cmd_bufs_ext . count ; ++ i ) { 286id < MTLCommandBuffer > cmd_buf = ctx - > cmd_bufs_ext [ i ]; 287 288MTLCommandBufferStatus status = [ cmd_buf status]; 289if ( status ! = MTLCommandBufferStatusCompleted) { 290GGML_LOG_ERROR ( "%s: error: command buffer %d failed with status %d\n" , __func__ , ( int ) i, ( int ) status); 291if ( status == MTLCommandBufferStatusError ) { 292GGML_LOG_ERROR ( "error: %s\n" , [[ cmd_buf error].localizedDescription UTF8String]); 293} 294 295// release this and all remaining command buffers before returning 296for ( size_t j = i; j < ctx - > cmd_bufs_ext . count ; ++ j ) { 297[ ctx - > cmd_bufs_ext [ j ] release]; 298} 299[ ctx - > cmd_bufs_ext removeAllObjects]; 300 301ctx - > has_error = true; 302return; 303} 304 305[ cmd_buf release]; 306} 307 308[ ctx - > cmd_bufs_ext removeAllObjects]; 309} 310 311@ autoreleasepool { 312[ ctx - > buf_refs removeAllObjects]; 313} 314} 315 316s tatic struct ggml_metal_buffer_id ggml_metal_get_buffer_id(const struct ggml_tensor * t) { 317if (! t ) { 318return ( struct ggml_metal_buffer_id) { nil , 0 }; 319} 320 321ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer; 322 323return ggml_metal_buffer_get_id( buffer - > context , t ); 324} 325 326v oid ggml_metal_set_tensor_async(ggml_metal_t ctx, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 327@ autoreleasepool { 328// wrap the source data into a Metal buffer 329id < MTLDevice > device = ggml_metal_device_get_obj( ctx - > dev ); 330id < MTLBuffer > buf_src = [ device newBufferWithBytes : data 331length : size 332options : MTLResourceStorageModeShared ]; 333 334GGML_ASSERT ( buf_src ); 335 336struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(tensor); 337if ( bid_dst . metal == nil ) { 338GGML_ABORT ( "%s: failed to find buffer for tensor '%s'\n" , __func__ , tensor - > name ); 339} 340 341bid_dst . offs += offset; 342 343// queue the copy operation into the queue of the Metal context 344// this will be queued at the end, after any currently ongoing GPU operations 345id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx - > dev ); 346id < MTLCommandBuffer > cmd_buf = [ queue commandBuffer]; 347id < MTLBlitCommandEncoder > encoder = [ cmd_buf blitCommandEncoder]; 348 349[ encoder copyFromBuffer : buf_src 350sourceOffset : 0 351toBuffer : bid_dst . metal 352destinationOffset : bid_dst . offs 353size : size ]; 354 355[ encoder endEncoding]; 356[ cmd_buf commit]; 357 358[ ctx - > buf_refs addObject : buf_src ]; 359[ buf_src release]; 360 361// do not wait here for completion 362// [ cmd_buf waitUntilCompleted]; 363 364// instead, remember a reference to the command buffer and wait for it later if needed 365[ ctx - > cmd_bufs_ext addObject : cmd_buf ]; 366ctx - > cmd_buf_last = cmd_buf; 367 368[ cmd_buf retain]; 369} 370} 371 372v oid ggml_metal_get_tensor_async(ggml_metal_t ctx, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { 373@ autoreleasepool { 374id < MTLDevice > device = ggml_metal_device_get_obj( ctx - > dev ); 375id < MTLBuffer > buf_dst = [ device newBufferWithBytesNoCopy : data 376length : size 377options : MTLResourceStorageModeShared 378deallocator : nil ]; 379 380GGML_ASSERT ( buf_dst ); 381 382struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id( tensor ); 383if ( bid_src . metal == nil ) { 384GGML_ABORT ( "%s: failed to find buffer for tensor '%s'\n" , __func__ , tensor - > name ); 385} 386 387bid_src . offs += offset; 388 389// queue the copy operation into the queue of the Metal context 390// this will be queued at the end, after any currently ongoing GPU operations 391id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx - > dev ); 392id < MTLCommandBuffer > cmd_buf = [ queue commandBuffer]; 393id < MTLBlitCommandEncoder > encoder = [ cmd_buf blitCommandEncoder]; 394 395[ encoder copyFromBuffer : bid_src . metal 396sourceOffset : bid_src . offs 397toBuffer : buf_dst 398destinationOffset : 0 399size : size ]; 400 401[ encoder endEncoding]; 402[ cmd_buf commit]; 403 404[ ctx - > buf_refs addObject : buf_dst ]; 405[ buf_dst release]; 406 407// do not wait here for completion 408// [ cmd_buf waitUntilCompleted]; 409 410// instead, remember a reference to the command buffer and wait for it later if needed 411[ ctx - > cmd_bufs_ext addObject : cmd_buf ]; 412ctx - > cmd_buf_last = cmd_buf; 413 414[ cmd_buf retain]; 415} 416} 417 418b ool ggml_metal_cpy_tensor_async(ggml_metal_t ctx_src, ggml_metal_t ctx_dst, const struct ggml_tensor * src, struct ggml_tensor * dst) { 419@ autoreleasepool { 420struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id( src ); 421struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id( dst ); 422 423if ( bid_src . metal == nil || bid_dst . metal == nil ) { 424return false; 425} 426 427id < MTLCommandQueue > dst_queue = ggml_metal_device_get_queue( ctx_dst - > dev ); 428id < MTLCommandBuffer > sync_cmd_buf = [ dst_queue commandBuffer]; 429 430ggml_metal_event_encode_signal ( ctx_dst - > ev_sync , sync_cmd_buf ); 431 432[ sync_cmd_buf commit]; 433 434[ ctx_dst - > cmd_bufs_ext addObject : sync_cmd_buf ]; 435ctx_dst - > cmd_buf_last = sync_cmd_buf; 436 437[ sync_cmd_buf retain]; 438 439// queue the copy operation into the Metal context 440// this will be queued at the end, after any currently ongoing GPU operations 441id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx_src - > dev ); 442id < MTLCommandBuffer > cmd_buf = [ queue commandBuffer]; 443ggml_metal_event_encode_wait ( ctx_dst - > ev_sync , cmd_buf ); 444id < MTLBlitCommandEncoder > encoder = [ cmd_buf blitCommandEncoder]; 445 446[ encoder copyFromBuffer : bid_src . metal 447sourceOffset : bid_src . offs 448toBuffer : bid_dst . metal 449destinationOffset : bid_dst . offs 450size : ggml_nbytes ( src )]; 451 452[ encoder endEncoding]; 453 454ggml_metal_event_t ev_cpy = ggml_metal_get_ev_cpy( ctx_src ); 455ggml_metal_event_encode_signal ( ev_cpy , cmd_buf ); 456 457[ cmd_buf commit]; 458 459// do not wait here for completion 460// [ cmd_buf waitUntilCompleted]; 461 462// instead, remember a reference to the command buffer and wait for it later if needed 463[ ctx_src - > cmd_bufs_ext addObject : cmd_buf ]; 464ctx_src - > cmd_buf_last = cmd_buf; 465 466[ cmd_buf retain]; 467 468ggml_metal_event_wait ( ctx_dst , ev_cpy ); 469 470return true; 471} 472} 473 474enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * gf) { 475if ( ctx - > has_error ) { 476GGML_LOG_ERROR ( "%s: backend is in error state from a previous command buffer failure - recreate the backend to recover\n" , __func__ ); 477return GGML_STATUS_FAILED; 478} 479 480// number of nodes encoded by the main thread (empirically determined) 481const int n_main = MAX(64, 0.1*gf->n_nodes); 482 483// number of threads in addition to the main thread 484const int n_cb = ctx->n_cb; 485 486// keep the memory wired 487ggml_metal_device_rsets_keep_alive ( ctx - > dev ); 488 489// submit the ggml compute graph to the GPU by creating command buffers and encoding the ops in them 490// the first n_nodes_0 are encoded and submitted for processing directly by the calling thread 491// while these nodes are processing, we start n_cb threads to enqueue the rest of the nodes 492// each thread creates it's own command buffer and enqueues the ops in parallel 493// 494// tests on M1 Pro and M2 Ultra using LLaMA models, show that optimal values for n_cb are 1 or 2 495 496@ autoreleasepool { 497ctx - > gf = gf; 498 499if ( ctx - > n_cb == 0 ) { 500// single - threaded encoding : the whole graph is encoded by one command buffer 501ctx - > n_nodes_0 = gf - > n_nodes ; 502ctx - > n_nodes_1 = 0; 503ctx - > n_nodes_per_cb = 0; 504} else { 505ctx - > n_nodes_0 = MIN( n_main , gf - > n_nodes ); 506ctx - > n_nodes_1 = gf - > n_nodes - ctx - > n_nodes_0 ; 507 508ctx - > n_nodes_per_cb = ( ctx - > n_nodes_1 + ctx - > n_cb - 1 ) / ctx - > n_cb ; 509} 510 511if ( ctx - > capture_compute >= 0 ) { 512ctx - > capture_compute -- ; 513} 514 515const bool use_capture = ctx - > capture_compute == 0 ; 516if ( use_capture ) { 517ctx - > capture_compute = - 1 ; 518 519// make sure all previous computations have finished before starting the capture 520if ( ctx - > cmd_buf_last ) { 521[ ctx - > cmd_buf_last waitUntilCompleted]; 522ctx - > cmd_buf_last = nil; 523} 524 525if (! ctx - > capture_started ) { 526NSString * path = [ NSString stringWithFormat :@ "/tmp/perf-metal-%d.gputrace" , getpid ()]; 527 528GGML_LOG_WARN ( "%s: capturing graph in %s\n" , __func__ , [ path UTF8String]); 529 530// create capture scope 531id < MTLDevice > device = ggml_metal_device_get_obj( ctx - > dev ); 532ctx - > capture_scope = [[ MTLCaptureManager sharedCaptureManager] newCaptureScopeWithDevice : device ]; 533 534MTLCaptureDescriptor * descriptor = [ MTLCaptureDescriptor new]; 535descriptor . captureObject = ctx - > capture_scope ; 536descriptor . destination = MTLCaptureDestinationGPUTraceDocument; 537descriptor . outputURL = [ NSURL fileURLWithPath : path ]; 538 539NSError * error = nil; 540if (![[ MTLCaptureManager sharedCaptureManager] startCaptureWithDescriptor : descriptor error : & error ]) { 541GGML_LOG_ERROR ( "%s: error: unable to start capture '%s'\n" , __func__ , [[ error localizedDescription] UTF8String]); 542} else { 543[ ctx - > capture_scope beginScope]; 544ctx - > capture_started = true; 545} 546} 547} 548 549// short - hand 550id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx - > dev ); 551 552// the main thread commits the first few commands immediately 553// cmd_buf[ n_cb ] 554{ 555id < MTLCommandBuffer > cmd_buf = [ queue commandBufferWithUnretainedReferences]; 556[ cmd_buf retain]; 557 558if ( ctx - > cmd_bufs [ n_cb ]. obj ) { 559[ ctx - > cmd_bufs [ n_cb ].obj release]; 560} 561ctx - > cmd_bufs [ n_cb ].obj = cmd_buf; 562 563[ cmd_buf enqueue]; 564 565ctx - > encode_async ( n_cb ); 566} 567 568// remember the command buffer for the next iteration 569ctx - > cmd_buf_last = ctx - > cmd_bufs [ n_cb ]. obj ; 570 571// prepare the rest of the command buffers asynchronously ( optional ) 572// cmd_buf[ 0. . n_cb) 573for ( int cb_idx = 0; cb_idx < n_cb ; ++ cb_idx ) { 574id < MTLCommandBuffer > cmd_buf = [ queue commandBufferWithUnretainedReferences]; 575[ cmd_buf retain]; 576 577if ( ctx - > cmd_bufs [ cb_idx ]. obj ) { 578[ ctx - > cmd_bufs [ cb_idx ].obj release]; 579} 580ctx - > cmd_bufs [ cb_idx ].obj = cmd_buf; 581 582// always enqueue the first two command buffers 583// enqueue all of the command buffers if we don ' t need to abort 584if ( cb_idx < 2 || ctx - > abort_callback == NULL ) { 585[ cmd_buf enqueue]; 586 587// update the pointer to the last queued command buffer 588// this is needed to implement synchronize() 589ctx - > cmd_buf_last = cmd_buf; 590} 591} 592 593dispatch_apply ( n_cb , ctx - > d_queue , ctx - > encode_async ); 594 595// for debugging : block until graph is computed 596// [ ctx - > cmd_buf_last waitUntilCompleted]; 597 598// enter here only when capturing in order to wait for all computation to finish 599// otherwise, we leave the graph to compute asynchronously 600if ( use_capture && ctx - > capture_started ) { 601// wait for completion and check status of each command buffer 602// needed to detect if the device ran out - of - memory for example (# 1881 ) 603{ 604id < MTLCommandBuffer > cmd_buf = ctx - > cmd_bufs [ n_cb ]. obj ; 605[ cmd_buf waitUntilCompleted]; 606 607MTLCommandBufferStatus status = [ cmd_buf status]; 608if ( status ! = MTLCommandBufferStatusCompleted) { 609GGML_LOG_INFO ( "%s: command buffer %d failed with status %lu\n" , __func__ , n_cb , status ); 610if ( status == MTLCommandBufferStatusError ) { 611GGML_LOG_INFO ( "error: %s\n" , [[ cmd_buf error].localizedDescription UTF8String]); 612} 613 614return GGML_STATUS_FAILED; 615} 616} 617 618for ( int i = 0; i < n_cb ; ++ i ) { 619id < MTLCommandBuffer > cmd_buf = ctx - > cmd_bufs [ i ]. obj ; 620[ cmd_buf waitUntilCompleted]; 621 622MTLCommandBufferStatus status = [ cmd_buf status]; 623if ( status ! = MTLCommandBufferStatusCompleted) { 624GGML_LOG_INFO ( "%s: command buffer %d failed with status %lu\n" , __func__ , i , status ); 625if ( status == MTLCommandBufferStatusError ) { 626GGML_LOG_INFO ( "error: %s\n" , [[ cmd_buf error].localizedDescription UTF8String]); 627} 628 629return GGML_STATUS_FAILED; 630} 631 632id < MTLCommandBuffer > next_buffer = ( i + 1 < n_cb ? ctx - > cmd_bufs [ i + 1 ].obj : nil ); 633if (! next_buffer ) { 634continue; 635} 636 637const bool next_queued = ([ next_buffer status] ! = MTLCommandBufferStatusNotEnqueued); 638if ( next_queued ) { 639continue; 640} 641 642if ( ctx - > abort_callback && ctx - > abort_callback ( ctx - > abort_callback_data )) { 643GGML_LOG_INFO ( "%s: command buffer %d aborted" , __func__ , i ); 644return GGML_STATUS_ABORTED; 645} 646 647[ next_buffer commit]; 648} 649 650[ ctx - > capture_scope endScope]; 651[[ MTLCaptureManager sharedCaptureManager] stopCapture]; 652 653ctx - > capture_started = false; 654} 655} 656 657return GGML_STATUS_SUCCESS; 658} 659 660v oid ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf) { 661// const int64_t t_start = ggml_time_us(); 662 663if ( ctx - > use_graph_optimize ) { 664ggml_graph_optimize ( gf ); 665} 666 667// printf ( "%s: graph optimize took %.3f ms\n" , __func__ , ( ggml_time_us () - t_start ) / 1000.0 ); 668} 669 670v oid ggml_metal_event_record(ggml_metal_t ctx, ggml_metal_event_t ev) { 671@ autoreleasepool { 672id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx - > dev ); 673id < MTLCommandBuffer > cmd_buf = [ queue commandBuffer]; 674 675ggml_metal_event_encode_signal ( ev , cmd_buf ); 676 677[ cmd_buf commit]; 678 679[ ctx - > cmd_bufs_ext addObject : cmd_buf ]; 680ctx - > cmd_buf_last = cmd_buf; 681 682[ cmd_buf retain]; 683} 684} 685 686v oid ggml_metal_event_wait(ggml_metal_t ctx, ggml_metal_event_t ev) { 687@ autoreleasepool { 688id < MTLCommandQueue > queue = ggml_metal_device_get_queue( ctx - > dev ); 689id < MTLCommandBuffer > cmd_buf = [ queue commandBuffer]; 690 691ggml_metal_event_encode_wait ( ev , cmd_buf ); 692 693[ cmd_buf commit]; 694 695[ ctx - > cmd_bufs_ext addObject : cmd_buf ]; 696ctx - > cmd_buf_last = cmd_buf; 697 698[ cmd_buf retain]; 699} 700} 701 702g gml_metal_event_t ggml_metal_get_ev_cpy(ggml_metal_t ctx) { 703return ctx - >ev_cpy; 704} 705 706v oid ggml_metal_set_n_cb(ggml_metal_t ctx, int n_cb) { 707// when fusion stats are collected the graph must be encoded by a single thread so the 708// counters are race-free; override whatever the caller requested 709if ( ggml_metal_fusion_info_stats ( ctx - > finfo )) { 710n_cb = 0; 711} 712 713if ( ctx - > n_cb ! = n_cb) { 714ctx - > n_cb = MIN( n_cb , GGML_METAL_MAX_COMMAND_BUFFERS ); 715 716if ( ctx - > n_cb > 2 ) { 717GGML_LOG_WARN ( "%s: n_cb = %d, using n_cb > 2 is not recommended and can degrade the performance in some cases\n" , __func__ , n_cb ); 718} 719} 720 721if ( ctx - > encode_async ) { 722Block_release ( ctx - > encode_async ); 723} 724 725ctx - > encode_async = Block_copy( ^ ( size_t iter) { 726const int cb_idx = iter; 727const int n_cb_l = ctx - > n_cb ; 728 729const int n_nodes_0 = ctx - > n_nodes_0 ; 730const int n_nodes_1 = ctx - > n_nodes_1 ; 731 732const int n_nodes_per_cb = ctx - > n_nodes_per_cb ; 733 734int idx_start = 0; 735int idx_end = n_nodes_0; 736 737if ( cb_idx < n_cb_l ) { 738idx_start = n_nodes_0 + ( ( cb_idx + 0 ) * n_nodes_per_cb ); 739idx_end = n_nodes_0 + ( MIN (( cb_idx == n_cb_l - 1 ) ? n_nodes_1 : ( cb_idx + 1 ) * n_nodes_per_cb , n_nodes_1 )); 740} 741 742id < MTLCommandBuffer > cmd_buf = ctx - > cmd_bufs [ cb_idx ]. obj ; 743 744ggml_metal_op_t ctx_op = ggml_metal_op_init( 745c tx - > dev , 746c md_buf , 747c tx - > gf , 748c tx - > finfo , 749i dx_start , 750i dx_end , 751c tx - > use_concurrency , 752c tx - > capture_compute , 753c tx - > debug_graph ); 754 755for ( int idx = 0; idx < ggml_metal_op_n_nodes ( ctx_op ); ++ idx ) { 756const int res = ggml_metal_op_encode( ctx_op , idx ); 757if ( res == 0 ) { 758break; 759} 760 761idx += res - 1 ; 762} 763 764ggml_metal_op_free ( ctx_op ); 765 766if ( cb_idx < 2 || ctx - > abort_callback == NULL ) { 767[ cmd_buf commit]; 768} 769}); 770} 771 772v oid ggml_metal_set_abort_callback(ggml_metal_t ctx, ggml_abort_callback abort_callback, void * user_data) { 773ctx - > abort_callback = abort_callback; 774ctx - > abort_callback_data = user_data; 775} 776 777b ool ggml_metal_supports_family(ggml_metal_t ctx, int family) { 778GGML_ASSERT ( ctx - > dev ! = nil ); 779 780id < MTLDevice > device = ggml_metal_device_get_obj( ctx - > dev ); 781 782return [ device supportsFamily : ( MTLGPUFamilyApple1 + family - 1 )]; 783} 784 785v oid ggml_metal_capture_next_compute(ggml_metal_t ctx) { 786ctx - > capture_compute = 1; 787}