Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-metal/ggml-metal-device.m # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-metal / ggml-metal-device.m` 2760 lines ยท 103283 bytes Raw Blame History 1 #import "ggml-metal-device.h" 2 #import "ggml-metal-fusion.h" 3 4 #import "ggml-impl.h" 5 #import "ggml-backend-impl.h" 6 #import "ggml-metal-impl.h" 7 #import "ggml-metal-common.h" 8 9 #include 10 11 #include 12 13 #include 14 15 #ifndef TARGET_OS_VISION 16 #define TARGET_OS_VISION 0 17 #endif 18 19 // create residency sets only on macOS >= 15.0 20 #if !TARGET_CPU_X86_64 && TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED >= 150000 || \ 21 TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED >= 180000 || \ 22 TARGET_OS_TV && __TV_OS_VERSION_MAX_ALLOWED >= 180000 || \ 23 TARGET_OS_VISION && __VISION_OS_VERSION_MAX_ALLOWED >= 200000 24 #define GGML_METAL_HAS_RESIDENCY_SETS 1 25 #endif 26 27 // overload of MTLGPUFamilyMetalX (not available in some environments) 28 static const NSInteger MTLGPUFamilyMetal3_GGML = 5001; 29 static const NSInteger MTLGPUFamilyMetal4_GGML = 5002; 30 31 // MTLLanguageVersion4_0 is not present in older SDKs 32 static const NSUInteger MTLLanguageVersion4_0_GGML = 4 << 16; 33 34 #if !GGML_METAL_EMBED_LIBRARY 35 // Here to assist with NSBundle Path Hack 36 @interface GGMLMetalClass : NSObject 37 @end 38 @implementation GGMLMetalClass 39 @end 40 #endif 41 42 // 43 // MTLFunctionConstantValues wrapper 44 // 45 46 struct ggml_metal_cv { 47 MTLFunctionConstantValues * obj; 48 }; 49 50 ggml_metal_cv_t ggml_metal_cv_init(void) { 51 ggml_metal_cv_t res = calloc(1, sizeof(struct ggml_metal_cv)); 52 53 res->obj = [[MTLFunctionConstantValues alloc] init]; 54 55 return res; 56 } 57 58 void ggml_metal_cv_free(ggml_metal_cv_t cv) { 59 [cv->obj release]; 60 free(cv); 61 } 62 63 void ggml_metal_cv_set_int16(ggml_metal_cv_t cv, int16_t value, int32_t idx) { 64 [cv->obj setConstantValue:&value type:MTLDataTypeShort atIndex:idx]; 65 } 66 67 void ggml_metal_cv_set_int32(ggml_metal_cv_t cv, int32_t value, int32_t idx) { 68 [cv->obj setConstantValue:&value type:MTLDataTypeInt atIndex:idx]; 69 } 70 71 void ggml_metal_cv_set_bool(ggml_metal_cv_t cv, bool value, int32_t idx) { 72 [cv->obj setConstantValue:&value type:MTLDataTypeBool atIndex:idx]; 73 } 74 75 // 76 // MTLComputePipelineState wrapper 77 // 78 79 struct ggml_metal_pipeline { 80 id obj; 81 }; 82 83 ggml_metal_pipeline_t ggml_metal_pipeline_init(void) { 84 ggml_metal_pipeline_t res = calloc(1, sizeof(struct ggml_metal_pipeline)); 85 86 *res = (struct ggml_metal_pipeline) { 87 /*.obj =*/ nil, 88 }; 89 90 return res; 91 } 92 93 void ggml_metal_pipeline_free(ggml_metal_pipeline_t pipeline) { 94 [pipeline->obj release]; 95 96 free(pipeline); 97 } 98 99 int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_with_params pipeline) { 100 return pipeline.pipeline->obj.maxTotalThreadsPerThreadgroup; 101 } 102 103 // 104 // MTLLibrary collection (one library per op-source, compiled separately) 105 // 106 107 // Single source of truth for the per-kind metal libraries. The order here 108 // defines the enum values and every per-kind table below, so adding a library 109 // is a one-line change here (plus adding its source to CMakeLists.txt). 110 // X(suffix, name): name is both the kernels/.metal basename and the 111 // ggml_metallib__{start,end} embed-symbol stem. 112 #define GGML_METAL_LIBS \ 113 X(FA_AUX, fa_aux) \ 114 X(FA_F16, fa_f16) \ 115 X(FA_F32, fa_f32) \ 116 X(FA_Q4_0, fa_q4_0) \ 117 X(FA_Q4_1, fa_q4_1) \ 118 X(FA_Q5_0, fa_q5_0) \ 119 X(FA_Q5_1, fa_q5_1) \ 120 X(FA_Q8_0, fa_q8_0) \ 121 X(FA_TENSOR, fa_tensor) \ 122 X(FA_VEC_F16, fa_vec_f16) \ 123 X(FA_VEC_F32, fa_vec_f32) \ 124 X(FA_VEC_Q4_0, fa_vec_q4_0) \ 125 X(FA_VEC_Q4_1, fa_vec_q4_1) \ 126 X(FA_VEC_Q5_0, fa_vec_q5_0) \ 127 X(FA_VEC_Q5_1, fa_vec_q5_1) \ 128 X(FA_VEC_Q8_0, fa_vec_q8_0) \ 129 X(MUL_MV, mul_mv) \ 130 X(MUL_MV_MMA, mul_mv_mma) \ 131 X(MUL_MM, mul_mm) \ 132 X(QUANTIZE, quantize) \ 133 X(SOFTMAX, softmax) \ 134 X(NORM, norm) \ 135 X(UNARY, unary) \ 136 X(BINBCAST, binbcast) \ 137 X(REDUCE, reduce) \ 138 X(TRI, tri) \ 139 X(SSM, ssm) \ 140 X(WKV, wkv) \ 141 X(GATED_DELTA_NET, gated_delta_net)\ 142 X(SOLVE_TRI, solve_tri) \ 143 X(ROPE, rope) \ 144 X(CONV, conv) \ 145 X(UPSCALE, upscale) \ 146 X(ARGSORT, argsort) \ 147 X(POOL, pool) \ 148 X(MISC, misc) 149 150 enum ggml_metal_lib_kind { 151 #define X(e, s) GGML_METAL_LIB_##e, 152 GGML_METAL_LIBS 153 #undef X 154 GGML_METAL_LIB_COUNT, 155 }; 156 157 static const char * const k_lib_names[GGML_METAL_LIB_COUNT] = { 158 #define X(e, s) [GGML_METAL_LIB_##e] = #s, 159 GGML_METAL_LIBS 160 #undef X 161 }; 162 163 struct ggml_metal_library { 164 // Per-kind compiled libraries. When single_library is true, the whole library 165 // (e.g. a pre-compiled default.metallib or a from-source build) lives at 166 // objs[0] and the remaining slots are nil. 167 id objs[GGML_METAL_LIB_COUNT]; 168 bool single_library; // true: combined library at objs[0]; false: per-kind libs in objs[*] 169 170 // Routing table: kernel function name -> objs[] index, populated from each 171 // compiled library's -[MTLLibrary functionNames]. The actual compiled 172 // libraries are the single source of truth for which library owns a kernel, 173 // so adding kernels later requires no manual routing maintenance. 174 // nil in single_library mode (everything resolves to objs[0]). 175 NSMutableDictionary * fn_to_lib; 176 177 // kernels from a second metallib, resolved ahead of the combined library 178 NSSet * override_fns; 179 180 ggml_metal_device_t dev; 181 ggml_metal_pipelines_t pipelines; // cache of compiled pipelines 182 183 NSLock * lock; 184 }; 185 186 // Build the fn_to_lib routing table by querying each compiled library's public 187 // function names. Call once after all per-kind libraries have been compiled. 188 static void ggml_metal_library_build_index(ggml_metal_library_t lib) { 189 @autoreleasepool { 190 NSMutableDictionary * index = [[NSMutableDictionary alloc] init]; 191 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 192 for (NSString * fname in [lib->objs[kind] functionNames]) { 193 index[fname] = @(kind); 194 } 195 } 196 lib->fn_to_lib = index; 197 } 198 } 199 200 // note: defined below, after struct ggml_metal_device 201 static void ggml_metal_device_disable_tensor(ggml_metal_device_t dev); 202 203 // the tensor API headers are exposed to the shader compiler only at Metal language version 4.0 204 static void ggml_metal_compile_options_set_lang(MTLCompileOptions * options, bool has_tensor) { 205 if (!has_tensor) { 206 return; 207 } 208 209 options.languageVersion = (MTLLanguageVersion) MTLLanguageVersion4_0_GGML; 210 } 211 212 // Parse a `#include "name"` line. Returns the quoted name in *include_name on 213 // success. Whitespace-tolerant; ignores `#include <...>` (system headers). 214 static bool ggml_metal_library_parse_quoted_include(NSString * line, NSString ** include_name) { 215 NSScanner * scanner = [NSScanner scannerWithString:line]; 216 scanner.charactersToBeSkipped = [NSCharacterSet whitespaceCharacterSet]; 217 218 if (![scanner scanString:@"#" intoString:NULL] || 219 ![scanner scanString:@"include" intoString:NULL] || 220 ![scanner scanString:@"\"" intoString:NULL]) { 221 return false; 222 } 223 224 NSString * name = nil; 225 if (![scanner scanUpToString:@"\"" intoString:&name]) { 226 return false; 227 } 228 229 if (include_name) { 230 *include_name = name; 231 } 232 return true; 233 } 234 235 // Recursively inline `#include "name"` directives. System includes (<...>), 236 // `#if/#else/#endif`, and other preprocessor lines are passed through to the 237 // Metal compiler unchanged. `#pragma once` is dropped since `seen` already 238 // guards against double-inclusion. 239 static bool ggml_metal_library_flatten_file(NSMutableString * dst, NSString * path, 240 NSArray * search_paths, 241 NSMutableSet * seen, NSError ** error) { 242 NSString * key = [path stringByStandardizingPath]; 243 if ([seen containsObject:key]) { 244 return true; 245 } 246 [seen addObject:key]; 247 248 NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:error]; 249 if (!src) { 250 return false; 251 } 252 253 NSFileManager * fm = [NSFileManager defaultManager]; 254 for (NSString * line in [src componentsSeparatedByString:@"\n"]) { 255 NSString * trimmed = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 256 if ([trimmed isEqualToString:@"#pragma once"]) { 257 continue; 258 } 259 260 NSString * include_name = nil; 261 if (ggml_metal_library_parse_quoted_include(line, &include_name)) { 262 NSString * resolved = nil; 263 for (NSString * dir in search_paths) { 264 NSString * candidate = [dir stringByAppendingPathComponent:include_name]; 265 if ([fm isReadableFileAtPath:candidate]) { 266 resolved = candidate; 267 break; 268 } 269 } 270 if (!resolved) { 271 if (error) { 272 NSString * msg = [NSString stringWithFormat:@"could not resolve include \"%@\" from '%@'", include_name, path]; 273 *error = [NSError errorWithDomain:@"ggml-metal-source-flatten" code:1 274 userInfo:@{NSLocalizedDescriptionKey: msg}]; 275 } 276 return false; 277 } 278 if (!ggml_metal_library_flatten_file(dst, resolved, search_paths, seen, error)) { 279 return false; 280 } 281 continue; 282 } 283 284 [dst appendString:line]; 285 [dst appendString:@"\n"]; 286 } 287 288 return true; 289 } 290 291 static NSString * ggml_metal_library_flatten_source(NSString * path_source, NSError ** error) { 292 // Search paths cover both runtime layout (build/bin/kernels + build/bin) 293 // and source-tree layout (ggml/src/ggml-metal/kernels + ggml/src/ggml-metal + ggml/src). 294 NSString * path_kernels = [path_source stringByDeletingLastPathComponent]; 295 NSString * path_base = [path_kernels stringByDeletingLastPathComponent]; 296 NSArray * search_paths = @[ 297 path_kernels, 298 path_base, 299 [path_base stringByDeletingLastPathComponent], 300 ]; 301 302 NSMutableString * src = [[NSMutableString alloc] init]; 303 NSMutableSet * seen = [NSMutableSet set]; 304 305 if (!ggml_metal_library_flatten_file(src, path_source, search_paths, seen, error)) { 306 [src release]; 307 return nil; 308 } 309 return src; 310 } 311 312 // Compile all per-kind libraries in parallel. `source_for_kind` returns the MSL 313 // source for a kind (the helper takes ownership and releases it), or nil with 314 // *err set on failure. On success the objs[] slots are populated and the routing 315 // index is built; on any failure every error is logged and false is returned 316 // (the caller is responsible for freeing `res`). 317 static bool ggml_metal_library_compile_all( 318 ggml_metal_library_t res, 319 id device, 320 NSDictionary * prep, 321 NSString * (^source_for_kind)(int kind, NSError ** err), 322 const char * origin) { 323 const int64_t t_start = ggml_time_us(); 324 325 int64_t * t_per_lib = calloc(GGML_METAL_LIB_COUNT, sizeof(int64_t)); 326 NSError ** err_per_lib = calloc(GGML_METAL_LIB_COUNT, sizeof(NSError *)); 327 __block atomic_bool any_failure = false; 328 329 dispatch_group_t group = dispatch_group_create(); 330 dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0); 331 332 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 333 dispatch_group_async(group, queue, ^{ 334 335 const int64_t t0 = ggml_time_us(); 336 337 NSError * error = nil; 338 339 NSString * src = source_for_kind(kind, &error); 340 if (!src) { 341 err_per_lib[kind] = [error retain]; 342 atomic_store(&any_failure, true); 343 return; 344 } 345 346 id lib = nil; 347 348 @autoreleasepool { 349 MTLCompileOptions * options = [MTLCompileOptions new]; 350 options.preprocessorMacros = prep; 351 ggml_metal_compile_options_set_lang(options, ggml_metal_device_get_props(res->dev)->has_tensor); 352 353 lib = [device newLibraryWithSource:src options:options error:&error]; 354 355 [options release]; 356 357 // retain the error before the autorelease pool drains it 358 if (!lib) { 359 err_per_lib[kind] = [error retain]; 360 } 361 } 362 363 [src release]; 364 365 t_per_lib[kind] = ggml_time_us() - t0; 366 367 if (!lib) { 368 atomic_store(&any_failure, true); 369 return; 370 } 371 372 res->objs[kind] = lib; 373 }); 374 } 375 dispatch_group_wait(group, DISPATCH_TIME_FOREVER); 376 dispatch_release(group); 377 378 const bool ok = !atomic_load(&any_failure); 379 380 if (ok) { 381 const int64_t t_total = ggml_time_us() - t_start; 382 int64_t t_max = 0; 383 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 384 GGML_LOG_DEBUG("%s: compiled '%s' library in %.3f sec\n", 385 __func__, k_lib_names[kind], t_per_lib[kind] / 1e6); 386 if (t_per_lib[kind] > t_max) t_max = t_per_lib[kind]; 387 } 388 GGML_LOG_INFO("%s: loaded %d libraries from %s in %.3f sec (max single = %.3f sec)\n", 389 __func__, GGML_METAL_LIB_COUNT, origin, t_total / 1e6, t_max / 1e6); 390 391 ggml_metal_library_build_index(res); 392 } else { 393 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 394 if (err_per_lib[kind]) { 395 GGML_LOG_ERROR("%s: failed to build '%s' library: %s\n", __func__, 396 k_lib_names[kind], [[err_per_lib[kind] description] UTF8String]); 397 [err_per_lib[kind] release]; 398 } 399 } 400 } 401 402 free(err_per_lib); 403 free(t_per_lib); 404 405 return ok; 406 } 407 408 // look for .metallib as a bundle resource, then next to the running binary 409 static NSString * ggml_metal_find_metallib(NSBundle * bundle, NSString * name) { 410 NSError * error = nil; 411 412 NSString * path_lib = [bundle pathForResource:name ofType:@"metallib"]; 413 if (path_lib == nil) { 414 // Try to find the resource in the directory where the current binary located. 415 NSString * bin_cur = [[NSProcessInfo processInfo] arguments][0]; 416 NSString * bin_dir = [bin_cur stringByDeletingLastPathComponent]; 417 418 NSString * path_lib_default = [NSString pathWithComponents:@[bin_dir, [name stringByAppendingPathExtension:@"metallib"]]]; 419 if ([[NSFileManager defaultManager] isReadableFileAtPath:path_lib_default]) { 420 GGML_LOG_INFO("%s: found '%s'\n", __func__, [path_lib_default UTF8String]); 421 422 NSDictionary * atts = [[NSFileManager defaultManager] attributesOfItemAtPath:path_lib_default error:&error]; 423 if (atts && atts[NSFileType] == NSFileTypeSymbolicLink) { 424 // Optionally, if this is a symlink, try to resolve it. 425 path_lib_default = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath:path_lib_default error:&error]; 426 if (path_lib_default && [path_lib_default length] > 0 && ![[path_lib_default substringToIndex:1] isEqualToString:@"/"]) { 427 // It is a relative path, adding the binary directory as directory prefix. 428 path_lib_default = [NSString pathWithComponents:@[bin_dir, path_lib_default]]; 429 } 430 if (!path_lib_default || ![[NSFileManager defaultManager] isReadableFileAtPath:path_lib_default]) { 431 // Link to the resource could not be resolved. 432 path_lib_default = nil; 433 } else { 434 GGML_LOG_INFO("%s: symlink resolved '%s'\n", __func__, [path_lib_default UTF8String]); 435 } 436 } 437 } else { 438 // The resource couldn't be found in the binary's directory. 439 path_lib_default = nil; 440 } 441 442 path_lib = path_lib_default; 443 } 444 445 return path_lib; 446 } 447 448 ggml_metal_library_t ggml_metal_library_init(ggml_metal_device_t dev) { 449 id device = ggml_metal_device_get_obj(dev); 450 451 ggml_metal_library_t res = calloc(1, sizeof(struct ggml_metal_library)); 452 res->dev = dev; 453 res->pipelines = ggml_metal_pipelines_init(); 454 res->lock = [NSLock new]; 455 456 // shared MTLCompileOptions preprocessor macros (matches the build-time defines) 457 NSMutableDictionary * prep = [NSMutableDictionary dictionary]; 458 if (ggml_metal_device_get_props(dev)->has_bfloat) { 459 [prep setObject:@"1" forKey:@"GGML_METAL_HAS_BF16"]; 460 } 461 if (ggml_metal_device_get_props(dev)->has_tensor) { 462 [prep setObject:@"1" forKey:@"GGML_METAL_HAS_TENSOR"]; 463 } 464 #if GGML_METAL_EMBED_LIBRARY 465 [prep setObject:@"1" forKey:@"GGML_METAL_EMBED_LIBRARY"]; 466 #endif 467 468 #if GGML_METAL_EMBED_LIBRARY 469 GGML_LOG_INFO("%s: using embedded metal library\n", __func__); 470 471 // start/end symbols emitted by CMake (see CMakeLists.txt), one pair per kind 472 #define X(e, s) extern const char ggml_metallib_##s##_start[]; extern const char ggml_metallib_##s##_end[]; 473 GGML_METAL_LIBS 474 #undef X 475 476 static const char * const lib_start[GGML_METAL_LIB_COUNT] = { 477 #define X(e, s) [GGML_METAL_LIB_##e] = ggml_metallib_##s##_start, 478 GGML_METAL_LIBS 479 #undef X 480 }; 481 static const char * const lib_end[GGML_METAL_LIB_COUNT] = { 482 #define X(e, s) [GGML_METAL_LIB_##e] = ggml_metallib_##s##_end, 483 GGML_METAL_LIBS 484 #undef X 485 }; 486 487 const bool ok = ggml_metal_library_compile_all(res, device, prep, 488 ^NSString * (int kind, NSError ** err) { 489 (void) err; 490 return [[NSString alloc] initWithBytes:lib_start[kind] 491 length:(lib_end[kind] - lib_start[kind]) 492 encoding:NSUTF8StringEncoding]; 493 }, "embedded data"); 494 495 if (!ok) { 496 ggml_metal_library_free(res); 497 return NULL; 498 } 499 500 return res; 501 #else 502 #ifdef SWIFT_PACKAGE 503 NSBundle * bundle = SWIFTPM_MODULE_BUNDLE; 504 #else 505 NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]]; 506 #endif 507 508 const int64_t t_start = ggml_time_us(); 509 510 NSError * error = nil; 511 NSString * path_lib = ggml_metal_find_metallib(bundle, @"default"); 512 513 if (path_lib != nil) { 514 // pre-compiled library found: a single combined default.metallib 515 NSURL * libURL = [NSURL fileURLWithPath:path_lib]; 516 GGML_LOG_INFO("%s: loading '%s'\n", __func__, [path_lib UTF8String]); 517 518 res->objs[0] = [device newLibraryWithURL:libURL error:&error]; 519 res->single_library = true; 520 if (!res->objs[0]) { 521 GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]); 522 ggml_metal_library_free(res); 523 return NULL; 524 } 525 526 // the tensor API kernels are built into a separate metallib 527 if (ggml_metal_device_get_props(dev)->has_tensor) { 528 NSString * path_mm = ggml_metal_find_metallib(bundle, @"ggml-tensor"); 529 530 id lib_mm = nil; 531 if (path_mm != nil) { 532 lib_mm = [device newLibraryWithURL:[NSURL fileURLWithPath:path_mm] error:&error]; 533 if (!lib_mm && error) { 534 GGML_LOG_ERROR("%s: %s\n", __func__, [[error description] UTF8String]); 535 } 536 } 537 538 if (lib_mm) { 539 GGML_LOG_INFO("%s: loaded '%s'\n", __func__, [path_mm UTF8String]); 540 541 res->objs[GGML_METAL_LIB_MUL_MM] = [lib_mm retain]; 542 res->override_fns = [[NSSet setWithArray:[lib_mm functionNames]] retain]; 543 } else { 544 GGML_LOG_INFO("%s: ggml-tensor.metallib not found - disabling the tensor API\n", __func__); 545 546 ggml_metal_device_disable_tensor(dev); 547 } 548 } 549 550 GGML_LOG_INFO("%s: loaded in %.3f sec\n", __func__, (ggml_time_us() - t_start) / 1e6); 551 return res; 552 } 553 554 // no pre-compiled metallib: fall back to compiling each kernel source separately 555 GGML_LOG_INFO("%s: default.metallib not found, loading kernel sources\n", __func__); 556 557 NSString * path_resource = [[NSProcessInfo processInfo].environment objectForKey:@"GGML_METAL_PATH_RESOURCES"]; 558 if (path_resource) { 559 GGML_LOG_INFO("%s: GGML_METAL_PATH_RESOURCES = %s\n", __func__, [path_resource UTF8String]); 560 } 561 562 // resolve each kind's source path up front (file lookup/logging stays on the calling thread) 563 NSString ** path_per_kind = calloc(GGML_METAL_LIB_COUNT, sizeof(NSString *)); 564 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 565 NSString * rel = [NSString stringWithFormat:@"kernels/%s.metal", k_lib_names[kind]]; 566 567 NSString * path_source = nil; 568 if (path_resource) { 569 path_source = [path_resource stringByAppendingPathComponent:rel]; 570 } else { 571 NSString * stem = [NSString stringWithFormat:@"kernels/%s", k_lib_names[kind]]; 572 path_source = [bundle pathForResource:stem ofType:@"metal"]; 573 } 574 575 if (path_source == nil || ![[NSFileManager defaultManager] isReadableFileAtPath:path_source]) { 576 GGML_LOG_WARN("%s: could not locate %s in bundle, falling back to cwd\n", __func__, [rel UTF8String]); 577 path_source = rel; 578 } 579 580 GGML_LOG_DEBUG("%s: loading '%s'\n", __func__, [path_source UTF8String]); 581 582 path_per_kind[kind] = [path_source retain]; 583 } 584 585 const bool ok = ggml_metal_library_compile_all(res, device, prep, 586 ^NSString * (int kind, NSError ** err) { 587 return ggml_metal_library_flatten_source(path_per_kind[kind], err); 588 }, "source"); 589 590 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 591 [path_per_kind[kind] release]; 592 } 593 free(path_per_kind); 594 595 if (!ok) { 596 ggml_metal_library_free(res); 597 return NULL; 598 } 599 600 return res; 601 #endif 602 } 603 604 ggml_metal_library_t ggml_metal_library_init_from_source(ggml_metal_device_t dev, const char * source, bool verbose) { 605 if (source == NULL) { 606 GGML_LOG_ERROR("%s: source is NULL\n", __func__); 607 return NULL; 608 } 609 610 id device = ggml_metal_device_get_obj(dev); 611 id library = nil; 612 NSError * error = nil; 613 614 const int64_t t_start = ggml_time_us(); 615 616 NSString * src = [[NSString alloc] initWithBytes:source 617 length:strlen(source) 618 encoding:NSUTF8StringEncoding]; 619 if (!src) { 620 GGML_LOG_ERROR("%s: failed to create NSString from source\n", __func__); 621 return NULL; 622 } 623 624 @autoreleasepool { 625 NSMutableDictionary * prep = [NSMutableDictionary dictionary]; 626 627 MTLCompileOptions * options = [MTLCompileOptions new]; 628 options.preprocessorMacros = prep; 629 ggml_metal_compile_options_set_lang(options, ggml_metal_device_get_props(dev)->has_tensor); 630 631 library = [device newLibraryWithSource:src options:options error:&error]; 632 if (error) { 633 if (verbose) { 634 GGML_LOG_ERROR("%s: error compiling source: %s\n", __func__, [[error description] UTF8String]); 635 } else { 636 GGML_LOG_ERROR("%s: error compiling source\n", __func__); 637 } 638 library = nil; 639 } 640 641 [options release]; 642 } 643 644 [src release]; 645 646 if (!library) { 647 if (verbose) { 648 GGML_LOG_ERROR("%s: failed to create Metal library from source\n", __func__); 649 } 650 651 return NULL; 652 } 653 654 if (verbose) { 655 GGML_LOG_INFO("%s: compiled in %.3f sec\n", __func__, (ggml_time_us() - t_start) / 1e6); 656 } 657 658 ggml_metal_library_t res = calloc(1, sizeof(struct ggml_metal_library)); 659 if (!res) { 660 GGML_LOG_ERROR("%s: calloc failed\n", __func__); 661 return NULL; 662 } 663 664 res->objs[0] = library; 665 res->single_library = true; 666 res->dev = dev; 667 res->pipelines = ggml_metal_pipelines_init(); 668 res->lock = [NSLock new]; 669 670 return res; 671 } 672 673 void ggml_metal_library_free(ggml_metal_library_t lib) { 674 if (!lib) { 675 return; 676 } 677 678 for (int kind = 0; kind < GGML_METAL_LIB_COUNT; ++kind) { 679 if (lib->objs[kind]) { 680 [lib->objs[kind] release]; 681 } 682 } 683 684 if (lib->fn_to_lib) { 685 [lib->fn_to_lib release]; 686 } 687 688 if (lib->override_fns) { 689 [lib->override_fns release]; 690 } 691 692 ggml_metal_pipelines_free(lib->pipelines); 693 694 [lib->lock release]; 695 696 free(lib); 697 } 698 699 ggml_metal_device_t ggml_metal_library_get_device(ggml_metal_library_t lib) { 700 return lib->dev; 701 } 702 703 struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline(ggml_metal_library_t lib, const char * name) { 704 [lib->lock lock]; 705 706 struct ggml_metal_pipeline_with_params res = { 707 /*.pipeline =*/ nil, 708 /*.nsg =*/ 0, 709 /*.nr0 =*/ 0, 710 /*.nr1 =*/ 0, 711 /*.smem =*/ 0, 712 /*.c4 =*/ false, 713 /*.cnt =*/ false, 714 }; 715 716 res.pipeline = ggml_metal_pipelines_get(lib->pipelines, name); 717 718 [lib->lock unlock]; 719 720 return res; 721 } 722 723 struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_metal_library_t lib, const char * base, const char * name, ggml_metal_cv_t cv) { 724 struct ggml_metal_pipeline_with_params res = { 725 /*.pipeline =*/ nil, 726 /*.nsg =*/ 0, 727 /*.nr0 =*/ 0, 728 /*.nr1 =*/ 0, 729 /*.smem =*/ 0, 730 /*.c4 =*/ false, 731 /*.cnt =*/ false, 732 }; 733 734 [lib->lock lock]; 735 736 res.pipeline = ggml_metal_pipelines_get(lib->pipelines, name); 737 if (res.pipeline) { 738 [lib->lock unlock]; 739 740 return res; 741 } 742 743 @autoreleasepool { 744 NSError * error = nil; 745 746 NSString * base_func = [NSString stringWithUTF8String:base]; 747 748 GGML_LOG_DEBUG("%s: compiling pipeline: base = '%s', name = '%s'\n", __func__, base, name); 749 750 // route to the library that actually defines this kernel; fn_to_lib is 751 // built from -[MTLLibrary functionNames] so it's always in sync 752 int lib_idx = 0; 753 if (lib->override_fns && [lib->override_fns containsObject:base_func]) { 754 lib_idx = GGML_METAL_LIB_MUL_MM; 755 } else if (!lib->single_library) { 756 NSNumber * idx = lib->fn_to_lib[base_func]; 757 if (!idx) { 758 [lib->lock unlock]; 759 760 GGML_LOG_ERROR("%s: kernel not found in any metal library: base = '%s', name = '%s'\n", __func__, base, name); 761 762 return res; 763 } 764 lib_idx = [idx intValue]; 765 } 766 767 id mtl_lib = lib->objs[lib_idx]; 768 769 id mtl_function; 770 if (!cv) { 771 mtl_function = [mtl_lib newFunctionWithName:base_func]; 772 } else { 773 mtl_function = [mtl_lib newFunctionWithName:base_func constantValues:cv->obj error:&error]; 774 } 775 if (!mtl_function) { 776 [lib->lock unlock]; 777 778 GGML_LOG_ERROR("%s: failed to compile pipeline: base = '%s', name = '%s'\n", __func__, base, name); 779 if (error) { 780 GGML_LOG_ERROR("%s: %s\n", __func__, [[error description] UTF8String]); 781 } 782 783 return res; 784 } 785 786 id device = ggml_metal_device_get_obj(lib->dev); 787 id obj = [device newComputePipelineStateWithFunction:mtl_function error:&error]; 788 789 [mtl_function release]; 790 791 if (!obj) { 792 [lib->lock unlock]; 793 794 GGML_LOG_ERROR("%s: failed to create pipeline state: base = '%s', name = '%s'\n", __func__, base, name); 795 if (error) { 796 GGML_LOG_ERROR("%s: %s\n", __func__, [[error description] UTF8String]); 797 } 798 799 return res; 800 } 801 802 GGML_LOG_DEBUG("%s: loaded %-40s %16p | th_max = %4d | th_width = %4d\n", __func__, name, 803 (void *) obj, 804 (int) obj.maxTotalThreadsPerThreadgroup, 805 (int) obj.threadExecutionWidth); 806 807 if (obj.maxTotalThreadsPerThreadgroup == 0 || obj.threadExecutionWidth == 0) { 808 [obj release]; 809 810 [lib->lock unlock]; 811 812 GGML_LOG_ERROR("%s: incompatible pipeline %s\n", __func__, name); 813 814 return res; 815 } 816 817 res.pipeline = ggml_metal_pipeline_init(); 818 res.pipeline->obj = obj; 819 820 ggml_metal_pipelines_add(lib->pipelines, name, res.pipeline); 821 } 822 823 [lib->lock unlock]; 824 825 return res; 826 } 827 828 // 829 // MTLComputeCommandEncoder wrapper 830 // 831 832 struct ggml_metal_encoder { 833 id obj; 834 }; 835 836 ggml_metal_encoder_t ggml_metal_encoder_init(ggml_metal_cmd_buf_t cmd_buf_raw, bool concurrent) { 837 ggml_metal_encoder_t res = calloc(1, sizeof(struct ggml_metal_encoder)); 838 839 id cmd_buf = (id) cmd_buf_raw; 840 841 if (concurrent) { 842 res->obj = [cmd_buf computeCommandEncoderWithDispatchType: MTLDispatchTypeConcurrent]; 843 } else { 844 res->obj = [cmd_buf computeCommandEncoder]; 845 } 846 847 [res->obj retain]; 848 849 return res; 850 } 851 852 void ggml_metal_encoder_free(ggml_metal_encoder_t encoder) { 853 [encoder->obj release]; 854 free(encoder); 855 } 856 857 void ggml_metal_encoder_debug_group_push(ggml_metal_encoder_t encoder, const char * name) { 858 @autoreleasepool { 859 [encoder->obj pushDebugGroup:[NSString stringWithCString:name encoding:NSUTF8StringEncoding]]; 860 } 861 } 862 863 void ggml_metal_encoder_debug_group_pop (ggml_metal_encoder_t encoder) { 864 [encoder->obj popDebugGroup]; 865 } 866 867 void ggml_metal_encoder_set_pipeline(ggml_metal_encoder_t encoder, struct ggml_metal_pipeline_with_params pipeline) { 868 if (!pipeline.pipeline) { 869 GGML_ABORT("%s: nil Metal pipeline (missing kernel; see compile_pipeline log above)\n", __func__); 870 } 871 872 [encoder->obj setComputePipelineState:pipeline.pipeline->obj]; 873 } 874 875 void ggml_metal_encoder_set_bytes(ggml_metal_encoder_t encoder, void * data, size_t size, int idx) { 876 [encoder->obj setBytes:data length:size atIndex:idx]; 877 } 878 879 void ggml_metal_encoder_set_buffer(ggml_metal_encoder_t encoder, struct ggml_metal_buffer_id buffer, int idx) { 880 [encoder->obj setBuffer:buffer.metal offset:buffer.offs atIndex:idx]; 881 } 882 883 void ggml_metal_encoder_set_threadgroup_memory_size(ggml_metal_encoder_t encoder, size_t size, int idx) { 884 // ref: https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/setthreadgroupmemorylength(_:index:) 885 GGML_ASSERT(size % 16 == 0); 886 887 [encoder->obj setThreadgroupMemoryLength:size atIndex:idx]; 888 } 889 890 void ggml_metal_encoder_dispatch_threadgroups(ggml_metal_encoder_t encoder, int tg0, int tg1, int tg2, int tptg0, int tptg1, int tptg2) { 891 [encoder->obj dispatchThreadgroups:MTLSizeMake(tg0, tg1, tg2) threadsPerThreadgroup:MTLSizeMake(tptg0, tptg1, tptg2)]; 892 } 893 894 void ggml_metal_encoder_memory_barrier(ggml_metal_encoder_t encoder) { 895 [encoder->obj memoryBarrierWithScope:MTLBarrierScopeBuffers]; 896 } 897 898 void ggml_metal_encoder_end_encoding(ggml_metal_encoder_t encoder) { 899 [encoder->obj endEncoding]; 900 } 901 902 struct ggml_metal_device { 903 id mtl_device; 904 905 // a single global queue shared by all Metal backends 906 // technically not needed for devices with unified memory, but enables discrete GPUs support 907 // ref: https://github.com/ggml-org/llama.cpp/pull/15906 908 id mtl_queue; 909 910 ggml_metal_rsets_t rsets; 911 912 ggml_metal_library_t library; 913 914 struct ggml_metal_device_props props; 915 916 // shared fusion debugging context 917 struct ggml_metal_fusion_info * finfo; 918 919 // virtual address for GPU memory allocations 920 atomic_uintptr_t addr_virt; 921 }; 922 923 // 924 // MTLResidenceSet wrapper 925 // 926 927 struct ggml_metal_rsets { 928 NSLock * lock; 929 930 NSMutableArray * data; 931 932 // number of seconds since the last graph computation 933 // keep the residency sets wired for that amount of time to avoid being collected by the OS 934 int keep_alive_s; 935 int loops_per_s; 936 int time_per_loop_ms; 937 938 // background heartbeat thread to keep the residency sets alive 939 atomic_bool d_stop; 940 atomic_int d_loop; 941 942 dispatch_group_t d_group; 943 }; 944 945 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 946 static void ggml_metal_dummy_work(ggml_metal_device_t dev) { 947 if (dev->mtl_queue == nil) { 948 return; 949 } 950 951 @autoreleasepool { 952 // perform a minimal dummy operation on the GPU 953 id buf = [dev->mtl_device newBufferWithLength:1 options:MTLResourceStorageModePrivate]; 954 id cmd_buf = [dev->mtl_queue commandBuffer]; 955 956 { 957 id encoder = [cmd_buf blitCommandEncoder]; 958 959 [encoder fillBuffer:buf range:NSMakeRange(0, 1) value:0]; 960 961 [encoder endEncoding]; 962 } 963 964 [cmd_buf commit]; 965 [buf release]; 966 } 967 } 968 #endif 969 970 ggml_metal_rsets_t ggml_metal_rsets_init(ggml_metal_device_t dev) { 971 ggml_metal_rsets_t res = calloc(1, sizeof(struct ggml_metal_rsets)); 972 973 res->lock = [[NSLock alloc] init]; 974 res->data = [[NSMutableArray alloc] init]; 975 976 // by default keep the memory wired for 3 minutes 977 res->keep_alive_s = 3*60; 978 979 const char * GGML_METAL_RESIDENCY_KEEP_ALIVE_S = getenv("GGML_METAL_RESIDENCY_KEEP_ALIVE_S"); 980 if (GGML_METAL_RESIDENCY_KEEP_ALIVE_S) { 981 res->keep_alive_s = atoi(GGML_METAL_RESIDENCY_KEEP_ALIVE_S); 982 } 983 984 if (res->keep_alive_s <= 0) { 985 res->keep_alive_s = 3*60; 986 } 987 988 res->time_per_loop_ms = 5; 989 res->loops_per_s = 1000/res->time_per_loop_ms; 990 991 GGML_LOG_INFO("%s: creating a residency set collection (keep_alive = %d s)\n", __func__, res->keep_alive_s); 992 993 atomic_store_explicit(&res->d_stop, false, memory_order_relaxed); 994 atomic_store_explicit(&res->d_loop, res->loops_per_s*res->keep_alive_s, memory_order_relaxed); 995 996 res->d_group = dispatch_group_create(); 997 998 // start a background thread that periodically requests residency for all the currently active sets in the collection 999 // the requests stop after a certain amount of time (keep_alive_s) of inactivity 1000 dispatch_queue_t d_queue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0); 1001 dispatch_group_async(res->d_group, d_queue, ^{ 1002 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 1003 if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { 1004 while (!atomic_load_explicit(&res->d_stop, memory_order_relaxed)) { 1005 if (atomic_load_explicit(&res->d_loop, memory_order_relaxed) > 0) { 1006 [res->lock lock]; 1007 1008 for (int i = 0; i < (int) res->data.count; ++i) { 1009 [res->data[i] requestResidency]; 1010 } 1011 1012 atomic_fetch_sub_explicit(&res->d_loop, 1, memory_order_relaxed); 1013 1014 [res->lock unlock]; 1015 } 1016 1017 usleep(res->time_per_loop_ms * 1000); 1018 } 1019 } 1020 #endif 1021 }); 1022 1023 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 1024 if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { 1025 // workaround for residency set memory not being released if no GPU operation occurs 1026 // https://developer.apple.com/forums/thread/839089 1027 // https://github.com/ggml-org/llama.cpp/issues/25937 1028 ggml_metal_dummy_work(dev); 1029 } 1030 #endif 1031 1032 return res; 1033 } 1034 1035 void ggml_metal_rsets_free(ggml_metal_rsets_t rsets) { 1036 if (rsets == NULL) { 1037 return; 1038 } 1039 1040 // note: if you hit this assert, most likely you haven't deallocated all Metal resources before exiting 1041 GGML_ASSERT([rsets->data count] == 0); 1042 1043 atomic_store_explicit(&rsets->d_stop, true, memory_order_relaxed); 1044 1045 dispatch_group_wait(rsets->d_group, DISPATCH_TIME_FOREVER); 1046 dispatch_release(rsets->d_group); 1047 1048 [rsets->data release]; 1049 [rsets->lock release]; 1050 1051 free(rsets); 1052 } 1053 1054 static const struct { 1055 const char * name; 1056 const char * token; 1057 enum ggml_metal_device_id id; 1058 } k_metal_devices[] = { 1059 #define DEV(name, id) { name, #id, id } 1060 DEV("M1", GGML_METAL_DEVICE_M1), 1061 DEV("M1 Pro", GGML_METAL_DEVICE_M1_PRO), 1062 DEV("M1 Max", GGML_METAL_DEVICE_M1_MAX), 1063 DEV("M1 Ultra", GGML_METAL_DEVICE_M1_ULTRA), 1064 DEV("M2", GGML_METAL_DEVICE_M2), 1065 DEV("M2 Pro", GGML_METAL_DEVICE_M2_PRO), 1066 DEV("M2 Max", GGML_METAL_DEVICE_M2_MAX), 1067 DEV("M2 Ultra", GGML_METAL_DEVICE_M2_ULTRA), 1068 DEV("M3", GGML_METAL_DEVICE_M3), 1069 DEV("M3 Pro", GGML_METAL_DEVICE_M3_PRO), 1070 DEV("M3 Max", GGML_METAL_DEVICE_M3_MAX), 1071 DEV("M3 Ultra", GGML_METAL_DEVICE_M3_ULTRA), 1072 DEV("M4", GGML_METAL_DEVICE_M4), 1073 DEV("M4 Pro", GGML_METAL_DEVICE_M4_PRO), 1074 DEV("M4 Max", GGML_METAL_DEVICE_M4_MAX), 1075 DEV("M5", GGML_METAL_DEVICE_M5), 1076 DEV("M5 Pro", GGML_METAL_DEVICE_M5_PRO), 1077 DEV("M5 Max", GGML_METAL_DEVICE_M5_MAX), 1078 DEV("M5 Ultra", GGML_METAL_DEVICE_M5_ULTRA), 1079 DEV("A18 Pro", GGML_METAL_DEVICE_A18_PRO), 1080 #undef DEV 1081 }; 1082 1083 static enum ggml_metal_device_id ggml_metal_device_id_parse(const char * name) { 1084 if (!name) { 1085 return GGML_METAL_DEVICE_GENERIC; 1086 } 1087 1088 static const char prefix[] = "Apple "; 1089 if (strncmp(name, prefix, sizeof(prefix) - 1) != 0) { 1090 return GGML_METAL_DEVICE_GENERIC; 1091 } 1092 const char * suffix = name + sizeof(prefix) - 1; 1093 1094 for (size_t i = 0; i < sizeof(k_metal_devices)/sizeof(k_metal_devices[0]); ++i) { 1095 if (strcmp(suffix, k_metal_devices[i].name) == 0) { 1096 return k_metal_devices[i].id; 1097 } 1098 } 1099 return GGML_METAL_DEVICE_GENERIC; 1100 } 1101 1102 const char * ggml_metal_device_id_token(enum ggml_metal_device_id id) { 1103 for (size_t i = 0; i < sizeof(k_metal_devices)/sizeof(k_metal_devices[0]); ++i) { 1104 if (k_metal_devices[i].id == id) { 1105 return k_metal_devices[i].token; 1106 } 1107 } 1108 return "GGML_METAL_DEVICE_GENERIC"; 1109 } 1110 1111 ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { 1112 ggml_metal_device_t dev = calloc(1, sizeof(struct ggml_metal_device)); 1113 1114 assert(dev != NULL); 1115 1116 @autoreleasepool { 1117 if (dev->mtl_device == nil) { 1118 dev->mtl_device = MTLCreateSystemDefaultDevice(); 1119 1120 if (dev->mtl_device) { 1121 dev->mtl_queue = [dev->mtl_device newCommandQueue]; 1122 if (dev->mtl_queue == nil) { 1123 GGML_LOG_ERROR("%s: error: failed to create command queue\n", __func__); 1124 } 1125 1126 dev->addr_virt = 0x000000400ULL; 1127 1128 dev->props.device = device; 1129 1130 // the Metal backend uses the system default device as the single physical device; 1131 // additional (virtual) devices are emulated on top of it via GGML_METAL_DEVICES 1132 dev->props.device_phys = 0; 1133 dev->props.device_virt = device; 1134 1135 dev->props.has_simdgroup_reduction = [dev->mtl_device supportsFamily:MTLGPUFamilyApple7]; 1136 dev->props.has_simdgroup_reduction |= [dev->mtl_device supportsFamily:MTLGPUFamilyMetal3_GGML]; 1137 1138 dev->props.has_simdgroup_mm = [dev->mtl_device supportsFamily:MTLGPUFamilyApple7]; 1139 dev->props.has_unified_memory = dev->mtl_device.hasUnifiedMemory; 1140 1141 dev->props.has_bfloat = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal3_GGML]; 1142 dev->props.has_bfloat |= [dev->mtl_device supportsFamily:MTLGPUFamilyApple6]; 1143 if (getenv("GGML_METAL_BF16_DISABLE") != NULL) { 1144 dev->props.has_bfloat = false; 1145 } 1146 1147 dev->props.has_tensor = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal4_GGML]; 1148 if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) { 1149 dev->props.has_tensor = false; 1150 } 1151 1152 // note: disable the tensor API by default for old chips because with the current implementation it is not useful 1153 // - M2 Ultra: ~5% slower 1154 // - M4, M4 Max: no significant difference 1155 // 1156 // TODO: try to update the tensor API kernels to at least match the simdgroup performance 1157 if (getenv("GGML_METAL_TENSOR_ENABLE") == NULL && 1158 ![[dev->mtl_device name] containsString:@"M5"] && 1159 ![[dev->mtl_device name] containsString:@"M6"] && 1160 ![[dev->mtl_device name] containsString:@"A19"] && 1161 ![[dev->mtl_device name] containsString:@"A20"]) { 1162 GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__); 1163 dev->props.has_tensor = false; 1164 } 1165 1166 // double-check that the tensor API compiles 1167 if (dev->props.has_tensor) { 1168 const char * src_tensor_f16 = "\n" 1169 "#include \n" 1170 "#include \n" 1171 "#include \n" 1172 " \n" 1173 "using namespace metal; \n" 1174 "using namespace mpp::tensor_ops; \n" 1175 " \n" 1176 "kernel void dummy_kernel( \n" 1177 " tensor> A [[buffer(0)]], \n" 1178 " tensor> B [[buffer(1)]], \n" 1179 " device float * C [[buffer(2)]], \n" 1180 " uint2 tgid [[threadgroup_position_in_grid]]) \n" 1181 "{ \n" 1182 " auto tA = A.slice(0, (int)tgid.y); \n" 1183 " auto tB = B.slice((int)tgid.x, 0); \n" 1184 " \n" 1185 " matmul2d< \n" 1186 " matmul2d_descriptor(16, 16, dynamic_extent), \n" 1187 " execution_simdgroups<4>> mm; \n" 1188 " \n" 1189 " auto cT = mm.get_destination_cooperative_tensor(); \n" 1190 " \n" 1191 " auto sA = tA.slice(0, 0); \n" 1192 " auto sB = tB.slice(0, 0); \n" 1193 " mm.run(sB, sA, cT); \n" 1194 " \n" 1195 " auto tC = tensor, tensor_inline>(C, dextents(16, 16)); \n" 1196 " \n" 1197 " cT.store(tC); \n" 1198 "}"; 1199 1200 GGML_LOG_INFO("%s: testing tensor API for f16 support\n", __func__); 1201 ggml_metal_library_t lib = ggml_metal_library_init_from_source(dev, src_tensor_f16, false); 1202 if (lib == NULL) { 1203 GGML_LOG_WARN("%s: - the tensor API is not supported in this environment - disabling\n", __func__); 1204 dev->props.has_tensor = false; 1205 } else { 1206 struct ggml_metal_pipeline_with_params ppl = ggml_metal_library_compile_pipeline(lib, "dummy_kernel", "dummy_kernel", nil); 1207 if (!ppl.pipeline) { 1208 GGML_LOG_WARN("%s: - the tensor API is not supported in this environment - disabling\n", __func__); 1209 dev->props.has_tensor = false; 1210 } 1211 1212 ggml_metal_library_free(lib); 1213 } 1214 } 1215 1216 // try to compile a dummy kernel to determine if the tensor API is supported for bfloat 1217 if (dev->props.has_tensor && dev->props.has_bfloat) { 1218 const char * src_tensor_bf16 = "\n" 1219 "#include \n" 1220 "#include \n" 1221 "#include \n" 1222 " \n" 1223 "using namespace metal; \n" 1224 "using namespace mpp::tensor_ops; \n" 1225 " \n" 1226 "kernel void dummy_kernel( \n" 1227 " tensor> A [[buffer(0)]], \n" 1228 " tensor> B [[buffer(1)]], \n" 1229 " device float * C [[buffer(2)]], \n" 1230 " uint2 tgid [[threadgroup_position_in_grid]]) \n" 1231 "{ \n" 1232 " auto tA = A.slice(0, (int)tgid.y); \n" 1233 " auto tB = B.slice((int)tgid.x, 0); \n" 1234 " \n" 1235 " matmul2d< \n" 1236 " matmul2d_descriptor(16, 16, dynamic_extent), \n" 1237 " execution_simdgroups<4>> mm; \n" 1238 " \n" 1239 " auto cT = mm.get_destination_cooperative_tensor(); \n" 1240 " \n" 1241 " auto sA = tA.slice(0, 0); \n" 1242 " auto sB = tB.slice(0, 0); \n" 1243 " mm.run(sB, sA, cT); \n" 1244 " \n" 1245 " auto tC = tensor, tensor_inline>(C, dextents(16, 16)); \n" 1246 " \n" 1247 " cT.store(tC); \n" 1248 "}"; 1249 1250 GGML_LOG_INFO("%s: testing tensor API for bfloat support\n", __func__); 1251 ggml_metal_library_t lib = ggml_metal_library_init_from_source(dev, src_tensor_bf16, false); 1252 if (lib == NULL) { 1253 GGML_LOG_WARN("%s: - the tensor API does not support bfloat - disabling bfloat support\n", __func__); 1254 dev->props.has_bfloat = false; 1255 } else { 1256 struct ggml_metal_pipeline_with_params ppl = ggml_metal_library_compile_pipeline(lib, "dummy_kernel", "dummy_kernel", nil); 1257 if (!ppl.pipeline) { 1258 GGML_LOG_WARN("%s: - the tensor API does not support bfloat - disabling bfloat support\n", __func__); 1259 dev->props.has_bfloat = false; 1260 } 1261 1262 ggml_metal_library_free(lib); 1263 } 1264 } 1265 1266 dev->props.use_residency_sets = true; 1267 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 1268 dev->props.use_residency_sets = getenv("GGML_METAL_NO_RESIDENCY") == nil; 1269 #endif 1270 1271 dev->props.use_shared_buffers = dev->props.has_unified_memory; 1272 #if TARGET_OS_OSX && TARGET_CPU_X86_64 1273 // In case of eGPU, shared memory may be preferable. 1274 dev->props.use_shared_buffers |= [dev->mtl_device location] == MTLDeviceLocationExternal; 1275 #endif 1276 if (getenv("GGML_METAL_SHARED_BUFFERS_DISABLE") != NULL) { 1277 dev->props.use_shared_buffers = false; 1278 } 1279 if (getenv("GGML_METAL_SHARED_BUFFERS_ENABLE") != NULL) { 1280 dev->props.use_shared_buffers = true; 1281 } 1282 1283 dev->props.device_id = ggml_metal_device_id_parse([[dev->mtl_device name] UTF8String]); 1284 1285 dev->props.op_offload_min_batch_size = getenv("GGML_OP_OFFLOAD_MIN_BATCH") ? atoi(getenv("GGML_OP_OFFLOAD_MIN_BATCH")) : 32; 1286 1287 dev->props.max_buffer_size = dev->mtl_device.maxBufferLength; 1288 dev->props.max_theadgroup_memory_size = dev->mtl_device.maxThreadgroupMemoryLength; 1289 if (@available(macOS 10.12, iOS 16.0, *)) { 1290 dev->props.max_working_set_size = dev->mtl_device.recommendedMaxWorkingSetSize; 1291 } else { 1292 dev->props.max_working_set_size = dev->mtl_device.maxBufferLength; 1293 } 1294 1295 { 1296 const char * val = getenv("GGML_METAL_FUSION_DEBUG"); 1297 dev->finfo = ggml_metal_fusion_info_init( 1298 getenv("GGML_METAL_FUSION_DISABLE") == nil, 1299 val ? atoi(val) : 0); 1300 } 1301 1302 snprintf(dev->props.name, sizeof(dev->props.name), "%s%d", "MTL", device); 1303 const char * gpu_name = [[dev->mtl_device name] UTF8String]; 1304 if (n_devices > 1) { 1305 snprintf(dev->props.desc, sizeof(dev->props.desc), "%s (dev p%d/v%d)", 1306 gpu_name, dev->props.device_phys, dev->props.device_virt); 1307 } else { 1308 snprintf(dev->props.desc, sizeof(dev->props.desc), "%s", gpu_name); 1309 } 1310 1311 dev->library = ggml_metal_library_init(dev); 1312 if (!dev->library) { 1313 GGML_LOG_ERROR("%s: error: failed to create library\n", __func__); 1314 } 1315 1316 if (dev->props.use_residency_sets) { 1317 dev->rsets = ggml_metal_rsets_init(dev); 1318 } else { 1319 dev->rsets = nil; 1320 } 1321 1322 // print MTL GPU family: 1323 GGML_LOG_INFO("%s: GPU name: %s (%s)\n", __func__, dev->props.name, dev->props.desc); 1324 1325 // determine max supported GPU family 1326 // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf 1327 // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf 1328 { 1329 for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) { 1330 if ([dev->mtl_device supportsFamily:i]) { 1331 dev->props.gpu_family = i - (int) MTLGPUFamilyApple1 + 1; 1332 GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, dev->props.gpu_family, i); 1333 break; 1334 } 1335 } 1336 1337 #if TARGET_CPU_X86_64 1338 for (int i = MTLGPUFamilyCommon1 + 5; i >= MTLGPUFamilyCommon1; --i) { 1339 if ([dev->mtl_device supportsFamily:i]) { 1340 GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyCommon%d (%d)\n", __func__, i - (int) MTLGPUFamilyCommon1 + 1, i); 1341 break; 1342 } 1343 } 1344 #endif 1345 1346 for (int i = MTLGPUFamilyMetal3_GGML + 5; i >= MTLGPUFamilyMetal3_GGML; --i) { 1347 if ([dev->mtl_device supportsFamily:i]) { 1348 GGML_LOG_INFO("%s: GPU family: MTLGPUFamilyMetal%d (%d)\n", __func__, i - (int) MTLGPUFamilyMetal3_GGML + 3, i); 1349 break; 1350 } 1351 } 1352 } 1353 1354 GGML_LOG_INFO("%s: simdgroup reduction = %s\n", __func__, dev->props.has_simdgroup_reduction ? "true" : "false"); 1355 GGML_LOG_INFO("%s: simdgroup matrix mul. = %s\n", __func__, dev->props.has_simdgroup_mm ? "true" : "false"); 1356 GGML_LOG_INFO("%s: has unified memory = %s\n", __func__, dev->props.has_unified_memory ? "true" : "false"); 1357 GGML_LOG_INFO("%s: has bfloat = %s\n", __func__, dev->props.has_bfloat ? "true" : "false"); 1358 GGML_LOG_INFO("%s: has tensor = %s\n", __func__, dev->props.has_tensor ? "true" : "false"); 1359 GGML_LOG_INFO("%s: use residency sets = %s\n", __func__, dev->props.use_residency_sets ? "true" : "false"); 1360 GGML_LOG_INFO("%s: use shared buffers = %s\n", __func__, dev->props.use_shared_buffers ? "true" : "false"); 1361 1362 #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15) 1363 if (@available(macOS 10.12, iOS 16.0, *)) { 1364 GGML_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, dev->props.max_working_set_size / 1e6); 1365 } 1366 #endif 1367 } 1368 } 1369 } 1370 1371 return dev; 1372 } 1373 1374 void ggml_metal_device_free(ggml_metal_device_t dev) { 1375 assert(dev != NULL); 1376 1377 @autoreleasepool { 1378 ggml_metal_fusion_info_free(dev->finfo); 1379 1380 ggml_metal_rsets_free(dev->rsets); 1381 1382 ggml_metal_library_free(dev->library); 1383 dev->library = NULL; 1384 1385 if (dev->mtl_queue) { 1386 [dev->mtl_queue release]; 1387 dev->mtl_queue = nil; 1388 } 1389 1390 if (dev->mtl_device) { 1391 [dev->mtl_device release]; 1392 dev->mtl_device = nil; 1393 } 1394 } 1395 1396 free(dev); 1397 } 1398 1399 void * ggml_metal_device_get_obj(ggml_metal_device_t dev) { 1400 return dev->mtl_device; 1401 } 1402 1403 void * ggml_metal_device_get_queue(ggml_metal_device_t dev) { 1404 return dev->mtl_queue; 1405 } 1406 1407 ggml_metal_library_t ggml_metal_device_get_library(ggml_metal_device_t dev) { 1408 return dev->library; 1409 } 1410 1411 void ggml_metal_device_rsets_add(ggml_metal_device_t dev, ggml_metal_rset_t rset) { 1412 if (rset == nil) { 1413 return; 1414 } 1415 1416 GGML_ASSERT(dev->rsets); 1417 1418 [dev->rsets->lock lock]; 1419 1420 [dev->rsets->data addObject:rset]; 1421 1422 [dev->rsets->lock unlock]; 1423 } 1424 1425 void ggml_metal_device_rsets_rm(ggml_metal_device_t dev, ggml_metal_rset_t rset) { 1426 if (rset == nil) { 1427 return; 1428 } 1429 1430 GGML_ASSERT(dev->rsets); 1431 1432 [dev->rsets->lock lock]; 1433 1434 [dev->rsets->data removeObject:rset]; 1435 1436 [dev->rsets->lock unlock]; 1437 } 1438 1439 void ggml_metal_device_rsets_keep_alive(ggml_metal_device_t dev) { 1440 if (dev->rsets == NULL) { 1441 return; 1442 } 1443 1444 atomic_store_explicit(&dev->rsets->d_loop, dev->rsets->loops_per_s*dev->rsets->keep_alive_s, memory_order_relaxed); 1445 } 1446 1447 struct ggml_metal_event { 1448 void * obj; // id 1449 1450 atomic_int value; 1451 }; 1452 1453 void ggml_metal_event_encode_signal(ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf_raw) { 1454 id event = (id)ev->obj; 1455 1456 id cmd_buf = (id) cmd_buf_raw; 1457 1458 [cmd_buf encodeSignalEvent:event value:atomic_fetch_add_explicit(&ev->value, 1, memory_order_relaxed) + 1]; 1459 } 1460 1461 void ggml_metal_event_encode_wait(ggml_metal_event_t ev, ggml_metal_cmd_buf_t cmd_buf_raw) { 1462 id event = (id)ev->obj; 1463 1464 id cmd_buf = (id) cmd_buf_raw; 1465 1466 [cmd_buf encodeWaitForEvent:event value:atomic_load_explicit(&ev->value, memory_order_relaxed)]; 1467 } 1468 1469 ggml_metal_event_t ggml_metal_device_event_init(ggml_metal_device_t dev) { 1470 id event = [dev->mtl_device newSharedEvent]; 1471 1472 ggml_metal_event_t ev = calloc(1, sizeof(struct ggml_metal_event)); 1473 1474 ev->obj = (__bridge void *)event; 1475 ev->value = 0; 1476 1477 return ev; 1478 } 1479 1480 void ggml_metal_device_event_free(ggml_metal_device_t dev, ggml_metal_event_t ev) { 1481 @autoreleasepool { 1482 id event = ev->obj; 1483 [event release]; 1484 1485 free(ev); 1486 1487 GGML_UNUSED(dev); 1488 } 1489 } 1490 1491 void ggml_metal_device_event_synchronize(ggml_metal_device_t dev, ggml_metal_event_t ev) { 1492 id event = ev->obj; 1493 const bool res = [event waitUntilSignaledValue:atomic_load_explicit(&ev->value, memory_order_relaxed) timeoutMS:60000]; 1494 if (!res) { 1495 GGML_ABORT("%s: failed to wait for event\n", __func__); 1496 } 1497 1498 GGML_UNUSED(dev); 1499 } 1500 1501 void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t * total) { 1502 if (@available(macOS 10.12, iOS 16.0, *)) { 1503 *total = dev->mtl_device.recommendedMaxWorkingSetSize; 1504 size_t cur = dev->mtl_device.currentAllocatedSize; 1505 // it's possible to allocate more than `recommendedMaxWorkingSetSize` 1506 *free = *total > cur ? *total - cur : 0; 1507 } else { 1508 *free = 0; 1509 *total = 0; 1510 } 1511 } 1512 1513 static bool ggml_metal_supports_mul_mat_op( 1514 bool has_simdgroup_reduction, 1515 const struct ggml_tensor * op, 1516 bool src0_f16_has_mv, 1517 bool mm_path) { 1518 if (!has_simdgroup_reduction || 1519 op->src[0]->type == GGML_TYPE_F8_E4M3 || 1520 op->src[0]->type == GGML_TYPE_NVFP4 || 1521 op->src[0]->type == GGML_TYPE_TQ1_0) { 1522 return false; 1523 } 1524 1525 if (op->src[1]->type != GGML_TYPE_F16) { 1526 return true; 1527 } 1528 1529 if (op->src[0]->type == GGML_TYPE_BF16) { 1530 return false; 1531 } 1532 1533 if (src0_f16_has_mv && op->src[0]->type == GGML_TYPE_F16) { 1534 return true; 1535 } 1536 1537 return mm_path; 1538 } 1539 1540 bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_tensor * op) { 1541 const bool has_simdgroup_mm = dev->props.has_simdgroup_mm; 1542 const bool has_simdgroup_reduction = dev->props.has_simdgroup_reduction; 1543 const bool has_bfloat = dev->props.has_bfloat; 1544 1545 if (!has_bfloat) { 1546 if (op->type == GGML_TYPE_BF16) { 1547 return false; 1548 } 1549 1550 for (size_t i = 0, n = 3; i < n; ++i) { 1551 if (op->src[i] != NULL && op->src[i]->type == GGML_TYPE_BF16) { 1552 return false; 1553 } 1554 } 1555 } 1556 1557 switch (op->op) { 1558 case GGML_OP_SCALE: 1559 return ggml_is_contiguous_rows(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16); 1560 case GGML_OP_FILL: 1561 case GGML_OP_CLAMP: 1562 case GGML_OP_SQR: 1563 case GGML_OP_SQRT: 1564 case GGML_OP_SIN: 1565 case GGML_OP_COS: 1566 case GGML_OP_LOG: 1567 return ggml_is_contiguous_rows(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); 1568 case GGML_OP_UNARY: 1569 switch (ggml_get_unary_op(op)) { 1570 case GGML_UNARY_OP_TANH: 1571 case GGML_UNARY_OP_RELU: 1572 case GGML_UNARY_OP_SIGMOID: 1573 case GGML_UNARY_OP_GELU: 1574 case GGML_UNARY_OP_GELU_ERF: 1575 case GGML_UNARY_OP_GELU_QUICK: 1576 case GGML_UNARY_OP_SILU: 1577 case GGML_UNARY_OP_ELU: 1578 case GGML_UNARY_OP_NEG: 1579 case GGML_UNARY_OP_ABS: 1580 case GGML_UNARY_OP_SGN: 1581 case GGML_UNARY_OP_STEP: 1582 case GGML_UNARY_OP_HARDSWISH: 1583 case GGML_UNARY_OP_HARDSIGMOID: 1584 case GGML_UNARY_OP_EXP: 1585 case GGML_UNARY_OP_SOFTPLUS: 1586 case GGML_UNARY_OP_EXPM1: 1587 case GGML_UNARY_OP_FLOOR: 1588 case GGML_UNARY_OP_CEIL: 1589 case GGML_UNARY_OP_ROUND: 1590 case GGML_UNARY_OP_TRUNC: 1591 case GGML_UNARY_OP_XIELU: 1592 return ggml_is_contiguous_rows(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); 1593 default: 1594 return false; 1595 } 1596 case GGML_OP_SILU_BACK: 1597 return (op->src[0]->type == GGML_TYPE_F32) && 1598 (op->src[1]->type == GGML_TYPE_F32) && 1599 (op->type == GGML_TYPE_F32) && 1600 ggml_is_contiguous(op->src[0]) && 1601 ggml_is_contiguous(op->src[1]) && 1602 ggml_is_contiguous(op) && 1603 ggml_are_same_shape(op->src[0], op->src[1]); 1604 case GGML_OP_GLU: 1605 switch (ggml_get_glu_op(op)) { 1606 case GGML_GLU_OP_REGLU: 1607 case GGML_GLU_OP_GEGLU: 1608 case GGML_GLU_OP_SWIGLU: 1609 case GGML_GLU_OP_SWIGLU_OAI: 1610 case GGML_GLU_OP_GEGLU_ERF: 1611 case GGML_GLU_OP_GEGLU_QUICK: 1612 case GGML_GLU_OP_SWIGLU_CLAMP: 1613 return ggml_is_contiguous_1(op->src[0]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); 1614 default: 1615 return false; 1616 } 1617 case GGML_OP_NONE: 1618 case GGML_OP_RESHAPE: 1619 case GGML_OP_VIEW: 1620 case GGML_OP_TRANSPOSE: 1621 case GGML_OP_PERMUTE: 1622 return true; 1623 case GGML_OP_CONCAT: 1624 { 1625 const enum ggml_type src0_type = op->src[0]->type; 1626 const enum ggml_type src1_type = op->src[1]->type; 1627 if (src0_type != src1_type || src0_type != op->type) { 1628 return false; 1629 } 1630 switch (src0_type) { 1631 case GGML_TYPE_F32: 1632 case GGML_TYPE_F16: 1633 case GGML_TYPE_I8: 1634 case GGML_TYPE_I16: 1635 case GGML_TYPE_I32: 1636 case GGML_TYPE_I64: 1637 return true; 1638 case GGML_TYPE_BF16: 1639 return has_bfloat; 1640 case GGML_TYPE_Q4_0: 1641 case GGML_TYPE_Q4_1: 1642 case GGML_TYPE_Q5_0: 1643 case GGML_TYPE_Q5_1: 1644 case GGML_TYPE_Q8_0: 1645 return true; 1646 default: 1647 return false; 1648 } 1649 } 1650 case GGML_OP_ADD: 1651 case GGML_OP_SUB: 1652 case GGML_OP_MUL: 1653 case GGML_OP_DIV: 1654 case GGML_OP_ADD_ID: 1655 return ggml_is_contiguous_rows(op->src[0]) && ggml_is_contiguous_rows(op->src[1]) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && (op->src[0]->type == op->src[1]->type); 1656 case GGML_OP_ACC: 1657 return ggml_is_contiguous_rows(op->src[0]) && ggml_is_contiguous_rows(op->src[1]) && op->src[0]->type == GGML_TYPE_F32; 1658 case GGML_OP_REPEAT: 1659 case GGML_OP_CONV_TRANSPOSE_1D: 1660 return true; 1661 case GGML_OP_CONV_TRANSPOSE_2D: 1662 return ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]) && 1663 (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) && 1664 op->src[1]->type == GGML_TYPE_F32 && 1665 op->type == GGML_TYPE_F32; 1666 case GGML_OP_COL2IM_1D: 1667 return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) && 1668 op->type == op->src[0]->type && 1669 ggml_is_contiguous(op->src[0]) && 1670 ggml_is_contiguous(op); 1671 case GGML_OP_CONV_3D: 1672 return ggml_is_contiguous(op->src[0]) && 1673 ggml_is_contiguous(op->src[1]) && 1674 (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32) && 1675 op->src[1]->type == GGML_TYPE_F32; 1676 case GGML_OP_SUM: 1677 return has_simdgroup_reduction && ggml_is_contiguous(op->src[0]); 1678 case GGML_OP_TRI: 1679 return ggml_is_contiguous_rows(op->src[0]); 1680 case GGML_OP_SUM_ROWS: 1681 case GGML_OP_CUMSUM: 1682 case GGML_OP_MEAN: 1683 case GGML_OP_SOFT_MAX: 1684 case GGML_OP_GROUP_NORM: 1685 case GGML_OP_L2_NORM: 1686 return has_simdgroup_reduction && ggml_is_contiguous_rows(op->src[0]); 1687 case GGML_OP_COUNT_EQUAL: 1688 return has_simdgroup_reduction && 1689 op->src[0]->type == GGML_TYPE_I32 && 1690 op->src[1]->type == GGML_TYPE_I32 && 1691 op->type == GGML_TYPE_I64; 1692 case GGML_OP_ARGMAX: 1693 return has_simdgroup_reduction; 1694 case GGML_OP_NORM: 1695 case GGML_OP_RMS_NORM: 1696 return has_simdgroup_reduction && (ggml_is_contiguous_rows(op->src[0])); 1697 case GGML_OP_ROPE: 1698 case GGML_OP_ROPE_BACK: 1699 return true; 1700 case GGML_OP_IM2COL: 1701 return ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 && (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32); 1702 case GGML_OP_CONV_2D: 1703 return ggml_is_contiguous(op->src[0]) && 1704 op->src[1]->type == GGML_TYPE_F32 && 1705 op->type == GGML_TYPE_F32 && 1706 (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32); 1707 case GGML_OP_CONV_2D_DW: 1708 return op->src[1]->type == GGML_TYPE_F32 && 1709 op->type == GGML_TYPE_F32 && 1710 (op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32); 1711 case GGML_OP_UPSCALE: 1712 return op->src[0]->type == GGML_TYPE_F32; 1713 case GGML_OP_POOL_1D: 1714 return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; 1715 case GGML_OP_POOL_2D: 1716 return op->src[0]->type == GGML_TYPE_F32; 1717 case GGML_OP_PAD: 1718 case GGML_OP_PAD_REFLECT_1D: 1719 case GGML_OP_TIMESTEP_EMBEDDING: 1720 return op->src[0]->type == GGML_TYPE_F32; 1721 case GGML_OP_LEAKY_RELU: 1722 return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; 1723 case GGML_OP_ARGSORT: 1724 case GGML_OP_TOP_K: 1725 case GGML_OP_ARANGE: 1726 return true; 1727 case GGML_OP_ROLL: 1728 return ggml_is_contiguous(op->src[0]); 1729 case GGML_OP_FLASH_ATTN_EXT: 1730 // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice 1731 if (op->src[5] != NULL) { 1732 const struct ggml_tensor * kv_rows = op->src[5]; 1733 1734 if (kv_rows->type != GGML_TYPE_I32 || 1735 !ggml_is_contiguous(kv_rows) || 1736 kv_rows->ne[2] != 1 || kv_rows->ne[3] != 1 || 1737 kv_rows->ne[1] != op->src[0]->ne[3] || 1738 !op->src[3] || op->src[1]->ne[3] != 1 || op->src[2]->ne[3] != 1) { 1739 return false; 1740 } 1741 1742 // the non-vec kernels attend over a contiguous F16 copy of the referenced rows: 1743 // - F16 K/V is gathered directly 1744 // - quantized K/V is first dequantized with kernel_flash_attn_ext_kv_*_f16 1745 // - other types keep attending to the whole cache (dense mask) 1746 switch (op->src[1]->type) { 1747 case GGML_TYPE_F16: 1748 case GGML_TYPE_Q4_0: 1749 case GGML_TYPE_Q4_1: 1750 case GGML_TYPE_Q5_0: 1751 case GGML_TYPE_Q5_1: 1752 case GGML_TYPE_Q8_0: 1753 break; 1754 default: 1755 return false; 1756 } 1757 1758 // the row gather copies F16 values in groups of 4 1759 if (op->src[2]->ne[0] % 4 != 0) { 1760 return false; 1761 } 1762 } 1763 // for new head sizes, add checks here 1764 if (op->src[0]->ne[0] != 32 && 1765 op->src[0]->ne[0] != 40 && 1766 op->src[0]->ne[0] != 48 && 1767 op->src[0]->ne[0] != 64 && 1768 op->src[0]->ne[0] != 72 && 1769 op->src[0]->ne[0] != 80 && 1770 op->src[0]->ne[0] != 96 && 1771 op->src[0]->ne[0] != 112 && 1772 op->src[0]->ne[0] != 128 && 1773 op->src[0]->ne[0] != 192 && 1774 op->src[0]->ne[0] != 256 && 1775 op->src[0]->ne[0] != 320 && 1776 op->src[0]->ne[0] != 512 && 1777 op->src[0]->ne[0] != 576) { 1778 return false; 1779 } 1780 // the kernels exist for K == V and for these K > V pairs only 1781 if (op->src[1]->ne[0] != op->src[2]->ne[0] && 1782 !(op->src[1]->ne[0] == 96 && op->src[2]->ne[0] == 64) && 1783 !(op->src[1]->ne[0] == 128 && op->src[2]->ne[0] == 96) && 1784 !(op->src[1]->ne[0] == 192 && op->src[2]->ne[0] == 128) && 1785 !(op->src[1]->ne[0] == 320 && op->src[2]->ne[0] == 256) && 1786 !(op->src[1]->ne[0] == 576 && op->src[2]->ne[0] == 512)) { 1787 return false; 1788 } 1789 if (op->src[1]->type != op->src[2]->type) { 1790 return false; 1791 } 1792 switch (op->src[1]->type) { 1793 case GGML_TYPE_F32: 1794 case GGML_TYPE_F16: 1795 case GGML_TYPE_Q8_0: 1796 case GGML_TYPE_Q4_0: 1797 case GGML_TYPE_Q4_1: 1798 case GGML_TYPE_Q5_0: 1799 case GGML_TYPE_Q5_1: 1800 break; 1801 case GGML_TYPE_BF16: 1802 if (!has_bfloat) { 1803 return false; 1804 } 1805 break; 1806 default: 1807 return false; 1808 } 1809 return has_simdgroup_mm; // TODO: over-restricted for vec-kernels 1810 case GGML_OP_LIGHTNING_INDEXER: 1811 if (op->src[0]->ne[0] != OP_LIGHTNING_INDEXER_DK) { 1812 return false; 1813 } 1814 if (!has_simdgroup_mm || 1815 op->src[0]->type != GGML_TYPE_F32 || 1816 op->src[2]->type != GGML_TYPE_F32 || 1817 op->src[3]->type != GGML_TYPE_F16 || 1818 op->type != GGML_TYPE_F32 || 1819 !ggml_is_contiguous_rows(op->src[0]) || 1820 !ggml_is_contiguous_rows(op->src[1]) || 1821 !ggml_is_contiguous_rows(op->src[2]) || 1822 !ggml_is_contiguous_rows(op->src[3])) { 1823 return false; 1824 } 1825 switch (op->src[1]->type) { 1826 case GGML_TYPE_F32: 1827 case GGML_TYPE_F16: 1828 case GGML_TYPE_Q4_0: 1829 case GGML_TYPE_Q4_1: 1830 case GGML_TYPE_Q5_0: 1831 case GGML_TYPE_Q5_1: 1832 case GGML_TYPE_Q8_0: 1833 return true; 1834 case GGML_TYPE_BF16: 1835 return has_bfloat; 1836 default: 1837 return false; 1838 } 1839 case GGML_OP_DSV4_HC_COMB: 1840 return has_simdgroup_reduction && 1841 op->src[0]->type == GGML_TYPE_F32 && 1842 op->src[1]->type == GGML_TYPE_F32 && 1843 op->src[2]->type == GGML_TYPE_F32 && 1844 op->type == GGML_TYPE_F32 && 1845 op->src[0]->ne[0] == 24 && 1846 op->src[1]->ne[0] >= 3 && 1847 op->src[2]->ne[0] == 24 && 1848 ggml_is_contiguous_rows(op->src[0]) && 1849 ggml_is_contiguous_rows(op->src[1]) && 1850 ggml_is_contiguous_rows(op->src[2]); 1851 case GGML_OP_DSV4_HC_PRE: 1852 return has_simdgroup_reduction && 1853 op->src[0]->type == GGML_TYPE_F32 && 1854 op->src[1]->type == GGML_TYPE_F32 && 1855 op->type == GGML_TYPE_F32 && 1856 ggml_is_contiguous_rows(op->src[0]) && 1857 ggml_is_contiguous_rows(op->src[1]); 1858 case GGML_OP_DSV4_HC_POST: 1859 return has_simdgroup_reduction && 1860 op->src[0]->type == GGML_TYPE_F32 && 1861 op->src[1]->type == GGML_TYPE_F32 && 1862 op->src[2]->type == GGML_TYPE_F32 && 1863 (op->src[3] == NULL || op->src[3]->type == GGML_TYPE_F32) && 1864 op->type == GGML_TYPE_F32 && 1865 op->src[1]->ne[1] == 4 && 1866 op->src[2]->ne[0] == 4 && 1867 (op->src[3] == NULL || (op->src[3]->ne[0] == 4 && op->src[3]->ne[1] == 4)) && 1868 ggml_is_contiguous_rows(op->src[0]) && 1869 ggml_is_contiguous_rows(op->src[1]) && 1870 ggml_is_contiguous_rows(op->src[2]) && 1871 (op->src[3] == NULL || ggml_is_contiguous_rows(op->src[3])); 1872 case GGML_OP_TOP_K_MASK: 1873 return (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32) && 1874 op->src[0]->type == op->type && 1875 op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && 1876 op->nb[0] == ggml_type_size(op->type) && 1877 op->src[1]->type == GGML_TYPE_I32 && 1878 (op->src[2] == NULL || op->src[2]->type == GGML_TYPE_F32) && 1879 (op->src[3] == NULL || op->src[3]->type == GGML_TYPE_I32) && 1880 (op->src[4] == NULL || op->src[4]->type == GGML_TYPE_I32); 1881 case GGML_OP_SSM_SCAN: 1882 return has_simdgroup_reduction; 1883 case GGML_OP_SSM_CONV: 1884 return has_simdgroup_reduction; 1885 case GGML_OP_RWKV_WKV6: 1886 case GGML_OP_RWKV_WKV7: 1887 return true; 1888 case GGML_OP_GATED_DELTA_NET: 1889 return has_simdgroup_reduction && op->src[2]->ne[0] % 32 == 0; 1890 case GGML_OP_SOLVE_TRI: 1891 return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32; 1892 case GGML_OP_MUL_MAT: 1893 // the FWHT kernels read an F16 source directly; every other F16 src1 path 1894 // still goes through ggml_metal_supports_mul_mat_op 1895 if (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F16 && 1896 ggml_metal_op_mul_mat_use_fwht(op, dev->props.max_theadgroup_memory_size)) { 1897 return has_simdgroup_reduction; 1898 } 1899 return ggml_metal_supports_mul_mat_op( 1900 has_simdgroup_reduction, op, true, 1901 ggml_metal_op_mul_mat_use_mm(op, has_simdgroup_mm)); 1902 case GGML_OP_MUL_MAT_ID: 1903 return ggml_metal_supports_mul_mat_op( 1904 has_simdgroup_reduction, op, false, 1905 ggml_metal_op_mul_mat_id_use_mm(op, has_simdgroup_mm)); 1906 case GGML_OP_SET: 1907 case GGML_OP_CPY: 1908 case GGML_OP_DUP: 1909 case GGML_OP_CONT: 1910 { 1911 switch (op->src[0]->type) { 1912 case GGML_TYPE_F32: 1913 switch (op->type) { 1914 case GGML_TYPE_F32: 1915 case GGML_TYPE_F16: 1916 case GGML_TYPE_BF16: 1917 case GGML_TYPE_Q8_0: 1918 case GGML_TYPE_Q1_0: 1919 case GGML_TYPE_Q2_0: 1920 case GGML_TYPE_Q4_0: 1921 case GGML_TYPE_Q4_1: 1922 case GGML_TYPE_Q5_0: 1923 case GGML_TYPE_Q5_1: 1924 case GGML_TYPE_IQ4_NL: 1925 case GGML_TYPE_TQ2_0: 1926 case GGML_TYPE_I32: 1927 return true; 1928 default: 1929 return false; 1930 } 1931 case GGML_TYPE_F16: 1932 switch (op->type) { 1933 case GGML_TYPE_F32: 1934 case GGML_TYPE_F16: 1935 return true; 1936 default: 1937 return false; 1938 } 1939 case GGML_TYPE_BF16: 1940 switch (op->type) { 1941 case GGML_TYPE_F32: 1942 case GGML_TYPE_BF16: 1943 return true; 1944 default: 1945 return false; 1946 } 1947 case GGML_TYPE_Q1_0: 1948 case GGML_TYPE_Q2_0: 1949 case GGML_TYPE_Q4_0: 1950 case GGML_TYPE_Q4_1: 1951 case GGML_TYPE_Q5_0: 1952 case GGML_TYPE_Q5_1: 1953 case GGML_TYPE_Q8_0: 1954 case GGML_TYPE_TQ2_0: 1955 switch (op->type) { 1956 case GGML_TYPE_F32: 1957 case GGML_TYPE_F16: 1958 return true; 1959 default: 1960 return false; 1961 } 1962 case GGML_TYPE_I32: 1963 return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32; 1964 default: 1965 return false; 1966 }; 1967 } 1968 case GGML_OP_GET_ROWS: 1969 return op->src[0]->type != GGML_TYPE_NVFP4 && 1970 op->src[0]->type != GGML_TYPE_TQ1_0 && 1971 op->src[0]->type != GGML_TYPE_F8_E4M3; 1972 case GGML_OP_SET_ROWS: 1973 { 1974 if (op->src[0]->type == GGML_TYPE_F16) { 1975 return op->type == GGML_TYPE_F16; 1976 } 1977 1978 if (op->src[0]->type != GGML_TYPE_F32) { 1979 return false; 1980 } 1981 1982 switch (op->type) { 1983 case GGML_TYPE_F32: 1984 case GGML_TYPE_F16: 1985 case GGML_TYPE_BF16: 1986 case GGML_TYPE_Q8_0: 1987 case GGML_TYPE_Q4_0: 1988 case GGML_TYPE_Q4_1: 1989 case GGML_TYPE_Q5_0: 1990 case GGML_TYPE_Q5_1: 1991 case GGML_TYPE_IQ4_NL: 1992 case GGML_TYPE_TQ2_0: 1993 return true; 1994 default: 1995 return false; 1996 }; 1997 } 1998 case GGML_OP_DIAG: 1999 return true; 2000 case GGML_OP_OPT_STEP_ADAMW: 2001 case GGML_OP_OPT_STEP_SGD: 2002 return has_simdgroup_reduction; 2003 default: 2004 return false; 2005 } 2006 } 2007 2008 const struct ggml_metal_device_props * ggml_metal_device_get_props(ggml_metal_device_t dev) { 2009 return &dev->props; 2010 } 2011 2012 static void ggml_metal_device_disable_tensor(ggml_metal_device_t dev) { 2013 dev->props.has_tensor = false; 2014 } 2015 2016 struct ggml_metal_fusion_info * ggml_metal_device_get_fusion_info(ggml_metal_device_t dev) { 2017 return dev->finfo; 2018 } 2019 2020 // 2021 // device buffers 2022 // 2023 2024 // max memory buffers that can be mapped to the device 2025 #define GGML_METAL_MAX_BUFFERS 64 2026 2027 struct ggml_metal_buffer_wrapper { 2028 void * data; 2029 size_t size; 2030 2031 id metal; 2032 }; 2033 2034 struct ggml_metal_buffer { 2035 void * all_data; 2036 size_t all_size; 2037 2038 // if false, the Metal buffer data is allocated in private GPU memory and is not shared with the host 2039 bool is_shared; 2040 bool owned; 2041 2042 // multiple buffers are used only to avoid the maximum buffer size limitation when using mmap 2043 int n_buffers; 2044 struct ggml_metal_buffer_wrapper buffers[GGML_METAL_MAX_BUFFERS]; 2045 2046 bool use_residency_sets; 2047 2048 // optional MTLResidencySet 2049 // note: cannot use explicitly "id" here because it is not available on certain OSes 2050 id rset; 2051 2052 // pointers to global device 2053 ggml_metal_device_t dev; 2054 }; 2055 2056 static void ggml_metal_log_allocated_size(id device, size_t size_aligned) { 2057 #ifndef GGML_METAL_NDEBUG 2058 #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15) 2059 if (@available(macOS 10.12, iOS 16.0, *)) { 2060 GGML_LOG_DEBUG("%s: allocated buffer, size = %8.2f MiB, (%8.2f / %8.2f)\n", 2061 __func__, 2062 size_aligned / 1024.0 / 1024.0, 2063 device.currentAllocatedSize / 1024.0 / 1024.0, 2064 device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0); 2065 2066 if (device.currentAllocatedSize > device.recommendedMaxWorkingSetSize) { 2067 GGML_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__); 2068 } 2069 } else { 2070 GGML_LOG_INFO("%s: allocated buffer, size = %8.2f MiB, (%8.2f)\n", 2071 __func__, 2072 size_aligned / 1024.0 / 1024.0, 2073 device.currentAllocatedSize / 1024.0 / 1024.0); 2074 } 2075 #endif 2076 #endif 2077 GGML_UNUSED(device); 2078 GGML_UNUSED(size_aligned); 2079 } 2080 2081 // rset init 2082 static bool ggml_metal_buffer_rset_init(ggml_metal_buffer_t buf) { 2083 buf->rset = nil; 2084 2085 if (!buf->use_residency_sets) { 2086 return true; 2087 } 2088 2089 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 2090 if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { 2091 MTLResidencySetDescriptor * desc = [[MTLResidencySetDescriptor alloc] init]; 2092 desc.label = @"ggml_metal"; 2093 desc.initialCapacity = buf->n_buffers; 2094 2095 NSError * error; 2096 buf->rset = [buf->dev->mtl_device newResidencySetWithDescriptor:desc error:&error]; 2097 if (error) { 2098 GGML_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]); 2099 [desc release]; 2100 return false; 2101 } 2102 2103 [desc release]; 2104 2105 for (int i = 0; i < buf->n_buffers; i++) { 2106 [buf->rset addAllocation:buf->buffers[i].metal]; 2107 } 2108 2109 [buf->rset commit]; 2110 [buf->rset requestResidency]; 2111 2112 return true; 2113 } 2114 #endif 2115 2116 return true; 2117 } 2118 2119 // rset free 2120 static void ggml_metal_buffer_rset_free(ggml_metal_buffer_t buf) { 2121 #if defined(GGML_METAL_HAS_RESIDENCY_SETS) 2122 if (@available(macOS 15.0, iOS 18.0, tvOS 18.0, visionOS 2.0, *)) { 2123 if (buf->rset) { 2124 [buf->rset endResidency]; 2125 [buf->rset removeAllAllocations]; 2126 [buf->rset commit]; 2127 [buf->rset release]; 2128 } 2129 } 2130 #else 2131 GGML_UNUSED(buf); 2132 #endif 2133 } 2134 2135 static void * ggml_metal_host_malloc(size_t n) { 2136 void * data = NULL; 2137 2138 kern_return_t err = vm_allocate((vm_map_t) mach_task_self(), (void *) &data, n, VM_FLAGS_ANYWHERE); 2139 if (err != KERN_SUCCESS) { 2140 GGML_LOG_ERROR("%s: error: vm_allocate failed\n", __func__); 2141 return NULL; 2142 } 2143 2144 return data; 2145 } 2146 2147 ggml_metal_buffer_t ggml_metal_buffer_init(ggml_metal_device_t dev, size_t size, bool shared) { 2148 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); 2149 2150 res->dev = dev; 2151 2152 const size_t size_page = sysconf(_SC_PAGESIZE); 2153 2154 size_t size_aligned = size; 2155 if ((size_aligned % size_page) != 0) { 2156 size_aligned += (size_page - (size_aligned % size_page)); 2157 } 2158 2159 const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev); 2160 2161 shared = shared && props_dev->use_shared_buffers; 2162 2163 // allocate shared buffer if the device supports it and it is required by the buffer type 2164 if (shared) { 2165 res->all_data = ggml_metal_host_malloc(size_aligned); 2166 res->is_shared = true; 2167 } else { 2168 // use virtual address 2169 res->all_data = (void *) atomic_fetch_add_explicit(&dev->addr_virt, size_aligned, memory_order_relaxed); 2170 res->is_shared = false; 2171 } 2172 res->all_size = size_aligned; 2173 2174 res->owned = true; 2175 2176 res->n_buffers = 1; 2177 2178 if (res->all_data != NULL) { 2179 res->buffers[0].size = size; 2180 res->buffers[0].metal = nil; 2181 2182 if (size_aligned > 0) { 2183 if (props_dev->use_shared_buffers && shared) { 2184 res->buffers[0].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:res->all_data 2185 length:size_aligned 2186 options:MTLResourceStorageModeShared 2187 deallocator:nil]; 2188 } else { 2189 res->buffers[0].metal = [res->dev->mtl_device newBufferWithLength:size_aligned options:MTLResourceStorageModePrivate]; 2190 } 2191 } 2192 2193 res->buffers[0].data = res->all_data; 2194 } 2195 2196 if (size_aligned > 0 && (res->all_data == NULL || res->buffers[0].metal == nil)) { 2197 GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0); 2198 free(res); 2199 return NULL; 2200 } 2201 2202 res->use_residency_sets = props_dev->use_residency_sets; 2203 2204 if (!ggml_metal_buffer_rset_init(res)) { 2205 GGML_LOG_ERROR("%s: error: failed to initialize residency set\n", __func__); 2206 free(res); 2207 return NULL; 2208 } 2209 2210 ggml_metal_device_rsets_add(dev, res->rset); 2211 2212 //ggml_metal_log_allocated_size(device, size_aligned); 2213 2214 return res; 2215 } 2216 2217 ggml_metal_buffer_t ggml_metal_buffer_map(ggml_metal_device_t dev, void * ptr, size_t size, size_t max_tensor_size) { 2218 ggml_metal_buffer_t res = calloc(1, sizeof(struct ggml_metal_buffer)); 2219 2220 res->dev = dev; 2221 2222 res->all_data = ptr; 2223 res->all_size = size; 2224 2225 res->is_shared = true; 2226 res->owned = false; 2227 2228 res->n_buffers = 0; 2229 2230 const size_t size_page = sysconf(_SC_PAGESIZE); 2231 2232 // page-align the data ptr 2233 { 2234 const uintptr_t offs = (uintptr_t) ptr % size_page; 2235 ptr = (void *) ((char *) ptr - offs); 2236 size += offs; 2237 } 2238 2239 size_t size_aligned = size; 2240 if ((size_aligned % size_page) != 0) { 2241 size_aligned += (size_page - (size_aligned % size_page)); 2242 } 2243 2244 const struct ggml_metal_device_props * props_dev = ggml_metal_device_get_props(dev); 2245 2246 // the buffer fits into the max buffer size allowed by the device 2247 if (size_aligned <= props_dev->max_buffer_size) { 2248 res->buffers[res->n_buffers].data = ptr; 2249 res->buffers[res->n_buffers].size = size; 2250 res->buffers[res->n_buffers].metal = nil; 2251 2252 if (size_aligned > 0) { 2253 res->buffers[res->n_buffers].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:ptr length:size_aligned options:MTLResourceStorageModeShared deallocator:nil]; 2254 2255 if (res->buffers[res->n_buffers].metal == nil) { 2256 GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0); 2257 free(res); 2258 return NULL; 2259 } 2260 } 2261 2262 ggml_metal_log_allocated_size(res->dev->mtl_device, size_aligned); 2263 2264 ++res->n_buffers; 2265 } else { 2266 // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into 2267 // one of the views 2268 const size_t size_ovlp = ((max_tensor_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case 2269 const size_t size_step = props_dev->max_buffer_size - size_ovlp; 2270 const size_t size_view = props_dev->max_buffer_size; 2271 2272 for (size_t i = 0; i < size; i += size_step) { 2273 const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i); 2274 2275 res->buffers[res->n_buffers].data = (void *) ((uint8_t *) ptr + i); 2276 res->buffers[res->n_buffers].size = size_step_aligned; 2277 res->buffers[res->n_buffers].metal = nil; 2278 2279 if (size_step_aligned > 0) { 2280 res->buffers[res->n_buffers].metal = [res->dev->mtl_device newBufferWithBytesNoCopy:(void *) ((uint8_t *) ptr + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil]; 2281 2282 if (res->buffers[res->n_buffers].metal == nil) { 2283 GGML_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_step_aligned / 1024.0 / 1024.0); 2284 free(res); 2285 return NULL; 2286 } 2287 } 2288 2289 ggml_metal_log_allocated_size(res->dev->mtl_device, size_step_aligned); 2290 2291 if (i + size_step < size) { 2292 GGML_LOG_INFO("\n"); 2293 } 2294 2295 ++res->n_buffers; 2296 } 2297 } 2298 2299 res->use_residency_sets = props_dev->use_residency_sets; 2300 2301 if (!ggml_metal_buffer_rset_init(res)) { 2302 GGML_LOG_ERROR("%s: error: failed to initialize residency set\n", __func__); 2303 free(res); 2304 return NULL; 2305 } 2306 2307 ggml_metal_device_rsets_add(dev, res->rset); 2308 2309 return res; 2310 } 2311 2312 void ggml_metal_buffer_free(ggml_metal_buffer_t buf) { 2313 @autoreleasepool { 2314 ggml_metal_device_rsets_rm(buf->dev, buf->rset); 2315 2316 for (int i = 0; i < buf->n_buffers; i++) { 2317 [buf->buffers[i].metal release]; 2318 } 2319 2320 ggml_metal_buffer_rset_free(buf); 2321 } 2322 2323 if (buf->is_shared && buf->owned) { 2324 vm_deallocate((vm_map_t)mach_task_self(), (vm_address_t)buf->all_data, buf->all_size); 2325 } 2326 2327 free(buf); 2328 } 2329 2330 void * ggml_metal_buffer_get_base(ggml_metal_buffer_t buf) { 2331 return buf->all_data; 2332 } 2333 2334 bool ggml_metal_buffer_is_shared(ggml_metal_buffer_t buf) { 2335 return buf->is_shared; 2336 } 2337 2338 void ggml_metal_buffer_memset_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { 2339 if (buf->is_shared) { 2340 memset((char *) tensor->data + offset, value, size); 2341 return; 2342 } 2343 2344 @autoreleasepool { 2345 // dst 2346 struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf, tensor); 2347 bid_dst.offs += offset; 2348 2349 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2350 2351 { 2352 id encoder = [cmd_buf blitCommandEncoder]; 2353 2354 [encoder fillBuffer:bid_dst.metal 2355 range:NSMakeRange(bid_dst.offs, bid_dst.offs + size) 2356 value:value]; 2357 2358 [encoder endEncoding]; 2359 } 2360 2361 [cmd_buf commit]; 2362 [cmd_buf waitUntilCompleted]; 2363 } 2364 } 2365 2366 void ggml_metal_buffer_set_tensor(ggml_metal_buffer_t buf, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 2367 if (buf->is_shared) { 2368 memcpy((char *) tensor->data + offset, data, size); 2369 return; 2370 } 2371 2372 @autoreleasepool { 2373 // src 2374 void * data_ptr = (void *)(uintptr_t) data; // "const cast" the src data 2375 id buf_src = [buf->dev->mtl_device newBufferWithBytesNoCopy:data_ptr 2376 length:size 2377 options:MTLResourceStorageModeShared 2378 deallocator:nil]; 2379 2380 GGML_ASSERT(buf_src); 2381 2382 // dst 2383 struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf, tensor); 2384 bid_dst.offs += offset; 2385 2386 // note: for experimentation purposes, here we use a semaphore to wait for the copy to complete 2387 // this is alternative to waitUntilCompleted, which should be faster, but don't seem to make much difference 2388 dispatch_semaphore_t completion_semaphore = dispatch_semaphore_create(0); 2389 2390 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2391 2392 { 2393 id encoder = [cmd_buf blitCommandEncoder]; 2394 2395 [encoder copyFromBuffer:buf_src 2396 sourceOffset:0 2397 toBuffer:bid_dst.metal 2398 destinationOffset:bid_dst.offs 2399 size:size]; 2400 2401 [encoder endEncoding]; 2402 } 2403 2404 [cmd_buf addCompletedHandler:^(id cb) { 2405 // TODO: can check for errors here 2406 GGML_UNUSED(cb); 2407 2408 dispatch_semaphore_signal(completion_semaphore); 2409 }]; 2410 2411 [cmd_buf commit]; 2412 2413 dispatch_semaphore_wait(completion_semaphore, DISPATCH_TIME_FOREVER); 2414 dispatch_release(completion_semaphore); 2415 2416 //[cmd_buf waitUntilCompleted]; 2417 2418 [buf_src release]; 2419 } 2420 } 2421 2422 void ggml_metal_buffer_get_tensor(ggml_metal_buffer_t buf, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { 2423 if (buf->is_shared) { 2424 memcpy(data, (const char *) tensor->data + offset, size); 2425 return; 2426 } 2427 2428 @autoreleasepool { 2429 // src 2430 struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(buf, tensor); 2431 bid_src.offs += offset; 2432 2433 // dst 2434 id buf_dst = [buf->dev->mtl_device newBufferWithBytesNoCopy:data 2435 length:size 2436 options:MTLResourceStorageModeShared 2437 deallocator:nil]; 2438 2439 GGML_ASSERT(buf_dst); 2440 2441 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2442 2443 { 2444 id encoder = [cmd_buf blitCommandEncoder]; 2445 2446 [encoder copyFromBuffer:bid_src.metal 2447 sourceOffset:bid_src.offs 2448 toBuffer:buf_dst 2449 destinationOffset:0 2450 size:size]; 2451 2452 [encoder endEncoding]; 2453 } 2454 2455 [cmd_buf commit]; 2456 [cmd_buf waitUntilCompleted]; 2457 2458 [buf_dst release]; 2459 } 2460 } 2461 2462 static bool ggml_metal_buffer_data_span(const void * const * data, const size_t * sizes, size_t n_tensors, uintptr_t * min_data, uintptr_t * max_data) { 2463 bool found = false; 2464 2465 for (size_t i = 0; i < n_tensors; i++) { 2466 if (sizes[i] == 0) { 2467 continue; 2468 } 2469 2470 const uintptr_t start = (uintptr_t) data[i]; 2471 const uintptr_t end = start + sizes[i]; 2472 if (!found) { 2473 *min_data = start; 2474 *max_data = end; 2475 found = true; 2476 } else { 2477 if (start < *min_data) { 2478 *min_data = start; 2479 } 2480 if (end > *max_data) { 2481 *max_data = end; 2482 } 2483 } 2484 } 2485 2486 return found; 2487 } 2488 2489 void ggml_metal_buffer_set_tensor_n(ggml_metal_buffer_t buf, struct ggml_tensor * const * tensors, const void * const * data, 2490 const size_t * offsets, const size_t * sizes, size_t n_tensors) { 2491 if (buf->is_shared) { 2492 for (size_t i = 0; i < n_tensors; i++) { 2493 if (sizes[i] == 0) { 2494 continue; 2495 } 2496 memcpy((char *) tensors[i]->data + offsets[i], data[i], sizes[i]); 2497 } 2498 return; 2499 } 2500 2501 uintptr_t min_data = 0, max_data = 0; 2502 if (!ggml_metal_buffer_data_span(data, sizes, n_tensors, &min_data, &max_data)) { 2503 return; 2504 } 2505 2506 @autoreleasepool { 2507 void * data_ptr = (void *) min_data; 2508 id buf_src = [buf->dev->mtl_device newBufferWithBytesNoCopy:data_ptr 2509 length:max_data - min_data 2510 options:MTLResourceStorageModeShared 2511 deallocator:nil]; 2512 2513 GGML_ASSERT(buf_src); 2514 2515 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2516 2517 { 2518 id encoder = [cmd_buf blitCommandEncoder]; 2519 2520 for (size_t i = 0; i < n_tensors; i++) { 2521 if (sizes[i] == 0) { 2522 continue; 2523 } 2524 2525 ggml_backend_buffer_t tensor_buf_ggml = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 2526 ggml_metal_buffer_t tensor_buf = (ggml_metal_buffer_t) tensor_buf_ggml->context; 2527 struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(tensor_buf, tensors[i]); 2528 bid_dst.offs += offsets[i]; 2529 2530 [encoder copyFromBuffer:buf_src 2531 sourceOffset:(uintptr_t) data[i] - min_data 2532 toBuffer:bid_dst.metal 2533 destinationOffset:bid_dst.offs 2534 size:sizes[i]]; 2535 } 2536 2537 [encoder endEncoding]; 2538 } 2539 2540 [cmd_buf commit]; 2541 [cmd_buf waitUntilCompleted]; 2542 2543 [buf_src release]; 2544 } 2545 } 2546 2547 void ggml_metal_buffer_get_tensor_n(ggml_metal_buffer_t buf, const struct ggml_tensor * const * tensors, void * const * data, 2548 const size_t * offsets, const size_t * sizes, size_t n_tensors) { 2549 if (buf->is_shared) { 2550 for (size_t i = 0; i < n_tensors; i++) { 2551 if (sizes[i] == 0) { 2552 continue; 2553 } 2554 memcpy(data[i], (const char *) tensors[i]->data + offsets[i], sizes[i]); 2555 } 2556 return; 2557 } 2558 2559 uintptr_t min_data = 0, max_data = 0; 2560 if (!ggml_metal_buffer_data_span((const void * const *) data, sizes, n_tensors, &min_data, &max_data)) { 2561 return; 2562 } 2563 2564 @autoreleasepool { 2565 id buf_dst = [buf->dev->mtl_device newBufferWithBytesNoCopy:(void *) min_data 2566 length:max_data - min_data 2567 options:MTLResourceStorageModeShared 2568 deallocator:nil]; 2569 2570 GGML_ASSERT(buf_dst); 2571 2572 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2573 2574 { 2575 id encoder = [cmd_buf blitCommandEncoder]; 2576 2577 for (size_t i = 0; i < n_tensors; i++) { 2578 if (sizes[i] == 0) { 2579 continue; 2580 } 2581 2582 ggml_backend_buffer_t tensor_buf_ggml = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 2583 ggml_metal_buffer_t tensor_buf = (ggml_metal_buffer_t) tensor_buf_ggml->context; 2584 struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(tensor_buf, tensors[i]); 2585 bid_src.offs += offsets[i]; 2586 2587 [encoder copyFromBuffer:bid_src.metal 2588 sourceOffset:bid_src.offs 2589 toBuffer:buf_dst 2590 destinationOffset:(uintptr_t) data[i] - min_data 2591 size:sizes[i]]; 2592 } 2593 2594 [encoder endEncoding]; 2595 } 2596 2597 [cmd_buf commit]; 2598 [cmd_buf waitUntilCompleted]; 2599 2600 [buf_dst release]; 2601 } 2602 } 2603 2604 bool ggml_metal_buffer_cpy_tensor(ggml_metal_buffer_t buf_dst, const struct ggml_tensor * src, struct ggml_tensor * dst) { 2605 ggml_metal_buffer_t buf_src = (ggml_metal_buffer_t)src->buffer->context; 2606 2607 const size_t size = ggml_nbytes(src); 2608 2609 // if both buffers are shared, we can use memcpy directly 2610 if (buf_dst->is_shared && buf_src->is_shared) { 2611 memcpy(dst->data, src->data, size); 2612 return true; 2613 } 2614 2615 // for private buffers, we need to use Metal blit commands 2616 @autoreleasepool { 2617 struct ggml_metal_buffer_id bid_src = ggml_metal_buffer_get_id(buf_src, src); 2618 struct ggml_metal_buffer_id bid_dst = ggml_metal_buffer_get_id(buf_dst, dst); 2619 2620 if (bid_src.metal == nil || bid_dst.metal == nil) { 2621 return false; 2622 } 2623 2624 id cmd_buf = [buf_dst->dev->mtl_queue commandBufferWithUnretainedReferences]; 2625 2626 { 2627 id encoder = [cmd_buf blitCommandEncoder]; 2628 2629 [encoder copyFromBuffer:bid_src.metal 2630 sourceOffset:bid_src.offs 2631 toBuffer:bid_dst.metal 2632 destinationOffset:bid_dst.offs 2633 size:size]; 2634 2635 [encoder endEncoding]; 2636 } 2637 2638 [cmd_buf commit]; 2639 [cmd_buf waitUntilCompleted]; 2640 } 2641 2642 return true; 2643 } 2644 2645 bool ggml_metal_buffer_cpy_tensor_n(ggml_metal_buffer_t buf_dst, const struct ggml_tensor * const * srcs, struct ggml_tensor * const * dsts, size_t n_tensors) { 2646 if (n_tensors == 0) { 2647 return true; 2648 } 2649 2650 bool all_shared = true; 2651 for (size_t i = 0; i < n_tensors; ++i) { 2652 ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer; 2653 ggml_metal_buffer_t buf_src = (ggml_metal_buffer_t) src_buf->context; 2654 if (!buf_dst->is_shared || !buf_src->is_shared) { 2655 all_shared = false; 2656 break; 2657 } 2658 } 2659 2660 if (all_shared) { 2661 for (size_t i = 0; i < n_tensors; ++i) { 2662 memcpy(dsts[i]->data, srcs[i]->data, ggml_nbytes(srcs[i])); 2663 } 2664 return true; 2665 } 2666 2667 // for private buffers, we need to use Metal blit commands 2668 @autoreleasepool { 2669 struct ggml_metal_buffer_id * bid_srcs = malloc(n_tensors * sizeof(struct ggml_metal_buffer_id)); 2670 struct ggml_metal_buffer_id * bid_dsts = malloc(n_tensors * sizeof(struct ggml_metal_buffer_id)); 2671 2672 for (size_t i = 0; i < n_tensors; ++i) { 2673 ggml_backend_buffer_t src_buf = srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer; 2674 ggml_backend_buffer_t dst_buf = dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer; 2675 ggml_metal_buffer_t buf_src = (ggml_metal_buffer_t) src_buf->context; 2676 ggml_metal_buffer_t buf_dst_i = (ggml_metal_buffer_t) dst_buf->context; 2677 bid_srcs[i] = ggml_metal_buffer_get_id(buf_src, srcs[i]); 2678 bid_dsts[i] = ggml_metal_buffer_get_id(buf_dst_i, dsts[i]); 2679 2680 if (bid_srcs[i].metal == nil || bid_dsts[i].metal == nil) { 2681 free(bid_srcs); 2682 free(bid_dsts); 2683 return false; 2684 } 2685 } 2686 2687 id cmd_buf = [buf_dst->dev->mtl_queue commandBufferWithUnretainedReferences]; 2688 2689 { 2690 id encoder = [cmd_buf blitCommandEncoder]; 2691 2692 for (size_t i = 0; i < n_tensors; ++i) { 2693 [encoder copyFromBuffer:bid_srcs[i].metal 2694 sourceOffset:bid_srcs[i].offs 2695 toBuffer:bid_dsts[i].metal 2696 destinationOffset:bid_dsts[i].offs 2697 size:ggml_nbytes(srcs[i])]; 2698 } 2699 2700 [encoder endEncoding]; 2701 } 2702 2703 [cmd_buf commit]; 2704 [cmd_buf waitUntilCompleted]; 2705 2706 free(bid_srcs); 2707 free(bid_dsts); 2708 } 2709 2710 return true; 2711 } 2712 2713 void ggml_metal_buffer_clear(ggml_metal_buffer_t buf, uint8_t value) { 2714 if (buf->is_shared) { 2715 memset(buf->all_data, value, buf->all_size); 2716 return; 2717 } 2718 2719 @autoreleasepool { 2720 id cmd_buf = [buf->dev->mtl_queue commandBufferWithUnretainedReferences]; 2721 2722 { 2723 id encoder = [cmd_buf blitCommandEncoder]; 2724 2725 [encoder fillBuffer:buf->buffers[0].metal 2726 range:NSMakeRange(0, buf->buffers[0].size) 2727 value:value]; 2728 2729 [encoder endEncoding]; 2730 } 2731 2732 [cmd_buf commit]; 2733 [cmd_buf waitUntilCompleted]; 2734 } 2735 } 2736 2737 struct ggml_metal_buffer_id ggml_metal_buffer_get_id(ggml_metal_buffer_t buf, const struct ggml_tensor * t) { 2738 struct ggml_metal_buffer_id res = { nil, 0 }; 2739 2740 const int64_t tsize = ggml_nbytes(t); 2741 2742 // find the view that contains the tensor fully 2743 for (int i = 0; i < buf->n_buffers; ++i) { 2744 const int64_t ioffs = (int64_t) t->data - (int64_t) buf->buffers[i].data; 2745 2746 //GGML_LOG_INFO("ioffs = %10ld, tsize = %10ld, sum = %10ld, buf->buffers[%d].size = %10ld\n", ioffs, tsize, ioffs + tsize, i, buf->buffers[i].size); 2747 if (ioffs >= 0 && ioffs + tsize <= (int64_t) buf->buffers[i].size) { 2748 res.metal = buf->buffers[i].metal; 2749 res.offs = (size_t) ioffs; 2750 2751 //GGML_LOG_INFO("%s: tensor '%16s', offs = %8ld\n", __func__, t->name, *offs); 2752 2753 return res; 2754 } 2755 } 2756 2757 GGML_LOG_ERROR("%s: error: tensor '%s' buffer is nil\n", __func__, t->name); 2758 2759 return res; 2760 }