ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / src / ggml-metal / ggml-metal-context.m
| 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 | |
| 23 | struct ggml_metal_command_buffer { |
| 24 | id<MTLCommandBuffer> obj; |
| 25 | }; |
| 26 | |
| 27 | struct 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 | |
| 87 | ggml_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 | |
| 195 | void 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 | |
| 250 | const char * ggml_metal_get_name(ggml_metal_t ctx) { |
| 251 | return ctx->name; |
| 252 | } |
| 253 | |
| 254 | void 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 | |
| 316 | static 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 | |
| 326 | void 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 | |
| 372 | void 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 | |
| 418 | bool 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 | |
| 474 | enum 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 | if (gf->n_nodes == 0) { |
| 481 | return GGML_STATUS_SUCCESS; |
| 482 | } |
| 483 | |
| 484 | // number of nodes encoded by the main thread (empirically determined) |
| 485 | const int n_main = MAX(64, 0.1*gf->n_nodes); |
| 486 | |
| 487 | // number of threads in addition to the main thread |
| 488 | const int n_cb = ctx->n_cb; |
| 489 | |
| 490 | // keep the memory wired |
| 491 | ggml_metal_device_rsets_keep_alive(ctx->dev); |
| 492 | |
| 493 | // submit the ggml compute graph to the GPU by creating command buffers and encoding the ops in them |
| 494 | // the first n_nodes_0 are encoded and submitted for processing directly by the calling thread |
| 495 | // while these nodes are processing, we start n_cb threads to enqueue the rest of the nodes |
| 496 | // each thread creates it's own command buffer and enqueues the ops in parallel |
| 497 | // |
| 498 | // tests on M1 Pro and M2 Ultra using LLaMA models, show that optimal values for n_cb are 1 or 2 |
| 499 | |
| 500 | @autoreleasepool { |
| 501 | ctx->gf = gf; |
| 502 | |
| 503 | if (ctx->n_cb == 0) { |
| 504 | // single-threaded encoding: the whole graph is encoded by one command buffer |
| 505 | ctx->n_nodes_0 = gf->n_nodes; |
| 506 | ctx->n_nodes_1 = 0; |
| 507 | ctx->n_nodes_per_cb = 0; |
| 508 | } else { |
| 509 | ctx->n_nodes_0 = MIN(n_main, gf->n_nodes); |
| 510 | ctx->n_nodes_1 = gf->n_nodes - ctx->n_nodes_0; |
| 511 | |
| 512 | ctx->n_nodes_per_cb = (ctx->n_nodes_1 + ctx->n_cb - 1) / ctx->n_cb; |
| 513 | } |
| 514 | |
| 515 | if (ctx->capture_compute >= 0) { |
| 516 | ctx->capture_compute--; |
| 517 | } |
| 518 | |
| 519 | const bool use_capture = ctx->capture_compute == 0; |
| 520 | if (use_capture) { |
| 521 | // make sure all previous computations have finished before starting the capture |
| 522 | if (ctx->cmd_buf_last) { |
| 523 | [ctx->cmd_buf_last waitUntilCompleted]; |
| 524 | ctx->cmd_buf_last = nil; |
| 525 | } |
| 526 | |
| 527 | if (!ctx->capture_started) { |
| 528 | NSString * path = [NSString stringWithFormat:@"/tmp/perf-metal-%d.gputrace", getpid()]; |
| 529 | |
| 530 | GGML_LOG_WARN("%s: capturing graph in %s\n", __func__, [path UTF8String]); |
| 531 | |
| 532 | // create capture scope |
| 533 | id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev); |
| 534 | ctx->capture_scope = [[MTLCaptureManager sharedCaptureManager] newCaptureScopeWithDevice:device]; |
| 535 | |
| 536 | MTLCaptureDescriptor * descriptor = [MTLCaptureDescriptor new]; |
| 537 | descriptor.captureObject = ctx->capture_scope; |
| 538 | descriptor.destination = MTLCaptureDestinationGPUTraceDocument; |
| 539 | descriptor.outputURL = [NSURL fileURLWithPath:path]; |
| 540 | |
| 541 | NSError * error = nil; |
| 542 | const bool ok = [[MTLCaptureManager sharedCaptureManager] startCaptureWithDescriptor:descriptor error:&error]; |
| 543 | |
| 544 | [descriptor release]; |
| 545 | |
| 546 | if (!ok) { |
| 547 | GGML_LOG_ERROR("%s: error: unable to start capture '%s' (did you set METAL_CAPTURE_ENABLED=1 ?)\n", __func__, [[error localizedDescription] UTF8String]); |
| 548 | [ctx->capture_scope release]; |
| 549 | ctx->capture_scope = nil; |
| 550 | } else { |
| 551 | [ctx->capture_scope beginScope]; |
| 552 | ctx->capture_started = true; |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | // short-hand |
| 558 | id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev); |
| 559 | |
| 560 | // the main thread commits the first few commands immediately |
| 561 | // cmd_buf[n_cb] |
| 562 | { |
| 563 | id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences]; |
| 564 | [cmd_buf retain]; |
| 565 | |
| 566 | if (ctx->cmd_bufs[n_cb].obj) { |
| 567 | [ctx->cmd_bufs[n_cb].obj release]; |
| 568 | } |
| 569 | ctx->cmd_bufs[n_cb].obj = cmd_buf; |
| 570 | |
| 571 | [cmd_buf enqueue]; |
| 572 | |
| 573 | ctx->encode_async(n_cb); |
| 574 | } |
| 575 | |
| 576 | // remember the command buffer for the next iteration |
| 577 | ctx->cmd_buf_last = ctx->cmd_bufs[n_cb].obj; |
| 578 | |
| 579 | // prepare the rest of the command buffers asynchronously (optional) |
| 580 | // cmd_buf[0.. n_cb) |
| 581 | for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) { |
| 582 | id<MTLCommandBuffer> cmd_buf = [queue commandBufferWithUnretainedReferences]; |
| 583 | [cmd_buf retain]; |
| 584 | |
| 585 | if (ctx->cmd_bufs[cb_idx].obj) { |
| 586 | [ctx->cmd_bufs[cb_idx].obj release]; |
| 587 | } |
| 588 | ctx->cmd_bufs[cb_idx].obj = cmd_buf; |
| 589 | |
| 590 | // always enqueue the first two command buffers |
| 591 | // enqueue all of the command buffers if we don't need to abort |
| 592 | if (cb_idx < 2 || ctx->abort_callback == NULL) { |
| 593 | [cmd_buf enqueue]; |
| 594 | |
| 595 | // update the pointer to the last queued command buffer |
| 596 | // this is needed to implement synchronize() |
| 597 | ctx->cmd_buf_last = cmd_buf; |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | dispatch_apply(n_cb, ctx->d_queue, ctx->encode_async); |
| 602 | |
| 603 | // for debugging: block until graph is computed |
| 604 | //[ctx->cmd_buf_last waitUntilCompleted]; |
| 605 | |
| 606 | // enter here only when capturing in order to wait for all computation to finish |
| 607 | // otherwise, we leave the graph to compute asynchronously |
| 608 | if (use_capture && ctx->capture_started) { |
| 609 | enum ggml_status res = GGML_STATUS_SUCCESS; |
| 610 | |
| 611 | // wait for completion and check status of each command buffer |
| 612 | // needed to detect if the device ran out-of-memory for example (#1881) |
| 613 | { |
| 614 | id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[n_cb].obj; |
| 615 | [cmd_buf waitUntilCompleted]; |
| 616 | |
| 617 | MTLCommandBufferStatus status = [cmd_buf status]; |
| 618 | if (status != MTLCommandBufferStatusCompleted) { |
| 619 | GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, n_cb, status); |
| 620 | if (status == MTLCommandBufferStatusError) { |
| 621 | GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]); |
| 622 | } |
| 623 | |
| 624 | res = GGML_STATUS_FAILED; |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | for (int i = 0; i < n_cb && res == GGML_STATUS_SUCCESS; ++i) { |
| 629 | id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[i].obj; |
| 630 | [cmd_buf waitUntilCompleted]; |
| 631 | |
| 632 | MTLCommandBufferStatus status = [cmd_buf status]; |
| 633 | if (status != MTLCommandBufferStatusCompleted) { |
| 634 | GGML_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status); |
| 635 | if (status == MTLCommandBufferStatusError) { |
| 636 | GGML_LOG_INFO("error: %s\n", [[cmd_buf error].localizedDescription UTF8String]); |
| 637 | } |
| 638 | res = GGML_STATUS_FAILED; |
| 639 | break; |
| 640 | } |
| 641 | |
| 642 | id<MTLCommandBuffer> next_buffer = (i + 1 < n_cb ? ctx->cmd_bufs[i + 1].obj : nil); |
| 643 | if (!next_buffer) { |
| 644 | continue; |
| 645 | } |
| 646 | |
| 647 | const bool next_queued = ([next_buffer status] != MTLCommandBufferStatusNotEnqueued); |
| 648 | if (next_queued) { |
| 649 | continue; |
| 650 | } |
| 651 | |
| 652 | if (ctx->abort_callback && ctx->abort_callback(ctx->abort_callback_data)) { |
| 653 | GGML_LOG_INFO("%s: command buffer %d aborted", __func__, i); |
| 654 | res = GGML_STATUS_ABORTED; |
| 655 | break; |
| 656 | } |
| 657 | |
| 658 | [next_buffer commit]; |
| 659 | } |
| 660 | |
| 661 | [ctx->capture_scope endScope]; |
| 662 | [[MTLCaptureManager sharedCaptureManager] stopCapture]; |
| 663 | |
| 664 | [ctx->capture_scope release]; |
| 665 | ctx->capture_scope = nil; |
| 666 | |
| 667 | ctx->capture_started = false; |
| 668 | |
| 669 | if (res != GGML_STATUS_SUCCESS) { |
| 670 | return res; |
| 671 | } |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | return GGML_STATUS_SUCCESS; |
| 676 | } |
| 677 | |
| 678 | void ggml_metal_graph_optimize(ggml_metal_t ctx, struct ggml_cgraph * gf) { |
| 679 | //const int64_t t_start = ggml_time_us(); |
| 680 | |
| 681 | if (ctx->use_graph_optimize) { |
| 682 | ggml_graph_optimize(gf); |
| 683 | } |
| 684 | |
| 685 | //printf("%s: graph optimize took %.3f ms\n", __func__, (ggml_time_us() - t_start) / 1000.0); |
| 686 | } |
| 687 | |
| 688 | void ggml_metal_event_record(ggml_metal_t ctx, ggml_metal_event_t ev) { |
| 689 | @autoreleasepool { |
| 690 | id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev); |
| 691 | id<MTLCommandBuffer> cmd_buf = [queue commandBuffer]; |
| 692 | |
| 693 | ggml_metal_event_encode_signal(ev, cmd_buf); |
| 694 | |
| 695 | [cmd_buf commit]; |
| 696 | |
| 697 | [ctx->cmd_bufs_ext addObject:cmd_buf]; |
| 698 | ctx->cmd_buf_last = cmd_buf; |
| 699 | |
| 700 | [cmd_buf retain]; |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | void ggml_metal_event_wait(ggml_metal_t ctx, ggml_metal_event_t ev) { |
| 705 | @autoreleasepool { |
| 706 | id<MTLCommandQueue> queue = ggml_metal_device_get_queue(ctx->dev); |
| 707 | id<MTLCommandBuffer> cmd_buf = [queue commandBuffer]; |
| 708 | |
| 709 | ggml_metal_event_encode_wait(ev, cmd_buf); |
| 710 | |
| 711 | [cmd_buf commit]; |
| 712 | |
| 713 | [ctx->cmd_bufs_ext addObject:cmd_buf]; |
| 714 | ctx->cmd_buf_last = cmd_buf; |
| 715 | |
| 716 | [cmd_buf retain]; |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | ggml_metal_event_t ggml_metal_get_ev_cpy(ggml_metal_t ctx) { |
| 721 | return ctx->ev_cpy; |
| 722 | } |
| 723 | |
| 724 | void ggml_metal_set_n_cb(ggml_metal_t ctx, int n_cb) { |
| 725 | // when fusion stats are collected the graph must be encoded by a single thread so the |
| 726 | // counters are race-free; override whatever the caller requested |
| 727 | if (ggml_metal_fusion_info_stats(ctx->finfo)) { |
| 728 | n_cb = 0; |
| 729 | } |
| 730 | |
| 731 | if (ctx->n_cb != n_cb) { |
| 732 | ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_COMMAND_BUFFERS); |
| 733 | |
| 734 | if (ctx->n_cb > 2) { |
| 735 | 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); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | if (ctx->encode_async) { |
| 740 | Block_release(ctx->encode_async); |
| 741 | } |
| 742 | |
| 743 | ctx->encode_async = Block_copy(^(size_t iter) { |
| 744 | const int cb_idx = iter; |
| 745 | const int n_cb_l = ctx->n_cb; |
| 746 | |
| 747 | const int n_nodes_0 = ctx->n_nodes_0; |
| 748 | const int n_nodes_1 = ctx->n_nodes_1; |
| 749 | |
| 750 | const int n_nodes_per_cb = ctx->n_nodes_per_cb; |
| 751 | |
| 752 | int idx_start = 0; |
| 753 | int idx_end = n_nodes_0; |
| 754 | |
| 755 | if (cb_idx < n_cb_l) { |
| 756 | idx_start = n_nodes_0 + ( (cb_idx + 0) * n_nodes_per_cb); |
| 757 | 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)); |
| 758 | } |
| 759 | |
| 760 | id<MTLCommandBuffer> cmd_buf = ctx->cmd_bufs[cb_idx].obj; |
| 761 | |
| 762 | ggml_metal_op_t ctx_op = ggml_metal_op_init( |
| 763 | ctx->dev, |
| 764 | cmd_buf, |
| 765 | ctx->gf, |
| 766 | ctx->finfo, |
| 767 | idx_start, |
| 768 | idx_end, |
| 769 | ctx->use_concurrency, |
| 770 | ctx->capture_compute == 0, |
| 771 | ctx->debug_graph); |
| 772 | |
| 773 | for (int idx = 0; idx < ggml_metal_op_n_nodes(ctx_op); ++idx) { |
| 774 | const int res = ggml_metal_op_encode(ctx_op, idx); |
| 775 | if (res == 0) { |
| 776 | break; |
| 777 | } |
| 778 | |
| 779 | idx += res - 1; |
| 780 | } |
| 781 | |
| 782 | ggml_metal_op_free(ctx_op); |
| 783 | |
| 784 | if (cb_idx < 2 || ctx->abort_callback == NULL) { |
| 785 | [cmd_buf commit]; |
| 786 | } |
| 787 | }); |
| 788 | } |
| 789 | |
| 790 | void ggml_metal_set_abort_callback(ggml_metal_t ctx, ggml_abort_callback abort_callback, void * user_data) { |
| 791 | ctx->abort_callback = abort_callback; |
| 792 | ctx->abort_callback_data = user_data; |
| 793 | } |
| 794 | |
| 795 | bool ggml_metal_supports_family(ggml_metal_t ctx, int family) { |
| 796 | GGML_ASSERT(ctx->dev != nil); |
| 797 | |
| 798 | id<MTLDevice> device = ggml_metal_device_get_obj(ctx->dev); |
| 799 | |
| 800 | return [device supportsFamily:(MTLGPUFamilyApple1 + family - 1)]; |
| 801 | } |
| 802 | |
| 803 | void ggml_metal_capture_next_compute(ggml_metal_t ctx) { |
| 804 | ctx->capture_compute = 1; |
| 805 | } |