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
26.9 KiB787 linesraw
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 {
24    id<MTLCommandBuffer> obj;
25};
26
27struct ggml_metal {
28    char name[128];
29
30    ggml_metal_device_t  dev;
31    ggml_metal_library_t lib;
32
33    ggml_metal_event_t ev_cpy;  // for async copies
34    ggml_metal_event_t ev_sync; // destination completion signal
35
36    dispatch_queue_t d_queue;
37
38    // additional, inference-time compiled pipelines
39    ggml_metal_pipelines_t pipelines_ext;
40
41    bool use_concurrency;
42    bool use_graph_optimize;
43
44    int debug_graph;
45
46    struct ggml_metal_fusion_info * finfo;
47
48    // capture state
49    int capture_compute;
50    bool capture_started;
51
52    id<MTLCaptureScope> capture_scope;
53
54    // command buffer state
55    int n_cb;           // number of extra threads used to submit the command buffers
56    int n_nodes_0;      // number of nodes submitted by the main thread
57    int n_nodes_1;      // remaining number of nodes submitted by the n_cb threads
58    int n_nodes_per_cb;
59
60    struct ggml_cgraph * gf;
61
62    // the callback given to the thread pool
63    void (^encode_async)(size_t ith);
64
65    // n_cb command buffers + 1 used by the main thread
66    struct 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
69    NSMutableArray * 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
73    NSMutableArray * buf_refs;
74
75    // the last command buffer queued into the Metal queue with operations relevant to the current Metal backend
76    id<MTLCommandBuffer> cmd_buf_last;
77
78    // abort ggml_metal_graph_compute if callback returns true
79    ggml_abort_callback abort_callback;
80    void *              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
84    bool has_error;
85};
86
87ggml_metal_t ggml_metal_init(ggml_metal_device_t dev) {
88    GGML_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
93        NSArray * devices = MTLCopyAllDevices();
94        for (id<MTLDevice> device in devices) {
95            GGML_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
101        ggml_metal_t res = calloc(1, sizeof(struct ggml_metal));
102
103        id<MTLDevice> device = ggml_metal_device_get_obj(dev);
104
105        GGML_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]
110        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(dev);
111        if (queue == nil) {
112            GGML_LOG_ERROR("%s: error: failed to create command queue\n", __func__);
113            free(res);
114            return NULL;
115        }
116
117        res->dev = dev;
118        res->lib = ggml_metal_device_get_library(dev);
119        if (res->lib == NULL) {
120            GGML_LOG_WARN("%s: the device does not have a precompiled Metal library - this is unexpected\n", __func__);
121            GGML_LOG_WARN("%s: will try to compile it on the fly\n", __func__);
122
123            res->lib = ggml_metal_library_init(dev);
124            if (res->lib == NULL) {
125                GGML_LOG_ERROR("%s: error: failed to initialize the Metal library\n", __func__);
126
127                free(res);
128
129                return NULL;
130            }
131        }
132
133        res->ev_cpy  = ggml_metal_device_event_init(dev);
134        res->ev_sync = ggml_metal_device_event_init(dev);
135
136        const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev);
137
138        snprintf(res->name, sizeof(res->name), "%s", props_dev->name);
139
140        res->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
141
142        res->use_concurrency = getenv("GGML_METAL_CONCURRENCY_DISABLE") == nil;
143
144        {
145            const char * val = getenv("GGML_METAL_GRAPH_DEBUG");
146            res->debug_graph = val ? atoi(val) : 0;
147        }
148
149        res->use_graph_optimize = true;
150
151        if (getenv("GGML_METAL_GRAPH_OPTIMIZE_DISABLE") != NULL) {
152            res->use_graph_optimize = false;
153        }
154
155        res->finfo = ggml_metal_device_get_fusion_info(dev);
156        if (ggml_metal_fusion_info_stats(res->finfo)) {
157            ggml_metal_fusion_info_labels_init(res->finfo);
158            res->n_cb = 0;
159        }
160
161        GGML_LOG_INFO("%s: use fusion         = %s\n", __func__, ggml_metal_fusion_info_enabled(res->finfo) ? "true" : "false");
162        GGML_LOG_INFO("%s: use concurrency    = %s\n", __func__, res->use_concurrency    ? "true" : "false");
163        GGML_LOG_INFO("%s: use graph optimize = %s\n", __func__, res->use_graph_optimize ? "true" : "false");
164
165        res->capture_compute = 0;
166        res->capture_started = false;
167        res->capture_scope = nil;
168
169        {
170            const char * val = getenv("GGML_METAL_CAPTURE_COMPUTE");
171            if (val) {
172                res->capture_compute = atoi(val);
173            }
174        }
175
176        res->has_error = false;
177
178        res->gf = nil;
179        res->encode_async = nil;
180        for (int i = 0; i < GGML_METAL_MAX_COMMAND_BUFFERS; ++i) {
181            res->cmd_bufs[i].obj = nil;
182        }
183
184        res->cmd_bufs_ext = [[NSMutableArray alloc] init];
185        res->buf_refs     = [[NSMutableArray alloc] init];
186
187        res->cmd_buf_last = nil;
188
189        res->pipelines_ext = ggml_metal_pipelines_init();
190
191        return res;
192    }
193}
194
195void ggml_metal_free(ggml_metal_t ctx) {
196    GGML_LOG_INFO("%s: deallocating\n", __func__);
197
198    for (int i = 0; i < GGML_METAL_MAX_COMMAND_BUFFERS; ++i) {
199        if (ctx->cmd_bufs[i].obj) {
200            [ctx->cmd_bufs[i].obj release];
201        }
202    }
203
204    for (int i = 0; i < (int) ctx->cmd_bufs_ext.count; ++i) {
205        if (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
218    if (ctx->pipelines_ext) {
219        ggml_metal_pipelines_free(ctx->pipelines_ext);
220        ctx->pipelines_ext = nil;
221    }
222
223    if (ggml_metal_fusion_info_debug(ctx->finfo) > 0) {
224        GGML_LOG_DEBUG("%s: fusion stats:\n", __func__);
225
226        const int n_fusions = ggml_metal_fusion_info_n_fusions(ctx->finfo);
227        for (int i = 0; i < n_fusions; i++) {
228            const uint64_t count = ggml_metal_fusion_info_count(ctx->finfo, i);
229            if (count == 0) {
230                continue;
231            }
232
233            // note: cannot use ggml_log here
234            GGML_LOG_DEBUG("%s: - %s: %" PRIu64 "\n", __func__, ggml_metal_fusion_info_label(ctx->finfo, i), count);
235        }
236    }
237
238    Block_release(ctx->encode_async);
239
240    //[ctx->queue release]; // [TAG_QUEUE_PER_BACKEND]
241
242    dispatch_release(ctx->d_queue);
243
244    ggml_metal_device_event_free(ctx->dev, ctx->ev_cpy);
245    ggml_metal_device_event_free(ctx->dev, ctx->ev_sync);
246
247    free(ctx);
248}
249
250const char * ggml_metal_get_name(ggml_metal_t ctx) {
251    return ctx->name;
252}
253
254void ggml_metal_synchronize(ggml_metal_t ctx) {
255    // wait for any backend operations to finish
256    if (ctx->cmd_buf_last) {
257        [ctx->cmd_buf_last waitUntilCompleted];
258        ctx->cmd_buf_last = nil;
259    }
260
261    // check status of all command buffers
262    {
263        const int n_cb = ctx->n_cb;
264
265        for (int cb_idx = 0; cb_idx <= n_cb; ++cb_idx) {
266            id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[cb_idx].obj;
267            if (!cmd_buf) {
268                continue;
269            }
270
271            MTLCommandBufferStatus status = [cmd_buf status];
272            if (status != MTLCommandBufferStatusCompleted) {
273                GGML_LOG_ERROR("%s: error: command buffer %d failed with status %d\n", __func__, cb_idx, (int) status);
274                if (status == MTLCommandBufferStatusError) {
275                    GGML_LOG_ERROR("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
276                }
277                ctx->has_error = true;
278                return;
279            }
280        }
281    }
282
283    // release any completed extra command buffers
284    if (ctx->cmd_bufs_ext.count > 0) {
285        for (size_t i = 0; i < ctx->cmd_bufs_ext.count; ++i) {
286            id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs_ext[i];
287
288            MTLCommandBufferStatus status = [cmd_buf status];
289            if (status != MTLCommandBufferStatusCompleted) {
290                GGML_LOG_ERROR("%s: error: command buffer %d failed with status %d\n", __func__, (int) i, (int) status);
291                if (status == MTLCommandBufferStatusError) {
292                    GGML_LOG_ERROR("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
293                }
294
295                // release this and all remaining command buffers before returning
296                for (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
301                ctx->has_error = true;
302                return;
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
316static struct ggml_metal_buffer_id ggml_metal_get_buffer_id(const struct ggml_tensor * t) {
317    if (!t) {
318        return (struct ggml_metal_buffer_id) { nil, 0 };
319    }
320
321    ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
322
323    return ggml_metal_buffer_get_id(buffer->context, t);
324}
325
326void 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
329        id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
330        id<MTLBuffer> buf_src = [device newBufferWithBytes:data
331                                                    length:size
332                                                   options:MTLResourceStorageModeShared];
333
334        GGML_ASSERT(buf_src);
335
336        struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(tensor);
337        if (bid_dst.metal == nil) {
338            GGML_ABORT("%s: failed to find buffer for tensor '%s'\n", __func__, tensor->name);
339        }
340
341        bid_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
345        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
346        id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
347        id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
348
349        [encoder copyFromBuffer:buf_src
350                   sourceOffset:0
351                       toBuffer:bid_dst.metal
352              destinationOffset:bid_dst.offs
353                           size: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];
366        ctx->cmd_buf_last = cmd_buf;
367
368        [cmd_buf retain];
369    }
370}
371
372void ggml_metal_get_tensor_async(ggml_metal_t ctx, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
373    @autoreleasepool {
374        id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
375        id<MTLBuffer> buf_dst = [device newBufferWithBytesNoCopy:data
376                                                          length:size
377                                                         options:MTLResourceStorageModeShared
378                                                     deallocator:nil];
379
380        GGML_ASSERT(buf_dst);
381
382        struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id(tensor);
383        if (bid_src.metal == nil) {
384            GGML_ABORT("%s: failed to find buffer for tensor '%s'\n", __func__, tensor->name);
385        }
386
387        bid_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
391        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
392        id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
393        id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
394
395        [encoder copyFromBuffer:bid_src.metal
396                   sourceOffset:bid_src.offs
397                       toBuffer:buf_dst
398              destinationOffset:0
399                           size: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];
412        ctx->cmd_buf_last = cmd_buf;
413
414        [cmd_buf retain];
415    }
416}
417
418bool 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 {
420        struct ggml_metal_buffer_id bid_src = ggml_metal_get_buffer_id(src);
421        struct ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(dst);
422
423        if (bid_src.metal == nil || bid_dst.metal == nil) {
424            return false;
425        }
426
427        id<MTLCommandQueue> dst_queue = ggml_metal_device_get_queue(ctx_dst->dev);
428        id<MTLCommandBuffer> sync_cmd_buf = [dst_queue commandBuffer];
429
430        ggml_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];
435        ctx_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
441        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx_src->dev);
442        id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
443        ggml_metal_event_encode_wait(ctx_dst->ev_sync, cmd_buf);
444        id<MTLBlitCommandEncoder> encoder = [cmd_buf blitCommandEncoder];
445
446        [encoder copyFromBuffer:bid_src.metal
447                   sourceOffset:bid_src.offs
448                       toBuffer:bid_dst.metal
449              destinationOffset:bid_dst.offs
450                           size:ggml_nbytes(src)];
451
452        [encoder endEncoding];
453
454        ggml_metal_event_t ev_cpy = ggml_metal_get_ev_cpy(ctx_src);
455        ggml_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];
464        ctx_src->cmd_buf_last = cmd_buf;
465
466        [cmd_buf retain];
467
468        ggml_metal_event_wait(ctx_dst, ev_cpy);
469
470        return true;
471    }
472}
473
474enum ggml_status ggml_metal_graph_compute(ggml_metal_t ctx, struct ggml_cgraph * gf) {
475    if (ctx->has_error) {
476        GGML_LOG_ERROR("%s: backend is in error state from a previous command buffer failure - recreate the backend to recover\n", __func__);
477        return GGML_STATUS_FAILED;
478    }
479
480    // number of nodes encoded by the main thread (empirically determined)
481    const int n_main = MAX(64, 0.1*gf->n_nodes);
482
483    // number of threads in addition to the main thread
484    const int n_cb = ctx->n_cb;
485
486    // keep the memory wired
487    ggml_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 {
497        ctx->gf = gf;
498
499        if (ctx->n_cb == 0) {
500            // single-threaded encoding: the whole graph is encoded by one command buffer
501            ctx->n_nodes_0      = gf->n_nodes;
502            ctx->n_nodes_1      = 0;
503            ctx->n_nodes_per_cb = 0;
504        } else {
505            ctx->n_nodes_0      = MIN(n_main, gf->n_nodes);
506            ctx->n_nodes_1      = gf->n_nodes - ctx->n_nodes_0;
507
508            ctx->n_nodes_per_cb = (ctx->n_nodes_1 + ctx->n_cb - 1) / ctx->n_cb;
509        }
510
511        if (ctx->capture_compute >= 0) {
512            ctx->capture_compute--;
513        }
514
515        const bool use_capture = ctx->capture_compute == 0;
516        if (use_capture) {
517            ctx->capture_compute = -1;
518
519            // make sure all previous computations have finished before starting the capture
520            if (ctx->cmd_buf_last) {
521                [ctx->cmd_buf_last waitUntilCompleted];
522                ctx->cmd_buf_last = nil;
523            }
524
525            if (!ctx->capture_started) {
526                NSString * path = [NSString stringWithFormat:@"/tmp/perf-metal-%d.gputrace", getpid()];
527
528                GGML_LOG_WARN("%s: capturing graph in %s\n", __func__, [path UTF8String]);
529
530                // create capture scope
531                id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
532                ctx->capture_scope = [[MTLCaptureManager sharedCaptureManager] newCaptureScopeWithDevice:device];
533
534                MTLCaptureDescriptor * descriptor = [MTLCaptureDescriptor new];
535                descriptor.captureObject = ctx->capture_scope;
536                descriptor.destination = MTLCaptureDestinationGPUTraceDocument;
537                descriptor.outputURL = [NSURL fileURLWithPath:path];
538
539                NSError * error = nil;
540                if (![[MTLCaptureManager sharedCaptureManager] startCaptureWithDescriptor:descriptor error:&error]) {
541                    GGML_LOG_ERROR("%s: error: unable to start capture '%s'\n", __func__, [[error localizedDescription] UTF8String]);
542                } else {
543                    [ctx->capture_scope beginScope];
544                    ctx->capture_started = true;
545                }
546            }
547        }
548
549        // short-hand
550        id<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        {
555            id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences];
556            [cmd_buf retain];
557
558            if (ctx->cmd_bufs[n_cb].obj) {
559                [ctx->cmd_bufs[n_cb].obj release];
560            }
561            ctx->cmd_bufs[n_cb].obj = cmd_buf;
562
563            [cmd_buf enqueue];
564
565            ctx->encode_async(n_cb);
566        }
567
568        // remember the command buffer for the next iteration
569        ctx->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)
573        for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
574            id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences];
575            [cmd_buf retain];
576
577            if (ctx->cmd_bufs[cb_idx].obj) {
578                [ctx->cmd_bufs[cb_idx].obj release];
579            }
580            ctx->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
584            if (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()
589                ctx->cmd_buf_last = cmd_buf;
590            }
591        }
592
593        dispatch_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
600        if (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            {
604                id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[n_cb].obj;
605                [cmd_buf waitUntilCompleted];
606
607                MTLCommandBufferStatus status = [cmd_buf status];
608                if (status != MTLCommandBufferStatusCompleted) {
609                    GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, n_cb, status);
610                    if (status == MTLCommandBufferStatusError) {
611                        GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
612                    }
613
614                    return GGML_STATUS_FAILED;
615                }
616            }
617
618            for (int i = 0; i < n_cb; ++i) {
619                id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[i].obj;
620                [cmd_buf waitUntilCompleted];
621
622                MTLCommandBufferStatus status = [cmd_buf status];
623                if (status != MTLCommandBufferStatusCompleted) {
624                    GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
625                    if (status == MTLCommandBufferStatusError) {
626                        GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]);
627                    }
628
629                    return GGML_STATUS_FAILED;
630                }
631
632                id<MTLCommandBuffer> next_buffer = (i + 1 < n_cb ? ctx->cmd_bufs[i + 1].obj : nil);
633                if (!next_buffer) {
634                    continue;
635                }
636
637                const bool next_queued = ([next_buffer status] != MTLCommandBufferStatusNotEnqueued);
638                if (next_queued) {
639                    continue;
640                }
641
642                if (ctx->abort_callback && ctx->abort_callback(ctx->abort_callback_data)) {
643                    GGML_LOG_INFO("%s: command buffer %d aborted", __func__, i);
644                    return GGML_STATUS_ABORTED;
645                }
646
647                [next_buffer commit];
648            }
649
650            [ctx->capture_scope endScope];
651            [[MTLCaptureManager sharedCaptureManager] stopCapture];
652
653            ctx->capture_started = false;
654        }
655    }
656
657    return GGML_STATUS_SUCCESS;
658}
659
660void ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf) {
661    //const int64_t t_start = ggml_time_us();
662
663    if (ctx->use_graph_optimize) {
664        ggml_graph_optimize(gf);
665    }
666
667    //printf("%s: graph optimize took %.3f ms\n", __func__, (ggml_time_us() - t_start) / 1000.0);
668}
669
670void ggml_metal_event_record(ggml_metal_t ctx, ggml_metal_event_t ev) {
671    @autoreleasepool {
672        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
673        id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
674
675        ggml_metal_event_encode_signal(ev, cmd_buf);
676
677        [cmd_buf commit];
678
679        [ctx->cmd_bufs_ext addObject:cmd_buf];
680        ctx->cmd_buf_last = cmd_buf;
681
682        [cmd_buf retain];
683    }
684}
685
686void ggml_metal_event_wait(ggml_metal_t ctx, ggml_metal_event_t ev) {
687    @autoreleasepool {
688        id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev);
689        id<MTLCommandBuffer> cmd_buf = [queue commandBuffer];
690
691        ggml_metal_event_encode_wait(ev, cmd_buf);
692
693        [cmd_buf commit];
694
695        [ctx->cmd_bufs_ext addObject:cmd_buf];
696        ctx->cmd_buf_last = cmd_buf;
697
698        [cmd_buf retain];
699    }
700}
701
702ggml_metal_event_t ggml_metal_get_ev_cpy(ggml_metal_t ctx) {
703    return ctx->ev_cpy;
704}
705
706void 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
709    if (ggml_metal_fusion_info_stats(ctx->finfo)) {
710        n_cb = 0;
711    }
712
713    if (ctx->n_cb != n_cb) {
714        ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_COMMAND_BUFFERS);
715
716        if (ctx->n_cb > 2) {
717            GGML_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
721    if (ctx->encode_async) {
722        Block_release(ctx->encode_async);
723    }
724
725    ctx->encode_async = Block_copy(^(size_t iter) {
726        const int cb_idx = iter;
727        const int n_cb_l = ctx->n_cb;
728
729        const int n_nodes_0 = ctx->n_nodes_0;
730        const int n_nodes_1 = ctx->n_nodes_1;
731
732        const int n_nodes_per_cb = ctx->n_nodes_per_cb;
733
734        int idx_start = 0;
735        int idx_end   = n_nodes_0;
736
737        if (cb_idx < n_cb_l) {
738            idx_start = n_nodes_0 + (                                         (cb_idx + 0) * n_nodes_per_cb);
739            idx_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
742        id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[cb_idx].obj;
743
744        ggml_metal_op_t ctx_op = ggml_metal_op_init(
745            ctx->dev,
746            cmd_buf,
747            ctx->gf,
748            ctx->finfo,
749            idx_start,
750            idx_end,
751            ctx->use_concurrency,
752            ctx->capture_compute,
753            ctx->debug_graph);
754
755        for (int idx = 0; idx < ggml_metal_op_n_nodes(ctx_op); ++idx) {
756            const int res = ggml_metal_op_encode(ctx_op, idx);
757            if (res == 0) {
758                break;
759            }
760
761            idx += res - 1;
762        }
763
764        ggml_metal_op_free(ctx_op);
765
766        if (cb_idx < 2 || ctx->abort_callback == NULL) {
767            [cmd_buf commit];
768        }
769    });
770}
771
772void ggml_metal_set_abort_callback(ggml_metal_t ctx, ggml_abort_callback abort_callback, void * user_data) {
773    ctx->abort_callback = abort_callback;
774    ctx->abort_callback_data = user_data;
775}
776
777bool ggml_metal_supports_family(ggml_metal_t ctx, int family) {
778    GGML_ASSERT(ctx->dev != nil);
779
780    id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev);
781
782    return [device supportsFamily:(MTLGPUFamilyApple1 + family - 1)];
783}
784
785void ggml_metal_capture_next_compute(ggml_metal_t ctx) {
786    ctx->capture_compute = 1;
787}