ggml-metal.m 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. #import "ggml-metal.h"
  2. #import "ggml.h"
  3. #import <Foundation/Foundation.h>
  4. #import <Metal/Metal.h>
  5. #undef MIN
  6. #undef MAX
  7. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  8. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  9. #ifdef GGML_METAL_NDEBUG
  10. #define GGML_METAL_LOG_INFO(...)
  11. #define GGML_METAL_LOG_WARN(...)
  12. #define GGML_METAL_LOG_ERROR(...)
  13. #else
  14. #define GGML_METAL_LOG_INFO(...) ggml_metal_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  15. #define GGML_METAL_LOG_WARN(...) ggml_metal_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  16. #define GGML_METAL_LOG_ERROR(...) ggml_metal_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  17. #endif
  18. #define UNUSED(x) (void)(x)
  19. #define GGML_MAX_CONCUR (2*GGML_MAX_NODES)
  20. struct ggml_metal_buffer {
  21. const char * name;
  22. void * data;
  23. size_t size;
  24. id<MTLBuffer> metal;
  25. };
  26. struct ggml_metal_context {
  27. int n_cb;
  28. id<MTLDevice> device;
  29. id<MTLCommandQueue> queue;
  30. id<MTLLibrary> library;
  31. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  32. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  33. dispatch_queue_t d_queue;
  34. int n_buffers;
  35. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  36. int concur_list[GGML_MAX_CONCUR];
  37. int concur_list_len;
  38. // custom kernels
  39. #define GGML_METAL_DECL_KERNEL(name) \
  40. id<MTLFunction> function_##name; \
  41. id<MTLComputePipelineState> pipeline_##name
  42. GGML_METAL_DECL_KERNEL(add);
  43. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  44. GGML_METAL_DECL_KERNEL(mul);
  45. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  46. GGML_METAL_DECL_KERNEL(scale);
  47. GGML_METAL_DECL_KERNEL(silu);
  48. GGML_METAL_DECL_KERNEL(relu);
  49. GGML_METAL_DECL_KERNEL(gelu);
  50. GGML_METAL_DECL_KERNEL(soft_max);
  51. GGML_METAL_DECL_KERNEL(soft_max_4);
  52. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  53. GGML_METAL_DECL_KERNEL(diag_mask_inf_8);
  54. GGML_METAL_DECL_KERNEL(get_rows_f32);
  55. GGML_METAL_DECL_KERNEL(get_rows_f16);
  56. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  57. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  58. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  59. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  60. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  61. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  62. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  63. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  64. GGML_METAL_DECL_KERNEL(rms_norm);
  65. GGML_METAL_DECL_KERNEL(norm);
  66. GGML_METAL_DECL_KERNEL(mul_mat_f32_f32);
  67. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32);
  68. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32_1row);
  69. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32_l4);
  70. GGML_METAL_DECL_KERNEL(mul_mat_q4_0_f32);
  71. GGML_METAL_DECL_KERNEL(mul_mat_q4_1_f32);
  72. GGML_METAL_DECL_KERNEL(mul_mat_q8_0_f32);
  73. GGML_METAL_DECL_KERNEL(mul_mat_q2_K_f32);
  74. GGML_METAL_DECL_KERNEL(mul_mat_q3_K_f32);
  75. GGML_METAL_DECL_KERNEL(mul_mat_q4_K_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mat_q5_K_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mat_q6_K_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mm_f32_f32);
  79. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  80. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  83. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  84. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  85. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  86. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  87. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  88. GGML_METAL_DECL_KERNEL(rope);
  89. GGML_METAL_DECL_KERNEL(alibi_f32);
  90. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  91. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  92. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  93. #undef GGML_METAL_DECL_KERNEL
  94. };
  95. // MSL code
  96. // TODO: move the contents here when ready
  97. // for now it is easier to work in a separate file
  98. static NSString * const msl_library_source = @"see metal.metal";
  99. // Here to assist with NSBundle Path Hack
  100. @interface GGMLMetalClass : NSObject
  101. @end
  102. @implementation GGMLMetalClass
  103. @end
  104. ggml_log_callback ggml_metal_log_callback = NULL;
  105. void * ggml_metal_log_user_data = NULL;
  106. void ggml_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  107. ggml_metal_log_callback = log_callback;
  108. ggml_metal_log_user_data = user_data;
  109. }
  110. static void ggml_metal_log(enum ggml_log_level level, const char* format, ...){
  111. if (ggml_metal_log_callback != NULL) {
  112. va_list args;
  113. va_start(args, format);
  114. char buffer[128];
  115. int len = vsnprintf(buffer, 128, format, args);
  116. if (len < 128) {
  117. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  118. } else {
  119. char* buffer2 = malloc(len+1);
  120. vsnprintf(buffer2, len+1, format, args);
  121. buffer2[len] = 0;
  122. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  123. free(buffer2);
  124. }
  125. va_end(args);
  126. }
  127. }
  128. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  129. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  130. id <MTLDevice> device;
  131. NSString * s;
  132. #if TARGET_OS_OSX
  133. // Show all the Metal device instances in the system
  134. NSArray * devices = MTLCopyAllDevices();
  135. for (device in devices) {
  136. s = [device name];
  137. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [s UTF8String]);
  138. }
  139. #endif
  140. // Pick and show default Metal device
  141. device = MTLCreateSystemDefaultDevice();
  142. s = [device name];
  143. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [s UTF8String]);
  144. // Configure context
  145. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  146. ctx->device = device;
  147. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  148. ctx->queue = [ctx->device newCommandQueue];
  149. ctx->n_buffers = 0;
  150. ctx->concur_list_len = 0;
  151. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  152. #ifdef GGML_SWIFT
  153. // load the default.metallib file
  154. {
  155. NSError * error = nil;
  156. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  157. NSString * llamaBundlePath = [bundle pathForResource:@"llama_llama" ofType:@"bundle"];
  158. NSBundle * llamaBundle = [NSBundle bundleWithPath:llamaBundlePath];
  159. NSString * libPath = [llamaBundle pathForResource:@"default" ofType:@"metallib"];
  160. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  161. // Load the metallib file into a Metal library
  162. ctx->library = [ctx->device newLibraryWithURL:libURL error:&error];
  163. if (error) {
  164. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  165. return NULL;
  166. }
  167. }
  168. #else
  169. UNUSED(msl_library_source);
  170. // read the source from "ggml-metal.metal" into a string and use newLibraryWithSource
  171. {
  172. NSError * error = nil;
  173. //NSString * path = [[NSBundle mainBundle] pathForResource:@"../../examples/metal/metal" ofType:@"metal"];
  174. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  175. NSString * path = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  176. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [path UTF8String]);
  177. NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
  178. if (error) {
  179. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  180. return NULL;
  181. }
  182. #ifdef GGML_QKK_64
  183. MTLCompileOptions* options = [MTLCompileOptions new];
  184. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  185. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  186. #else
  187. ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];
  188. #endif
  189. if (error) {
  190. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  191. return NULL;
  192. }
  193. }
  194. #endif
  195. // load kernels
  196. {
  197. NSError * error = nil;
  198. #define GGML_METAL_ADD_KERNEL(name) \
  199. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  200. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  201. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  202. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  203. (int) ctx->pipeline_##name.threadExecutionWidth); \
  204. if (error) { \
  205. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  206. return NULL; \
  207. }
  208. GGML_METAL_ADD_KERNEL(add);
  209. GGML_METAL_ADD_KERNEL(add_row);
  210. GGML_METAL_ADD_KERNEL(mul);
  211. GGML_METAL_ADD_KERNEL(mul_row);
  212. GGML_METAL_ADD_KERNEL(scale);
  213. GGML_METAL_ADD_KERNEL(silu);
  214. GGML_METAL_ADD_KERNEL(relu);
  215. GGML_METAL_ADD_KERNEL(gelu);
  216. GGML_METAL_ADD_KERNEL(soft_max);
  217. GGML_METAL_ADD_KERNEL(soft_max_4);
  218. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  219. GGML_METAL_ADD_KERNEL(diag_mask_inf_8);
  220. GGML_METAL_ADD_KERNEL(get_rows_f32);
  221. GGML_METAL_ADD_KERNEL(get_rows_f16);
  222. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  223. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  224. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  225. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  226. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  227. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  228. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  229. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  230. GGML_METAL_ADD_KERNEL(rms_norm);
  231. GGML_METAL_ADD_KERNEL(norm);
  232. GGML_METAL_ADD_KERNEL(mul_mat_f32_f32);
  233. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32);
  234. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32_1row);
  235. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32_l4);
  236. GGML_METAL_ADD_KERNEL(mul_mat_q4_0_f32);
  237. GGML_METAL_ADD_KERNEL(mul_mat_q4_1_f32);
  238. GGML_METAL_ADD_KERNEL(mul_mat_q8_0_f32);
  239. GGML_METAL_ADD_KERNEL(mul_mat_q2_K_f32);
  240. GGML_METAL_ADD_KERNEL(mul_mat_q3_K_f32);
  241. GGML_METAL_ADD_KERNEL(mul_mat_q4_K_f32);
  242. GGML_METAL_ADD_KERNEL(mul_mat_q5_K_f32);
  243. GGML_METAL_ADD_KERNEL(mul_mat_q6_K_f32);
  244. GGML_METAL_ADD_KERNEL(mul_mm_f32_f32);
  245. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  246. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  247. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  248. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  249. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  250. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  251. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  252. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  253. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  254. GGML_METAL_ADD_KERNEL(rope);
  255. GGML_METAL_ADD_KERNEL(alibi_f32);
  256. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  257. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  258. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  259. #undef GGML_METAL_ADD_KERNEL
  260. }
  261. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  262. #if TARGET_OS_OSX
  263. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  264. if (ctx->device.maxTransferRate != 0) {
  265. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  266. } else {
  267. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  268. }
  269. #endif
  270. return ctx;
  271. }
  272. void ggml_metal_free(struct ggml_metal_context * ctx) {
  273. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  274. #define GGML_METAL_DEL_KERNEL(name) \
  275. [ctx->function_##name release]; \
  276. [ctx->pipeline_##name release];
  277. GGML_METAL_DEL_KERNEL(add);
  278. GGML_METAL_DEL_KERNEL(add_row);
  279. GGML_METAL_DEL_KERNEL(mul);
  280. GGML_METAL_DEL_KERNEL(mul_row);
  281. GGML_METAL_DEL_KERNEL(scale);
  282. GGML_METAL_DEL_KERNEL(silu);
  283. GGML_METAL_DEL_KERNEL(relu);
  284. GGML_METAL_DEL_KERNEL(gelu);
  285. GGML_METAL_DEL_KERNEL(soft_max);
  286. GGML_METAL_DEL_KERNEL(soft_max_4);
  287. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  288. GGML_METAL_DEL_KERNEL(diag_mask_inf_8);
  289. GGML_METAL_DEL_KERNEL(get_rows_f32);
  290. GGML_METAL_DEL_KERNEL(get_rows_f16);
  291. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  292. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  293. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  294. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  295. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  296. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  297. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  298. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  299. GGML_METAL_DEL_KERNEL(rms_norm);
  300. GGML_METAL_DEL_KERNEL(norm);
  301. GGML_METAL_DEL_KERNEL(mul_mat_f32_f32);
  302. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32);
  303. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32_1row);
  304. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32_l4);
  305. GGML_METAL_DEL_KERNEL(mul_mat_q4_0_f32);
  306. GGML_METAL_DEL_KERNEL(mul_mat_q4_1_f32);
  307. GGML_METAL_DEL_KERNEL(mul_mat_q8_0_f32);
  308. GGML_METAL_DEL_KERNEL(mul_mat_q2_K_f32);
  309. GGML_METAL_DEL_KERNEL(mul_mat_q3_K_f32);
  310. GGML_METAL_DEL_KERNEL(mul_mat_q4_K_f32);
  311. GGML_METAL_DEL_KERNEL(mul_mat_q5_K_f32);
  312. GGML_METAL_DEL_KERNEL(mul_mat_q6_K_f32);
  313. GGML_METAL_DEL_KERNEL(mul_mm_f32_f32);
  314. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  315. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  316. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  317. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  318. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  319. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  320. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  321. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  322. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  323. GGML_METAL_DEL_KERNEL(rope);
  324. GGML_METAL_DEL_KERNEL(alibi_f32);
  325. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  326. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  327. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  328. #undef GGML_METAL_DEL_KERNEL
  329. for (int i = 0; i < ctx->n_buffers; ++i) {
  330. [ctx->buffers[i].metal release];
  331. }
  332. [ctx->library release];
  333. [ctx->queue release];
  334. [ctx->device release];
  335. dispatch_release(ctx->d_queue);
  336. free(ctx);
  337. }
  338. void * ggml_metal_host_malloc(size_t n) {
  339. void * data = NULL;
  340. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  341. if (result != 0) {
  342. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  343. return NULL;
  344. }
  345. return data;
  346. }
  347. void ggml_metal_host_free(void * data) {
  348. free(data);
  349. }
  350. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  351. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  352. }
  353. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  354. return ctx->concur_list_len;
  355. }
  356. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  357. return ctx->concur_list;
  358. }
  359. // finds the Metal buffer that contains the tensor data on the GPU device
  360. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  361. // Metal buffer based on the host memory pointer
  362. //
  363. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  364. //GGML_METAL_LOG_INFO("%s: data tensor '%16s', offs_data = %8ld, offs_eval = %8ld, offs_cach = %8ld\n", __func__, t->name, offs_data, offs_eval, offs_cach);
  365. const int64_t tsize = ggml_nbytes(t);
  366. // find the view that contains the tensor fully
  367. for (int i = 0; i < ctx->n_buffers; ++i) {
  368. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  369. //metal_printf("ioffs = %10ld, tsize = %10ld, sum = %10ld, ctx->buffers[%d].size = %10ld, name = %s\n", ioffs, tsize, ioffs + tsize, i, ctx->buffers[i].size, ctx->buffers[i].name);
  370. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  371. *offs = (size_t) ioffs;
  372. //GGML_METAL_LOG_INFO("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  373. return ctx->buffers[i].metal;
  374. }
  375. }
  376. GGML_METAL_LOG_ERROR("%s: error: buffer is nil\n", __func__);
  377. return nil;
  378. }
  379. bool ggml_metal_add_buffer(
  380. struct ggml_metal_context * ctx,
  381. const char * name,
  382. void * data,
  383. size_t size,
  384. size_t max_size) {
  385. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  386. GGML_METAL_LOG_ERROR("%s: error: too many buffers\n", __func__);
  387. return false;
  388. }
  389. if (data) {
  390. // verify that the buffer does not overlap with any of the existing buffers
  391. for (int i = 0; i < ctx->n_buffers; ++i) {
  392. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  393. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  394. GGML_METAL_LOG_ERROR("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  395. return false;
  396. }
  397. }
  398. const size_t size_page = sysconf(_SC_PAGESIZE);
  399. size_t size_aligned = size;
  400. if ((size_aligned % size_page) != 0) {
  401. size_aligned += (size_page - (size_aligned % size_page));
  402. }
  403. // the buffer fits into the max buffer size allowed by the device
  404. if (size_aligned <= ctx->device.maxBufferLength) {
  405. ctx->buffers[ctx->n_buffers].name = name;
  406. ctx->buffers[ctx->n_buffers].data = data;
  407. ctx->buffers[ctx->n_buffers].size = size;
  408. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  409. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  410. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  411. return false;
  412. }
  413. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB", __func__, name, size_aligned / 1024.0 / 1024.0);
  414. ++ctx->n_buffers;
  415. } else {
  416. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  417. // one of the views
  418. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  419. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  420. const size_t size_view = ctx->device.maxBufferLength;
  421. for (size_t i = 0; i < size; i += size_step) {
  422. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  423. ctx->buffers[ctx->n_buffers].name = name;
  424. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  425. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  426. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  427. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  428. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  429. return false;
  430. }
  431. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  432. if (i + size_step < size) {
  433. GGML_METAL_LOG_INFO("\n");
  434. }
  435. ++ctx->n_buffers;
  436. }
  437. }
  438. #if TARGET_OS_OSX
  439. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  440. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  441. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  442. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  443. GGML_METAL_LOG_WARN(", warning: current allocated size is greater than the recommended max working set size\n", __func__);
  444. } else {
  445. GGML_METAL_LOG_INFO("\n");
  446. }
  447. #else
  448. GGML_METAL_LOG_INFO(", (%8.2f)\n", ctx->device.currentAllocatedSize / 1024.0 / 1024.0);
  449. #endif
  450. }
  451. return true;
  452. }
  453. void ggml_metal_set_tensor(
  454. struct ggml_metal_context * ctx,
  455. struct ggml_tensor * t) {
  456. size_t offs;
  457. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  458. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  459. }
  460. void ggml_metal_get_tensor(
  461. struct ggml_metal_context * ctx,
  462. struct ggml_tensor * t) {
  463. size_t offs;
  464. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  465. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  466. }
  467. void ggml_metal_graph_find_concurrency(
  468. struct ggml_metal_context * ctx,
  469. struct ggml_cgraph * gf, bool check_mem) {
  470. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  471. int nodes_unused[GGML_MAX_CONCUR];
  472. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  473. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  474. ctx->concur_list_len = 0;
  475. int n_left = gf->n_nodes;
  476. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  477. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  478. while (n_left > 0) {
  479. // number of nodes at a layer (that can be issued concurrently)
  480. int concurrency = 0;
  481. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  482. if (nodes_unused[i]) {
  483. // if the requirements for gf->nodes[i] are satisfied
  484. int exe_flag = 1;
  485. // scan all srcs
  486. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  487. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  488. if (src_cur) {
  489. // if is leaf nodes it's satisfied.
  490. // TODO: ggml_is_leaf()
  491. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  492. continue;
  493. }
  494. // otherwise this src should be the output from previous nodes.
  495. int is_found = 0;
  496. // scan 2*search_depth back because we inserted barrier.
  497. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  498. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  499. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  500. is_found = 1;
  501. break;
  502. }
  503. }
  504. if (is_found == 0) {
  505. exe_flag = 0;
  506. break;
  507. }
  508. }
  509. }
  510. if (exe_flag && check_mem) {
  511. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  512. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  513. int64_t data_start = (int64_t) gf->nodes[i]->data;
  514. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  515. for (int j = n_start; j < i; j++) {
  516. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  517. && gf->nodes[j]->op != GGML_OP_VIEW \
  518. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  519. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  520. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  521. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  522. continue;
  523. }
  524. exe_flag = 0;
  525. }
  526. }
  527. }
  528. if (exe_flag) {
  529. ctx->concur_list[level_pos + concurrency] = i;
  530. nodes_unused[i] = 0;
  531. concurrency++;
  532. ctx->concur_list_len++;
  533. }
  534. }
  535. }
  536. n_left -= concurrency;
  537. // adding a barrier different layer
  538. ctx->concur_list[level_pos + concurrency] = -1;
  539. ctx->concur_list_len++;
  540. // jump all sorted nodes at nodes_bak
  541. while (!nodes_unused[n_start]) {
  542. n_start++;
  543. }
  544. level_pos += concurrency + 1;
  545. }
  546. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  547. GGML_METAL_LOG_WARN("%s: too many elements for metal ctx->concur_list!\n", __func__);
  548. }
  549. }
  550. void ggml_metal_graph_compute(
  551. struct ggml_metal_context * ctx,
  552. struct ggml_cgraph * gf) {
  553. @autoreleasepool {
  554. // if there is ctx->concur_list, dispatch concurrently
  555. // else fallback to serial dispatch
  556. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  557. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  558. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  559. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  560. // create multiple command buffers and enqueue them
  561. // then, we encode the graph into the command buffers in parallel
  562. const int n_cb = ctx->n_cb;
  563. for (int i = 0; i < n_cb; ++i) {
  564. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  565. // enqueue the command buffers in order to specify their execution order
  566. [ctx->command_buffers[i] enqueue];
  567. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  568. }
  569. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  570. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  571. dispatch_async(ctx->d_queue, ^{
  572. size_t offs_src0 = 0;
  573. size_t offs_src1 = 0;
  574. size_t offs_dst = 0;
  575. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  576. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  577. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  578. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  579. for (int ind = node_start; ind < node_end; ++ind) {
  580. const int i = has_concur ? ctx->concur_list[ind] : ind;
  581. if (i == -1) {
  582. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  583. continue;
  584. }
  585. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  586. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  587. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  588. struct ggml_tensor * dst = gf->nodes[i];
  589. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  590. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  591. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  592. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  593. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  594. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  595. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  596. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  597. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  598. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  599. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  600. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  601. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  602. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  603. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  604. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  605. const int64_t ne0 = dst ? dst->ne[0] : 0;
  606. const int64_t ne1 = dst ? dst->ne[1] : 0;
  607. const int64_t ne2 = dst ? dst->ne[2] : 0;
  608. const int64_t ne3 = dst ? dst->ne[3] : 0;
  609. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  610. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  611. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  612. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  613. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  614. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  615. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  616. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  617. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  618. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  619. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  620. //if (src0) {
  621. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  622. // ggml_is_contiguous(src0), src0->name);
  623. //}
  624. //if (src1) {
  625. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  626. // ggml_is_contiguous(src1), src1->name);
  627. //}
  628. //if (dst) {
  629. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  630. // dst->name);
  631. //}
  632. switch (dst->op) {
  633. case GGML_OP_NONE:
  634. case GGML_OP_RESHAPE:
  635. case GGML_OP_VIEW:
  636. case GGML_OP_TRANSPOSE:
  637. case GGML_OP_PERMUTE:
  638. {
  639. // noop
  640. } break;
  641. case GGML_OP_ADD:
  642. {
  643. GGML_ASSERT(ggml_is_contiguous(src0));
  644. GGML_ASSERT(ggml_is_contiguous(src1));
  645. // utilize float4
  646. GGML_ASSERT(ne00 % 4 == 0);
  647. const int64_t nb = ne00/4;
  648. if (ggml_nelements(src1) == ne10) {
  649. // src1 is a row
  650. GGML_ASSERT(ne11 == 1);
  651. [encoder setComputePipelineState:ctx->pipeline_add_row];
  652. } else {
  653. [encoder setComputePipelineState:ctx->pipeline_add];
  654. }
  655. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  656. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  657. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  658. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  659. const int64_t n = ggml_nelements(dst)/4;
  660. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  661. } break;
  662. case GGML_OP_MUL:
  663. {
  664. GGML_ASSERT(ggml_is_contiguous(src0));
  665. GGML_ASSERT(ggml_is_contiguous(src1));
  666. // utilize float4
  667. GGML_ASSERT(ne00 % 4 == 0);
  668. const int64_t nb = ne00/4;
  669. if (ggml_nelements(src1) == ne10) {
  670. // src1 is a row
  671. GGML_ASSERT(ne11 == 1);
  672. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  673. } else {
  674. [encoder setComputePipelineState:ctx->pipeline_mul];
  675. }
  676. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  677. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  678. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  679. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  680. const int64_t n = ggml_nelements(dst)/4;
  681. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  682. } break;
  683. case GGML_OP_SCALE:
  684. {
  685. GGML_ASSERT(ggml_is_contiguous(src0));
  686. const float scale = *(const float *) src1->data;
  687. [encoder setComputePipelineState:ctx->pipeline_scale];
  688. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  689. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  690. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  691. const int64_t n = ggml_nelements(dst)/4;
  692. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  693. } break;
  694. case GGML_OP_UNARY:
  695. switch (ggml_get_unary_op(gf->nodes[i])) {
  696. case GGML_UNARY_OP_SILU:
  697. {
  698. [encoder setComputePipelineState:ctx->pipeline_silu];
  699. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  700. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  701. const int64_t n = ggml_nelements(dst)/4;
  702. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  703. } break;
  704. case GGML_UNARY_OP_RELU:
  705. {
  706. [encoder setComputePipelineState:ctx->pipeline_relu];
  707. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  708. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  709. const int64_t n = ggml_nelements(dst);
  710. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  711. } break;
  712. case GGML_UNARY_OP_GELU:
  713. {
  714. [encoder setComputePipelineState:ctx->pipeline_gelu];
  715. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  716. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  717. const int64_t n = ggml_nelements(dst)/4;
  718. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  719. } break;
  720. default:
  721. {
  722. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  723. GGML_ASSERT(false);
  724. }
  725. } break;
  726. case GGML_OP_SOFT_MAX:
  727. {
  728. const int nth = 32;
  729. if (ne00%4 == 0) {
  730. [encoder setComputePipelineState:ctx->pipeline_soft_max_4];
  731. } else {
  732. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  733. }
  734. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  735. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  736. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  737. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  738. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  739. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  740. } break;
  741. case GGML_OP_DIAG_MASK_INF:
  742. {
  743. const int n_past = ((int32_t *)(dst->op_params))[0];
  744. if (ne00%8 == 0) {
  745. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf_8];
  746. } else {
  747. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  748. }
  749. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  750. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  751. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  752. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  753. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  754. if (ne00%8 == 0) {
  755. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  756. }
  757. else {
  758. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  759. }
  760. } break;
  761. case GGML_OP_MUL_MAT:
  762. {
  763. // TODO: needs to be updated after PR: https://github.com/ggerganov/ggml/pull/224
  764. GGML_ASSERT(ne00 == ne10);
  765. // GGML_ASSERT(ne02 == ne12); // Should be checked on individual data types until broadcast is implemented everywhere
  766. uint gqa = ne12/ne02;
  767. GGML_ASSERT(ne03 == ne13);
  768. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  769. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  770. if (!ggml_is_transposed(src0) &&
  771. !ggml_is_transposed(src1) &&
  772. src1t == GGML_TYPE_F32 &&
  773. [ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  774. ne00%32 == 0 &&
  775. ne11 > 1) {
  776. switch (src0->type) {
  777. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f32_f32]; break;
  778. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  779. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  780. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  781. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  782. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  783. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  784. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  785. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  786. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  787. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  788. }
  789. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  790. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  791. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  792. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  793. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  794. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  795. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  796. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  797. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  798. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  799. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  800. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  801. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  802. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:13];
  803. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  804. [encoder dispatchThreadgroups:MTLSizeMake( (ne11+31)/32, (ne01+63) / 64, ne12) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  805. } else {
  806. int nth0 = 32;
  807. int nth1 = 1;
  808. int nrows = 1;
  809. // use custom matrix x vector kernel
  810. switch (src0t) {
  811. case GGML_TYPE_F32:
  812. {
  813. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f32_f32];
  814. nrows = 4;
  815. } break;
  816. case GGML_TYPE_F16:
  817. {
  818. nth0 = 32;
  819. nth1 = 1;
  820. if (ne11 * ne12 < 4) {
  821. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32_1row];
  822. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  823. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32_l4];
  824. nrows = ne11;
  825. } else {
  826. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32];
  827. nrows = 4;
  828. }
  829. } break;
  830. case GGML_TYPE_Q4_0:
  831. {
  832. GGML_ASSERT(ne02 == 1);
  833. GGML_ASSERT(ne12 == 1);
  834. nth0 = 8;
  835. nth1 = 8;
  836. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_0_f32];
  837. } break;
  838. case GGML_TYPE_Q4_1:
  839. {
  840. GGML_ASSERT(ne02 == 1);
  841. GGML_ASSERT(ne12 == 1);
  842. nth0 = 8;
  843. nth1 = 8;
  844. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_1_f32];
  845. } break;
  846. case GGML_TYPE_Q8_0:
  847. {
  848. GGML_ASSERT(ne02 == 1);
  849. GGML_ASSERT(ne12 == 1);
  850. nth0 = 8;
  851. nth1 = 8;
  852. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q8_0_f32];
  853. } break;
  854. case GGML_TYPE_Q2_K:
  855. {
  856. GGML_ASSERT(ne02 == 1);
  857. GGML_ASSERT(ne12 == 1);
  858. nth0 = 2;
  859. nth1 = 32;
  860. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q2_K_f32];
  861. } break;
  862. case GGML_TYPE_Q3_K:
  863. {
  864. GGML_ASSERT(ne02 == 1);
  865. GGML_ASSERT(ne12 == 1);
  866. nth0 = 2;
  867. nth1 = 32;
  868. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q3_K_f32];
  869. } break;
  870. case GGML_TYPE_Q4_K:
  871. {
  872. GGML_ASSERT(ne02 == 1);
  873. GGML_ASSERT(ne12 == 1);
  874. nth0 = 4; //1;
  875. nth1 = 8; //32;
  876. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_K_f32];
  877. } break;
  878. case GGML_TYPE_Q5_K:
  879. {
  880. GGML_ASSERT(ne02 == 1);
  881. GGML_ASSERT(ne12 == 1);
  882. nth0 = 2;
  883. nth1 = 32;
  884. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q5_K_f32];
  885. } break;
  886. case GGML_TYPE_Q6_K:
  887. {
  888. GGML_ASSERT(ne02 == 1);
  889. GGML_ASSERT(ne12 == 1);
  890. nth0 = 2;
  891. nth1 = 32;
  892. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q6_K_f32];
  893. } break;
  894. default:
  895. {
  896. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  897. GGML_ASSERT(false && "not implemented");
  898. }
  899. };
  900. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  901. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  902. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  903. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  904. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  905. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  906. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  907. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  908. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  909. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  910. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  911. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  912. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  913. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  914. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  915. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  916. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  917. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:17];
  918. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 || src0t == GGML_TYPE_Q8_0 ||
  919. src0t == GGML_TYPE_Q2_K) {// || src0t == GGML_TYPE_Q4_K) {
  920. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  921. }
  922. else if (src0t == GGML_TYPE_Q4_K) {
  923. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  924. }
  925. else if (src0t == GGML_TYPE_Q3_K) {
  926. #ifdef GGML_QKK_64
  927. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  928. #else
  929. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  930. #endif
  931. }
  932. else if (src0t == GGML_TYPE_Q5_K) {
  933. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  934. }
  935. else if (src0t == GGML_TYPE_Q6_K) {
  936. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  937. } else {
  938. int64_t ny = (ne11 + nrows - 1)/nrows;
  939. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  940. }
  941. }
  942. } break;
  943. case GGML_OP_GET_ROWS:
  944. {
  945. switch (src0->type) {
  946. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_get_rows_f32]; break;
  947. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  948. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  949. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  950. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  951. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  952. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  953. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  954. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  955. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  956. default: GGML_ASSERT(false && "not implemented");
  957. }
  958. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  959. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  960. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  961. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  962. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  963. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:5];
  964. const int64_t n = ggml_nelements(src1);
  965. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  966. } break;
  967. case GGML_OP_RMS_NORM:
  968. {
  969. float eps;
  970. memcpy(&eps, dst->op_params, sizeof(float));
  971. const int nth = 512;
  972. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  973. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  974. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  975. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  976. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  977. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  978. [encoder setThreadgroupMemoryLength:nth/32*sizeof(float) atIndex:0];
  979. const int64_t nrows = ggml_nrows(src0);
  980. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  981. } break;
  982. case GGML_OP_NORM:
  983. {
  984. float eps;
  985. memcpy(&eps, dst->op_params, sizeof(float));
  986. const int nth = 256;
  987. [encoder setComputePipelineState:ctx->pipeline_norm];
  988. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  989. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  990. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  991. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  992. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  993. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  994. const int64_t nrows = ggml_nrows(src0);
  995. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  996. } break;
  997. case GGML_OP_ALIBI:
  998. {
  999. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1000. const int n_past = ((int32_t *) dst->op_params)[0]; UNUSED(n_past);
  1001. const int n_head = ((int32_t *) dst->op_params)[1];
  1002. float max_bias;
  1003. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1004. if (__builtin_popcount(n_head) != 1) {
  1005. GGML_ASSERT(false && "only power-of-two n_head implemented");
  1006. }
  1007. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1008. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1009. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  1010. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1011. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1012. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1013. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1014. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1015. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1016. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1017. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1018. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1019. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1020. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1021. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1022. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1023. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1024. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1025. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1026. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1027. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1028. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1029. const int nth = 32;
  1030. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1031. } break;
  1032. case GGML_OP_ROPE:
  1033. {
  1034. const int n_past = ((int32_t *) dst->op_params)[0];
  1035. const int n_dims = ((int32_t *) dst->op_params)[1];
  1036. const int mode = ((int32_t *) dst->op_params)[2];
  1037. float freq_base;
  1038. float freq_scale;
  1039. memcpy(&freq_base, (int32_t *) dst->op_params + 4, sizeof(float));
  1040. memcpy(&freq_scale, (int32_t *) dst->op_params + 5, sizeof(float));
  1041. [encoder setComputePipelineState:ctx->pipeline_rope];
  1042. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1043. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1044. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1045. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1046. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1047. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1048. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1049. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1050. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1051. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1052. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1053. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1054. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1055. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1056. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1057. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1058. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1059. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1060. [encoder setBytes:&n_past length:sizeof( int) atIndex:18];
  1061. [encoder setBytes:&n_dims length:sizeof( int) atIndex:19];
  1062. [encoder setBytes:&mode length:sizeof( int) atIndex:20];
  1063. [encoder setBytes:&freq_base length:sizeof(float) atIndex:21];
  1064. [encoder setBytes:&freq_scale length:sizeof(float) atIndex:22];
  1065. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
  1066. } break;
  1067. case GGML_OP_DUP:
  1068. case GGML_OP_CPY:
  1069. case GGML_OP_CONT:
  1070. {
  1071. const int nth = 32;
  1072. switch (src0t) {
  1073. case GGML_TYPE_F32:
  1074. {
  1075. switch (dstt) {
  1076. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  1077. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  1078. default: GGML_ASSERT(false && "not implemented");
  1079. };
  1080. } break;
  1081. case GGML_TYPE_F16:
  1082. {
  1083. switch (dstt) {
  1084. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  1085. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  1086. default: GGML_ASSERT(false && "not implemented");
  1087. };
  1088. } break;
  1089. default: GGML_ASSERT(false && "not implemented");
  1090. }
  1091. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1092. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1093. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1094. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1095. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1096. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1097. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1098. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1099. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1100. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1101. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1102. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1103. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1104. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1105. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1106. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1107. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1108. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1109. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1110. } break;
  1111. default:
  1112. {
  1113. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1114. GGML_ASSERT(false);
  1115. }
  1116. }
  1117. }
  1118. if (encoder != nil) {
  1119. [encoder endEncoding];
  1120. encoder = nil;
  1121. }
  1122. [command_buffer commit];
  1123. });
  1124. }
  1125. // wait for all threads to finish
  1126. dispatch_barrier_sync(ctx->d_queue, ^{});
  1127. // check status of command buffers
  1128. // needed to detect if the device ran out-of-memory for example (#1881)
  1129. for (int i = 0; i < n_cb; i++) {
  1130. [ctx->command_buffers[i] waitUntilCompleted];
  1131. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  1132. if (status != MTLCommandBufferStatusCompleted) {
  1133. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  1134. GGML_ASSERT(false);
  1135. }
  1136. }
  1137. }
  1138. }