ggml-metal.m 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  1. #import "ggml-metal.h"
  2. #import "ggml-backend-impl.h"
  3. #import "ggml.h"
  4. #import <Foundation/Foundation.h>
  5. #import <Metal/Metal.h>
  6. #undef MIN
  7. #undef MAX
  8. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  9. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  10. #ifdef GGML_METAL_NDEBUG
  11. #define GGML_METAL_LOG_INFO(...)
  12. #define GGML_METAL_LOG_WARN(...)
  13. #define GGML_METAL_LOG_ERROR(...)
  14. #else
  15. #define GGML_METAL_LOG_INFO(...) ggml_metal_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  16. #define GGML_METAL_LOG_WARN(...) ggml_metal_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  17. #define GGML_METAL_LOG_ERROR(...) ggml_metal_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  18. #endif
  19. #define UNUSED(x) (void)(x)
  20. #define GGML_MAX_CONCUR (2*GGML_DEFAULT_GRAPH_SIZE)
  21. struct ggml_metal_buffer {
  22. const char * name;
  23. void * data;
  24. size_t size;
  25. id<MTLBuffer> metal;
  26. };
  27. struct ggml_metal_context {
  28. int n_cb;
  29. id<MTLDevice> device;
  30. id<MTLCommandQueue> queue;
  31. id<MTLLibrary> library;
  32. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  33. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  34. dispatch_queue_t d_queue;
  35. int n_buffers;
  36. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  37. int concur_list[GGML_MAX_CONCUR];
  38. int concur_list_len;
  39. // custom kernels
  40. #define GGML_METAL_DECL_KERNEL(name) \
  41. id<MTLFunction> function_##name; \
  42. id<MTLComputePipelineState> pipeline_##name
  43. GGML_METAL_DECL_KERNEL(add);
  44. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  45. GGML_METAL_DECL_KERNEL(mul);
  46. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  47. GGML_METAL_DECL_KERNEL(scale);
  48. GGML_METAL_DECL_KERNEL(scale_4);
  49. GGML_METAL_DECL_KERNEL(silu);
  50. GGML_METAL_DECL_KERNEL(relu);
  51. GGML_METAL_DECL_KERNEL(gelu);
  52. GGML_METAL_DECL_KERNEL(soft_max);
  53. GGML_METAL_DECL_KERNEL(soft_max_4);
  54. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  55. GGML_METAL_DECL_KERNEL(diag_mask_inf_8);
  56. GGML_METAL_DECL_KERNEL(get_rows_f32);
  57. GGML_METAL_DECL_KERNEL(get_rows_f16);
  58. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  59. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  60. GGML_METAL_DECL_KERNEL(get_rows_q5_0);
  61. GGML_METAL_DECL_KERNEL(get_rows_q5_1);
  62. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  63. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  64. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  65. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  66. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  67. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  68. GGML_METAL_DECL_KERNEL(rms_norm);
  69. GGML_METAL_DECL_KERNEL(norm);
  70. GGML_METAL_DECL_KERNEL(mul_mv_f32_f32);
  71. GGML_METAL_DECL_KERNEL(mul_mv_f16_f16);
  72. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32);
  73. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_1row);
  74. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_l4);
  75. GGML_METAL_DECL_KERNEL(mul_mv_q4_0_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mv_q4_1_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mv_q5_0_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mv_q5_1_f32);
  79. GGML_METAL_DECL_KERNEL(mul_mv_q8_0_f32);
  80. GGML_METAL_DECL_KERNEL(mul_mv_q2_K_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mv_q3_K_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mv_q4_K_f32);
  83. GGML_METAL_DECL_KERNEL(mul_mv_q5_K_f32);
  84. GGML_METAL_DECL_KERNEL(mul_mv_q6_K_f32);
  85. GGML_METAL_DECL_KERNEL(mul_mm_f32_f32);
  86. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  87. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  88. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  89. GGML_METAL_DECL_KERNEL(mul_mm_q5_0_f32);
  90. GGML_METAL_DECL_KERNEL(mul_mm_q5_1_f32);
  91. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  92. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  93. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  94. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  95. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  96. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  97. GGML_METAL_DECL_KERNEL(rope_f32);
  98. GGML_METAL_DECL_KERNEL(rope_f16);
  99. GGML_METAL_DECL_KERNEL(alibi_f32);
  100. GGML_METAL_DECL_KERNEL(im2col_f16);
  101. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  102. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  103. GGML_METAL_DECL_KERNEL(cpy_f32_q8_0);
  104. GGML_METAL_DECL_KERNEL(cpy_f32_q4_0);
  105. GGML_METAL_DECL_KERNEL(cpy_f32_q4_1);
  106. //GGML_METAL_DECL_KERNEL(cpy_f32_q5_0);
  107. //GGML_METAL_DECL_KERNEL(cpy_f32_q5_1);
  108. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  109. GGML_METAL_DECL_KERNEL(concat);
  110. GGML_METAL_DECL_KERNEL(sqr);
  111. #undef GGML_METAL_DECL_KERNEL
  112. };
  113. // MSL code
  114. // TODO: move the contents here when ready
  115. // for now it is easier to work in a separate file
  116. //static NSString * const msl_library_source = @"see metal.metal";
  117. // Here to assist with NSBundle Path Hack
  118. @interface GGMLMetalClass : NSObject
  119. @end
  120. @implementation GGMLMetalClass
  121. @end
  122. ggml_log_callback ggml_metal_log_callback = NULL;
  123. void * ggml_metal_log_user_data = NULL;
  124. void ggml_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  125. ggml_metal_log_callback = log_callback;
  126. ggml_metal_log_user_data = user_data;
  127. }
  128. GGML_ATTRIBUTE_FORMAT(2, 3)
  129. static void ggml_metal_log(enum ggml_log_level level, const char * format, ...){
  130. if (ggml_metal_log_callback != NULL) {
  131. va_list args;
  132. va_start(args, format);
  133. char buffer[128];
  134. int len = vsnprintf(buffer, 128, format, args);
  135. if (len < 128) {
  136. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  137. } else {
  138. char* buffer2 = malloc(len+1);
  139. vsnprintf(buffer2, len+1, format, args);
  140. buffer2[len] = 0;
  141. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  142. free(buffer2);
  143. }
  144. va_end(args);
  145. }
  146. }
  147. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  148. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  149. id <MTLDevice> device;
  150. NSString * s;
  151. #if TARGET_OS_OSX
  152. // Show all the Metal device instances in the system
  153. NSArray * devices = MTLCopyAllDevices();
  154. for (device in devices) {
  155. s = [device name];
  156. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [s UTF8String]);
  157. }
  158. #endif
  159. // Pick and show default Metal device
  160. device = MTLCreateSystemDefaultDevice();
  161. s = [device name];
  162. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [s UTF8String]);
  163. // Configure context
  164. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  165. ctx->device = device;
  166. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  167. ctx->queue = [ctx->device newCommandQueue];
  168. ctx->n_buffers = 0;
  169. ctx->concur_list_len = 0;
  170. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  171. // load library
  172. {
  173. NSBundle * bundle = nil;
  174. #ifdef SWIFT_PACKAGE
  175. bundle = SWIFTPM_MODULE_BUNDLE;
  176. #else
  177. bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  178. #endif
  179. NSError * error = nil;
  180. NSString * libPath = [bundle pathForResource:@"default" ofType:@"metallib"];
  181. if (libPath != nil) {
  182. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  183. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [libPath UTF8String]);
  184. ctx->library = [ctx->device newLibraryWithURL:libURL error:&error];
  185. } else {
  186. GGML_METAL_LOG_INFO("%s: default.metallib not found, loading from source\n", __func__);
  187. NSString * sourcePath;
  188. NSString * ggmlMetalPathResources = [[NSProcessInfo processInfo].environment objectForKey:@"GGML_METAL_PATH_RESOURCES"];
  189. if (ggmlMetalPathResources) {
  190. sourcePath = [ggmlMetalPathResources stringByAppendingPathComponent:@"ggml-metal.metal"];
  191. } else {
  192. sourcePath = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  193. }
  194. if (sourcePath == nil) {
  195. GGML_METAL_LOG_WARN("%s: error: could not use bundle path to find ggml-metal.metal, falling back to trying cwd\n", __func__);
  196. sourcePath = @"ggml-metal.metal";
  197. }
  198. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [sourcePath UTF8String]);
  199. NSString * src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:&error];
  200. if (error) {
  201. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  202. return NULL;
  203. }
  204. MTLCompileOptions* options = nil;
  205. #ifdef GGML_QKK_64
  206. options = [MTLCompileOptions new];
  207. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  208. #endif
  209. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  210. }
  211. if (error) {
  212. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  213. return NULL;
  214. }
  215. }
  216. // load kernels
  217. {
  218. NSError * error = nil;
  219. /*
  220. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  221. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  222. (int) ctx->pipeline_##name.threadExecutionWidth); \
  223. */
  224. #define GGML_METAL_ADD_KERNEL(name) \
  225. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  226. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  227. if (error) { \
  228. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  229. return NULL; \
  230. }
  231. GGML_METAL_ADD_KERNEL(add);
  232. GGML_METAL_ADD_KERNEL(add_row);
  233. GGML_METAL_ADD_KERNEL(mul);
  234. GGML_METAL_ADD_KERNEL(mul_row);
  235. GGML_METAL_ADD_KERNEL(scale);
  236. GGML_METAL_ADD_KERNEL(scale_4);
  237. GGML_METAL_ADD_KERNEL(silu);
  238. GGML_METAL_ADD_KERNEL(relu);
  239. GGML_METAL_ADD_KERNEL(gelu);
  240. GGML_METAL_ADD_KERNEL(soft_max);
  241. GGML_METAL_ADD_KERNEL(soft_max_4);
  242. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  243. GGML_METAL_ADD_KERNEL(diag_mask_inf_8);
  244. GGML_METAL_ADD_KERNEL(get_rows_f32);
  245. GGML_METAL_ADD_KERNEL(get_rows_f16);
  246. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  247. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  248. GGML_METAL_ADD_KERNEL(get_rows_q5_0);
  249. GGML_METAL_ADD_KERNEL(get_rows_q5_1);
  250. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  251. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  252. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  253. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  254. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  255. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  256. GGML_METAL_ADD_KERNEL(rms_norm);
  257. GGML_METAL_ADD_KERNEL(norm);
  258. GGML_METAL_ADD_KERNEL(mul_mv_f32_f32);
  259. GGML_METAL_ADD_KERNEL(mul_mv_f16_f16);
  260. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32);
  261. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_1row);
  262. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_l4);
  263. GGML_METAL_ADD_KERNEL(mul_mv_q4_0_f32);
  264. GGML_METAL_ADD_KERNEL(mul_mv_q4_1_f32);
  265. GGML_METAL_ADD_KERNEL(mul_mv_q5_0_f32);
  266. GGML_METAL_ADD_KERNEL(mul_mv_q5_1_f32);
  267. GGML_METAL_ADD_KERNEL(mul_mv_q8_0_f32);
  268. GGML_METAL_ADD_KERNEL(mul_mv_q2_K_f32);
  269. GGML_METAL_ADD_KERNEL(mul_mv_q3_K_f32);
  270. GGML_METAL_ADD_KERNEL(mul_mv_q4_K_f32);
  271. GGML_METAL_ADD_KERNEL(mul_mv_q5_K_f32);
  272. GGML_METAL_ADD_KERNEL(mul_mv_q6_K_f32);
  273. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  274. GGML_METAL_ADD_KERNEL(mul_mm_f32_f32);
  275. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  276. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  277. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  278. GGML_METAL_ADD_KERNEL(mul_mm_q5_0_f32);
  279. GGML_METAL_ADD_KERNEL(mul_mm_q5_1_f32);
  280. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  281. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  282. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  283. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  284. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  285. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  286. }
  287. GGML_METAL_ADD_KERNEL(rope_f32);
  288. GGML_METAL_ADD_KERNEL(rope_f16);
  289. GGML_METAL_ADD_KERNEL(alibi_f32);
  290. GGML_METAL_ADD_KERNEL(im2col_f16);
  291. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  292. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  293. GGML_METAL_ADD_KERNEL(cpy_f32_q8_0);
  294. GGML_METAL_ADD_KERNEL(cpy_f32_q4_0);
  295. GGML_METAL_ADD_KERNEL(cpy_f32_q4_1);
  296. //GGML_METAL_ADD_KERNEL(cpy_f32_q5_0);
  297. //GGML_METAL_ADD_KERNEL(cpy_f32_q5_1);
  298. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  299. GGML_METAL_ADD_KERNEL(concat);
  300. GGML_METAL_ADD_KERNEL(sqr);
  301. #undef GGML_METAL_ADD_KERNEL
  302. }
  303. #if TARGET_OS_OSX
  304. // print MTL GPU family:
  305. GGML_METAL_LOG_INFO("%s: GPU name: %s\n", __func__, [[ctx->device name] UTF8String]);
  306. // determine max supported GPU family
  307. // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
  308. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  309. for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) {
  310. if ([ctx->device supportsFamily:i]) {
  311. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, i - (int) MTLGPUFamilyApple1 + 1, i);
  312. break;
  313. }
  314. }
  315. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  316. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MiB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  317. if (ctx->device.maxTransferRate != 0) {
  318. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MiB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  319. } else {
  320. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  321. }
  322. #endif
  323. return ctx;
  324. }
  325. void ggml_metal_free(struct ggml_metal_context * ctx) {
  326. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  327. #define GGML_METAL_DEL_KERNEL(name) \
  328. [ctx->function_##name release]; \
  329. [ctx->pipeline_##name release];
  330. GGML_METAL_DEL_KERNEL(add);
  331. GGML_METAL_DEL_KERNEL(add_row);
  332. GGML_METAL_DEL_KERNEL(mul);
  333. GGML_METAL_DEL_KERNEL(mul_row);
  334. GGML_METAL_DEL_KERNEL(scale);
  335. GGML_METAL_DEL_KERNEL(scale_4);
  336. GGML_METAL_DEL_KERNEL(silu);
  337. GGML_METAL_DEL_KERNEL(relu);
  338. GGML_METAL_DEL_KERNEL(gelu);
  339. GGML_METAL_DEL_KERNEL(soft_max);
  340. GGML_METAL_DEL_KERNEL(soft_max_4);
  341. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  342. GGML_METAL_DEL_KERNEL(diag_mask_inf_8);
  343. GGML_METAL_DEL_KERNEL(get_rows_f32);
  344. GGML_METAL_DEL_KERNEL(get_rows_f16);
  345. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  346. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  347. GGML_METAL_DEL_KERNEL(get_rows_q5_0);
  348. GGML_METAL_DEL_KERNEL(get_rows_q5_1);
  349. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  350. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  351. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  352. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  353. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  354. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  355. GGML_METAL_DEL_KERNEL(rms_norm);
  356. GGML_METAL_DEL_KERNEL(norm);
  357. GGML_METAL_DEL_KERNEL(mul_mv_f32_f32);
  358. GGML_METAL_DEL_KERNEL(mul_mv_f16_f16);
  359. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32);
  360. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_1row);
  361. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_l4);
  362. GGML_METAL_DEL_KERNEL(mul_mv_q4_0_f32);
  363. GGML_METAL_DEL_KERNEL(mul_mv_q4_1_f32);
  364. GGML_METAL_DEL_KERNEL(mul_mv_q5_0_f32);
  365. GGML_METAL_DEL_KERNEL(mul_mv_q5_1_f32);
  366. GGML_METAL_DEL_KERNEL(mul_mv_q8_0_f32);
  367. GGML_METAL_DEL_KERNEL(mul_mv_q2_K_f32);
  368. GGML_METAL_DEL_KERNEL(mul_mv_q3_K_f32);
  369. GGML_METAL_DEL_KERNEL(mul_mv_q4_K_f32);
  370. GGML_METAL_DEL_KERNEL(mul_mv_q5_K_f32);
  371. GGML_METAL_DEL_KERNEL(mul_mv_q6_K_f32);
  372. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  373. GGML_METAL_DEL_KERNEL(mul_mm_f32_f32);
  374. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  375. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  376. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  377. GGML_METAL_DEL_KERNEL(mul_mm_q5_0_f32);
  378. GGML_METAL_DEL_KERNEL(mul_mm_q5_1_f32);
  379. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  380. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  381. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  382. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  383. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  384. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  385. }
  386. GGML_METAL_DEL_KERNEL(rope_f32);
  387. GGML_METAL_DEL_KERNEL(rope_f16);
  388. GGML_METAL_DEL_KERNEL(alibi_f32);
  389. GGML_METAL_DEL_KERNEL(im2col_f16);
  390. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  391. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  392. GGML_METAL_DEL_KERNEL(cpy_f32_q8_0);
  393. GGML_METAL_DEL_KERNEL(cpy_f32_q4_0);
  394. GGML_METAL_DEL_KERNEL(cpy_f32_q4_1);
  395. //GGML_METAL_DEL_KERNEL(cpy_f32_q5_0);
  396. //GGML_METAL_DEL_KERNEL(cpy_f32_q5_1);
  397. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  398. GGML_METAL_DEL_KERNEL(concat);
  399. GGML_METAL_DEL_KERNEL(sqr);
  400. #undef GGML_METAL_DEL_KERNEL
  401. for (int i = 0; i < ctx->n_buffers; ++i) {
  402. [ctx->buffers[i].metal release];
  403. }
  404. [ctx->library release];
  405. [ctx->queue release];
  406. [ctx->device release];
  407. dispatch_release(ctx->d_queue);
  408. free(ctx);
  409. }
  410. void * ggml_metal_host_malloc(size_t n) {
  411. void * data = NULL;
  412. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  413. if (result != 0) {
  414. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  415. return NULL;
  416. }
  417. return data;
  418. }
  419. void ggml_metal_host_free(void * data) {
  420. free(data);
  421. }
  422. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  423. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  424. }
  425. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  426. return ctx->concur_list_len;
  427. }
  428. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  429. return ctx->concur_list;
  430. }
  431. // finds the Metal buffer that contains the tensor data on the GPU device
  432. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  433. // Metal buffer based on the host memory pointer
  434. //
  435. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  436. //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);
  437. const int64_t tsize = ggml_nbytes(t);
  438. if (t->buffer && t->buffer->backend && t->buffer->backend->context) {
  439. ctx = t->buffer->backend->context;
  440. }
  441. // find the view that contains the tensor fully
  442. for (int i = 0; i < ctx->n_buffers; ++i) {
  443. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  444. //GGML_METAL_LOG_INFO("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);
  445. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  446. *offs = (size_t) ioffs;
  447. //GGML_METAL_LOG_INFO("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  448. return ctx->buffers[i].metal;
  449. }
  450. }
  451. GGML_METAL_LOG_ERROR("%s: error: buffer is nil\n", __func__);
  452. return nil;
  453. }
  454. bool ggml_metal_add_buffer(
  455. struct ggml_metal_context * ctx,
  456. const char * name,
  457. void * data,
  458. size_t size,
  459. size_t max_size) {
  460. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  461. GGML_METAL_LOG_ERROR("%s: error: too many buffers\n", __func__);
  462. return false;
  463. }
  464. if (data) {
  465. // verify that the buffer does not overlap with any of the existing buffers
  466. for (int i = 0; i < ctx->n_buffers; ++i) {
  467. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  468. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  469. GGML_METAL_LOG_ERROR("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  470. return false;
  471. }
  472. }
  473. const size_t size_page = sysconf(_SC_PAGESIZE);
  474. size_t size_aligned = size;
  475. if ((size_aligned % size_page) != 0) {
  476. size_aligned += (size_page - (size_aligned % size_page));
  477. }
  478. // the buffer fits into the max buffer size allowed by the device
  479. if (size_aligned <= ctx->device.maxBufferLength) {
  480. ctx->buffers[ctx->n_buffers].name = name;
  481. ctx->buffers[ctx->n_buffers].data = data;
  482. ctx->buffers[ctx->n_buffers].size = size;
  483. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  484. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  485. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MiB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  486. return false;
  487. }
  488. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MiB", __func__, name, size_aligned / 1024.0 / 1024.0);
  489. ++ctx->n_buffers;
  490. } else {
  491. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  492. // one of the views
  493. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  494. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  495. const size_t size_view = ctx->device.maxBufferLength;
  496. for (size_t i = 0; i < size; i += size_step) {
  497. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  498. ctx->buffers[ctx->n_buffers].name = name;
  499. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  500. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  501. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  502. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  503. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MiB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  504. return false;
  505. }
  506. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MiB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  507. if (i + size_step < size) {
  508. GGML_METAL_LOG_INFO("\n");
  509. }
  510. ++ctx->n_buffers;
  511. }
  512. }
  513. #if TARGET_OS_OSX
  514. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  515. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  516. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  517. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  518. GGML_METAL_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
  519. } else {
  520. GGML_METAL_LOG_INFO("\n");
  521. }
  522. #else
  523. GGML_METAL_LOG_INFO(", (%8.2f)\n", ctx->device.currentAllocatedSize / 1024.0 / 1024.0);
  524. #endif
  525. }
  526. return true;
  527. }
  528. void ggml_metal_set_tensor(
  529. struct ggml_metal_context * ctx,
  530. struct ggml_tensor * t) {
  531. size_t offs;
  532. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  533. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  534. }
  535. void ggml_metal_get_tensor(
  536. struct ggml_metal_context * ctx,
  537. struct ggml_tensor * t) {
  538. size_t offs;
  539. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  540. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  541. }
  542. void ggml_metal_graph_find_concurrency(
  543. struct ggml_metal_context * ctx,
  544. struct ggml_cgraph * gf, bool check_mem) {
  545. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  546. int nodes_unused[GGML_MAX_CONCUR];
  547. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  548. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  549. ctx->concur_list_len = 0;
  550. int n_left = gf->n_nodes;
  551. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  552. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  553. while (n_left > 0) {
  554. // number of nodes at a layer (that can be issued concurrently)
  555. int concurrency = 0;
  556. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  557. if (nodes_unused[i]) {
  558. // if the requirements for gf->nodes[i] are satisfied
  559. int exe_flag = 1;
  560. // scan all srcs
  561. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  562. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  563. if (src_cur) {
  564. // if is leaf nodes it's satisfied.
  565. // TODO: ggml_is_leaf()
  566. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  567. continue;
  568. }
  569. // otherwise this src should be the output from previous nodes.
  570. int is_found = 0;
  571. // scan 2*search_depth back because we inserted barrier.
  572. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  573. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  574. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  575. is_found = 1;
  576. break;
  577. }
  578. }
  579. if (is_found == 0) {
  580. exe_flag = 0;
  581. break;
  582. }
  583. }
  584. }
  585. if (exe_flag && check_mem) {
  586. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  587. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  588. int64_t data_start = (int64_t) gf->nodes[i]->data;
  589. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  590. for (int j = n_start; j < i; j++) {
  591. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  592. && gf->nodes[j]->op != GGML_OP_VIEW \
  593. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  594. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  595. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  596. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  597. continue;
  598. }
  599. exe_flag = 0;
  600. }
  601. }
  602. }
  603. if (exe_flag) {
  604. ctx->concur_list[level_pos + concurrency] = i;
  605. nodes_unused[i] = 0;
  606. concurrency++;
  607. ctx->concur_list_len++;
  608. }
  609. }
  610. }
  611. n_left -= concurrency;
  612. // adding a barrier different layer
  613. ctx->concur_list[level_pos + concurrency] = -1;
  614. ctx->concur_list_len++;
  615. // jump all sorted nodes at nodes_bak
  616. while (!nodes_unused[n_start]) {
  617. n_start++;
  618. }
  619. level_pos += concurrency + 1;
  620. }
  621. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  622. GGML_METAL_LOG_WARN("%s: too many elements for metal ctx->concur_list!\n", __func__);
  623. }
  624. }
  625. void ggml_metal_graph_compute(
  626. struct ggml_metal_context * ctx,
  627. struct ggml_cgraph * gf) {
  628. @autoreleasepool {
  629. // if there is ctx->concur_list, dispatch concurrently
  630. // else fallback to serial dispatch
  631. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  632. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  633. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  634. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  635. // create multiple command buffers and enqueue them
  636. // then, we encode the graph into the command buffers in parallel
  637. const int n_cb = ctx->n_cb;
  638. for (int i = 0; i < n_cb; ++i) {
  639. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  640. // enqueue the command buffers in order to specify their execution order
  641. [ctx->command_buffers[i] enqueue];
  642. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  643. }
  644. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  645. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  646. dispatch_async(ctx->d_queue, ^{
  647. size_t offs_src0 = 0;
  648. size_t offs_src1 = 0;
  649. size_t offs_dst = 0;
  650. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  651. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  652. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  653. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  654. for (int ind = node_start; ind < node_end; ++ind) {
  655. const int i = has_concur ? ctx->concur_list[ind] : ind;
  656. if (i == -1) {
  657. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  658. continue;
  659. }
  660. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  661. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  662. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  663. struct ggml_tensor * dst = gf->nodes[i];
  664. switch (dst->op) {
  665. case GGML_OP_NONE:
  666. case GGML_OP_RESHAPE:
  667. case GGML_OP_VIEW:
  668. case GGML_OP_TRANSPOSE:
  669. case GGML_OP_PERMUTE:
  670. {
  671. // noop -> next node
  672. } continue;
  673. default:
  674. {
  675. } break;
  676. }
  677. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  678. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  679. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  680. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  681. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  682. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  683. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  684. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  685. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  686. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  687. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  688. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  689. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  690. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  691. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  692. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  693. const int64_t ne0 = dst ? dst->ne[0] : 0;
  694. const int64_t ne1 = dst ? dst->ne[1] : 0;
  695. const int64_t ne2 = dst ? dst->ne[2] : 0;
  696. const int64_t ne3 = dst ? dst->ne[3] : 0;
  697. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  698. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  699. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  700. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  701. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  702. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  703. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  704. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  705. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  706. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  707. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  708. //if (src0) {
  709. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  710. // ggml_is_contiguous(src0), src0->name);
  711. //}
  712. //if (src1) {
  713. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  714. // ggml_is_contiguous(src1), src1->name);
  715. //}
  716. //if (dst) {
  717. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  718. // dst->name);
  719. //}
  720. switch (dst->op) {
  721. case GGML_OP_CONCAT:
  722. {
  723. const int64_t nb = ne00;
  724. [encoder setComputePipelineState:ctx->pipeline_concat];
  725. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  726. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  727. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  728. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  729. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  730. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  731. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  732. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  733. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  734. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  735. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  736. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  737. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  738. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  739. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  740. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  741. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  742. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  743. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  744. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  745. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  746. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  747. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  748. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  749. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  750. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  751. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  752. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  753. const int nth = MIN(1024, ne0);
  754. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  755. } break;
  756. case GGML_OP_ADD:
  757. {
  758. GGML_ASSERT(ggml_is_contiguous(src0));
  759. GGML_ASSERT(ggml_is_contiguous(src1));
  760. bool bcast_row = false;
  761. int64_t nb = ne00;
  762. if (ggml_nelements(src1) == ne10 && ne00 % 4 == 0) {
  763. // src1 is a row
  764. GGML_ASSERT(ne11 == 1);
  765. nb = ne00 / 4;
  766. [encoder setComputePipelineState:ctx->pipeline_add_row];
  767. bcast_row = true;
  768. } else {
  769. [encoder setComputePipelineState:ctx->pipeline_add];
  770. }
  771. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  772. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  773. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  774. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  775. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  776. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  777. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  778. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  779. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  780. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  781. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  782. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  783. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  784. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  785. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  786. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  787. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  788. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  789. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  790. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  791. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  792. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  793. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  794. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  795. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  796. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  797. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  798. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  799. if (bcast_row) {
  800. const int64_t n = ggml_nelements(dst)/4;
  801. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  802. } else {
  803. const int nth = MIN(1024, ne0);
  804. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  805. }
  806. } break;
  807. case GGML_OP_MUL:
  808. {
  809. GGML_ASSERT(ggml_is_contiguous(src0));
  810. GGML_ASSERT(ggml_is_contiguous(src1));
  811. // utilize float4
  812. GGML_ASSERT(ne00 % 4 == 0);
  813. const int64_t nb = ne00/4;
  814. if (ggml_nelements(src1) == ne10) {
  815. // src1 is a row
  816. GGML_ASSERT(ne11 == 1);
  817. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  818. } else {
  819. [encoder setComputePipelineState:ctx->pipeline_mul];
  820. }
  821. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  822. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  823. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  824. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  825. const int64_t n = ggml_nelements(dst)/4;
  826. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  827. } break;
  828. case GGML_OP_SCALE:
  829. {
  830. GGML_ASSERT(ggml_is_contiguous(src0));
  831. const float scale = *(const float *) src1->data;
  832. int64_t n = ggml_nelements(dst);
  833. if (n % 4 == 0) {
  834. n /= 4;
  835. [encoder setComputePipelineState:ctx->pipeline_scale_4];
  836. } else {
  837. [encoder setComputePipelineState:ctx->pipeline_scale];
  838. }
  839. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  840. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  841. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  842. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  843. } break;
  844. case GGML_OP_UNARY:
  845. switch (ggml_get_unary_op(gf->nodes[i])) {
  846. case GGML_UNARY_OP_SILU:
  847. {
  848. [encoder setComputePipelineState:ctx->pipeline_silu];
  849. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  850. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  851. const int64_t n = ggml_nelements(dst);
  852. GGML_ASSERT(n % 4 == 0);
  853. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  854. } break;
  855. case GGML_UNARY_OP_RELU:
  856. {
  857. [encoder setComputePipelineState:ctx->pipeline_relu];
  858. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  859. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  860. const int64_t n = ggml_nelements(dst);
  861. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  862. } break;
  863. case GGML_UNARY_OP_GELU:
  864. {
  865. [encoder setComputePipelineState:ctx->pipeline_gelu];
  866. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  867. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  868. const int64_t n = ggml_nelements(dst);
  869. GGML_ASSERT(n % 4 == 0);
  870. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  871. } break;
  872. default:
  873. {
  874. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  875. GGML_ASSERT(false);
  876. }
  877. } break;
  878. case GGML_OP_SQR:
  879. {
  880. GGML_ASSERT(ggml_is_contiguous(src0));
  881. [encoder setComputePipelineState:ctx->pipeline_sqr];
  882. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  883. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  884. const int64_t n = ggml_nelements(dst);
  885. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  886. } break;
  887. case GGML_OP_SOFT_MAX:
  888. {
  889. int nth = 32; // SIMD width
  890. if (ne00%4 == 0) {
  891. while (nth < ne00/4 && nth < 256) {
  892. nth *= 2;
  893. }
  894. [encoder setComputePipelineState:ctx->pipeline_soft_max_4];
  895. } else {
  896. while (nth < ne00 && nth < 1024) {
  897. nth *= 2;
  898. }
  899. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  900. }
  901. const float scale = ((float *) dst->op_params)[0];
  902. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  903. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  904. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  905. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  906. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  907. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  908. [encoder setBytes:&scale length:sizeof(scale) atIndex:6];
  909. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  910. [encoder dispatchThreadgroups:MTLSizeMake(ne01*ne02*ne03, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  911. } break;
  912. case GGML_OP_DIAG_MASK_INF:
  913. {
  914. const int n_past = ((int32_t *)(dst->op_params))[0];
  915. if (ne00%8 == 0) {
  916. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf_8];
  917. } else {
  918. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  919. }
  920. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  921. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  922. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  923. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  924. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  925. if (ne00%8 == 0) {
  926. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  927. }
  928. else {
  929. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  930. }
  931. } break;
  932. case GGML_OP_MUL_MAT:
  933. {
  934. GGML_ASSERT(ne00 == ne10);
  935. GGML_ASSERT(ne03 == ne13);
  936. const uint gqa = ne12/ne02;
  937. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  938. // to the matrix-vector kernel
  939. int ne11_mm_min = src0t == GGML_TYPE_F16 ? 1 : 16;
  940. #if 0
  941. // the numbers below are measured on M2 Ultra for 7B and 13B models
  942. // these numbers do not translate to other devices or model sizes
  943. // TODO: need to find a better approach
  944. if ([ctx->device.name isEqualToString:@"Apple M2 Ultra"]) {
  945. switch (src0t) {
  946. case GGML_TYPE_F16: ne11_mm_min = 2; break;
  947. case GGML_TYPE_Q8_0: ne11_mm_min = 7; break;
  948. case GGML_TYPE_Q2_K: ne11_mm_min = 15; break;
  949. case GGML_TYPE_Q3_K: ne11_mm_min = 7; break;
  950. case GGML_TYPE_Q4_0:
  951. case GGML_TYPE_Q4_1: ne11_mm_min = 15; break;
  952. case GGML_TYPE_Q4_K: ne11_mm_min = 11; break;
  953. case GGML_TYPE_Q5_0: // not tested yet
  954. case GGML_TYPE_Q5_1: ne11_mm_min = 13; break; // not tested yet
  955. case GGML_TYPE_Q5_K: ne11_mm_min = 7; break;
  956. case GGML_TYPE_Q6_K: ne11_mm_min = 7; break;
  957. default: ne11_mm_min = 1; break;
  958. }
  959. }
  960. #endif
  961. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  962. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  963. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  964. !ggml_is_transposed(src0) &&
  965. !ggml_is_transposed(src1) &&
  966. src1t == GGML_TYPE_F32 &&
  967. ne00 % 32 == 0 && ne00 >= 64 &&
  968. (ne11 > ne11_mm_min || (ggml_is_quantized(src0t) && ne12 > 1))) {
  969. //printf("matrix: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  970. switch (src0->type) {
  971. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f32_f32]; break;
  972. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  973. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  974. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  975. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_0_f32]; break;
  976. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_1_f32]; break;
  977. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  978. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  979. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  980. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  981. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  982. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  983. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  984. }
  985. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  986. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  987. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  988. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  989. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  990. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  991. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  992. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  993. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  994. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  995. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  996. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  997. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  998. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:13];
  999. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  1000. [encoder dispatchThreadgroups:MTLSizeMake( (ne11 + 31)/32, (ne01 + 63)/64, ne12) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  1001. } else {
  1002. int nth0 = 32;
  1003. int nth1 = 1;
  1004. int nrows = 1;
  1005. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1006. // use custom matrix x vector kernel
  1007. switch (src0t) {
  1008. case GGML_TYPE_F32:
  1009. {
  1010. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1011. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f32_f32];
  1012. nrows = 4;
  1013. } break;
  1014. case GGML_TYPE_F16:
  1015. {
  1016. nth0 = 32;
  1017. nth1 = 1;
  1018. if (src1t == GGML_TYPE_F32) {
  1019. if (ne11 * ne12 < 4) {
  1020. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_1row];
  1021. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  1022. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_l4];
  1023. nrows = ne11;
  1024. } else {
  1025. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32];
  1026. nrows = 4;
  1027. }
  1028. } else {
  1029. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f16];
  1030. nrows = 4;
  1031. }
  1032. } break;
  1033. case GGML_TYPE_Q4_0:
  1034. {
  1035. GGML_ASSERT(ne02 == 1);
  1036. GGML_ASSERT(ne12 == 1);
  1037. nth0 = 8;
  1038. nth1 = 8;
  1039. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_0_f32];
  1040. } break;
  1041. case GGML_TYPE_Q4_1:
  1042. {
  1043. GGML_ASSERT(ne02 == 1);
  1044. GGML_ASSERT(ne12 == 1);
  1045. nth0 = 8;
  1046. nth1 = 8;
  1047. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_1_f32];
  1048. } break;
  1049. case GGML_TYPE_Q5_0:
  1050. {
  1051. GGML_ASSERT(ne02 == 1);
  1052. GGML_ASSERT(ne12 == 1);
  1053. nth0 = 8;
  1054. nth1 = 8;
  1055. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_0_f32];
  1056. } break;
  1057. case GGML_TYPE_Q5_1:
  1058. {
  1059. GGML_ASSERT(ne02 == 1);
  1060. GGML_ASSERT(ne12 == 1);
  1061. nth0 = 8;
  1062. nth1 = 8;
  1063. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_1_f32];
  1064. } break;
  1065. case GGML_TYPE_Q8_0:
  1066. {
  1067. GGML_ASSERT(ne02 == 1);
  1068. GGML_ASSERT(ne12 == 1);
  1069. nth0 = 8;
  1070. nth1 = 8;
  1071. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q8_0_f32];
  1072. } break;
  1073. case GGML_TYPE_Q2_K:
  1074. {
  1075. GGML_ASSERT(ne02 == 1);
  1076. GGML_ASSERT(ne12 == 1);
  1077. nth0 = 2;
  1078. nth1 = 32;
  1079. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q2_K_f32];
  1080. } break;
  1081. case GGML_TYPE_Q3_K:
  1082. {
  1083. GGML_ASSERT(ne02 == 1);
  1084. GGML_ASSERT(ne12 == 1);
  1085. nth0 = 2;
  1086. nth1 = 32;
  1087. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q3_K_f32];
  1088. } break;
  1089. case GGML_TYPE_Q4_K:
  1090. {
  1091. GGML_ASSERT(ne02 == 1);
  1092. GGML_ASSERT(ne12 == 1);
  1093. nth0 = 4; //1;
  1094. nth1 = 8; //32;
  1095. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_K_f32];
  1096. } break;
  1097. case GGML_TYPE_Q5_K:
  1098. {
  1099. GGML_ASSERT(ne02 == 1);
  1100. GGML_ASSERT(ne12 == 1);
  1101. nth0 = 2;
  1102. nth1 = 32;
  1103. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_K_f32];
  1104. } break;
  1105. case GGML_TYPE_Q6_K:
  1106. {
  1107. GGML_ASSERT(ne02 == 1);
  1108. GGML_ASSERT(ne12 == 1);
  1109. nth0 = 2;
  1110. nth1 = 32;
  1111. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q6_K_f32];
  1112. } break;
  1113. default:
  1114. {
  1115. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  1116. GGML_ASSERT(false && "not implemented");
  1117. }
  1118. };
  1119. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1120. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1121. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1122. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1123. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1124. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1125. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1126. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1127. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1128. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  1129. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  1130. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  1131. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  1132. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  1133. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  1134. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  1135. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  1136. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:17];
  1137. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 ||
  1138. src0t == GGML_TYPE_Q5_0 || src0t == GGML_TYPE_Q5_1 || src0t == GGML_TYPE_Q8_0 ||
  1139. src0t == GGML_TYPE_Q2_K) { // || src0t == GGML_TYPE_Q4_K) {
  1140. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1141. }
  1142. else if (src0t == GGML_TYPE_Q4_K) {
  1143. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1144. }
  1145. else if (src0t == GGML_TYPE_Q3_K) {
  1146. #ifdef GGML_QKK_64
  1147. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1148. #else
  1149. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1150. #endif
  1151. }
  1152. else if (src0t == GGML_TYPE_Q5_K) {
  1153. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1154. }
  1155. else if (src0t == GGML_TYPE_Q6_K) {
  1156. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1157. } else {
  1158. int64_t ny = (ne11 + nrows - 1)/nrows;
  1159. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1160. }
  1161. }
  1162. } break;
  1163. case GGML_OP_GET_ROWS:
  1164. {
  1165. switch (src0->type) {
  1166. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_get_rows_f32]; break;
  1167. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  1168. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  1169. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  1170. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_0]; break;
  1171. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_1]; break;
  1172. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  1173. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  1174. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  1175. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  1176. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  1177. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  1178. default: GGML_ASSERT(false && "not implemented");
  1179. }
  1180. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1181. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1182. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1183. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1184. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  1185. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:5];
  1186. const int64_t n = ggml_nelements(src1);
  1187. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1188. } break;
  1189. case GGML_OP_RMS_NORM:
  1190. {
  1191. GGML_ASSERT(ne00 % 4 == 0);
  1192. float eps;
  1193. memcpy(&eps, dst->op_params, sizeof(float));
  1194. int nth = 32; // SIMD width
  1195. while (nth < ne00/4 && nth < 1024) {
  1196. nth *= 2;
  1197. }
  1198. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  1199. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1200. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1201. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1202. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1203. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1204. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1205. const int64_t nrows = ggml_nrows(src0);
  1206. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1207. } break;
  1208. case GGML_OP_NORM:
  1209. {
  1210. float eps;
  1211. memcpy(&eps, dst->op_params, sizeof(float));
  1212. const int nth = MIN(256, ne00);
  1213. [encoder setComputePipelineState:ctx->pipeline_norm];
  1214. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1215. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1216. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1217. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1218. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1219. [encoder setThreadgroupMemoryLength:GGML_PAD(nth*sizeof(float), 16) atIndex:0];
  1220. const int64_t nrows = ggml_nrows(src0);
  1221. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1222. } break;
  1223. case GGML_OP_ALIBI:
  1224. {
  1225. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1226. const int nth = MIN(1024, ne00);
  1227. //const int n_past = ((int32_t *) dst->op_params)[0];
  1228. const int n_head = ((int32_t *) dst->op_params)[1];
  1229. float max_bias;
  1230. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1231. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1232. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1233. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  1234. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  1235. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1236. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1237. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1238. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1239. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1240. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1241. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1242. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1243. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1244. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1245. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1246. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1247. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1248. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1249. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1250. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1251. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1252. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1253. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1254. [encoder setBytes:&m1 length:sizeof( float) atIndex:19];
  1255. [encoder setBytes:&n_heads_log2_floor length:sizeof(int) atIndex:20];
  1256. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1257. } break;
  1258. case GGML_OP_ROPE:
  1259. {
  1260. GGML_ASSERT(ne10 == ne02);
  1261. const int nth = MIN(1024, ne00);
  1262. const int n_past = ((int32_t *) dst->op_params)[0];
  1263. const int n_dims = ((int32_t *) dst->op_params)[1];
  1264. const int mode = ((int32_t *) dst->op_params)[2];
  1265. // skip 3, n_ctx, used in GLM RoPE, unimplemented in metal
  1266. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  1267. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1268. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  1269. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  1270. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  1271. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  1272. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  1273. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  1274. switch (src0->type) {
  1275. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_rope_f32]; break;
  1276. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_rope_f16]; break;
  1277. default: GGML_ASSERT(false);
  1278. };
  1279. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1280. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1281. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1282. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1283. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:4];
  1284. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:5];
  1285. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:6];
  1286. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:7];
  1287. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:8];
  1288. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:9];
  1289. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:10];
  1290. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:11];
  1291. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:12];
  1292. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:13];
  1293. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:14];
  1294. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:15];
  1295. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:16];
  1296. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:17];
  1297. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:18];
  1298. [encoder setBytes:&n_past length:sizeof( int) atIndex:19];
  1299. [encoder setBytes:&n_dims length:sizeof( int) atIndex:20];
  1300. [encoder setBytes:&mode length:sizeof( int) atIndex:21];
  1301. [encoder setBytes:&n_orig_ctx length:sizeof( int) atIndex:22];
  1302. [encoder setBytes:&freq_base length:sizeof( float) atIndex:23];
  1303. [encoder setBytes:&freq_scale length:sizeof( float) atIndex:24];
  1304. [encoder setBytes:&ext_factor length:sizeof( float) atIndex:25];
  1305. [encoder setBytes:&attn_factor length:sizeof( float) atIndex:26];
  1306. [encoder setBytes:&beta_fast length:sizeof( float) atIndex:27];
  1307. [encoder setBytes:&beta_slow length:sizeof( float) atIndex:28];
  1308. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1309. } break;
  1310. case GGML_OP_IM2COL:
  1311. {
  1312. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  1313. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  1314. GGML_ASSERT( dst->type == GGML_TYPE_F16);
  1315. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  1316. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  1317. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  1318. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  1319. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  1320. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  1321. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  1322. const int32_t N = src1->ne[is_2D ? 3 : 2];
  1323. const int32_t IC = src1->ne[is_2D ? 2 : 1];
  1324. const int32_t IH = is_2D ? src1->ne[1] : 1;
  1325. const int32_t IW = src1->ne[0];
  1326. const int32_t KH = is_2D ? src0->ne[1] : 1;
  1327. const int32_t KW = src0->ne[0];
  1328. const int32_t OH = is_2D ? dst->ne[2] : 1;
  1329. const int32_t OW = dst->ne[1];
  1330. const int32_t CHW = IC * KH * KW;
  1331. const int32_t ofs0 = src1->nb[is_2D ? 3 : 2] / 4;
  1332. const int32_t ofs1 = src1->nb[is_2D ? 2 : 1] / 4;
  1333. switch (src0->type) {
  1334. case GGML_TYPE_F32: GGML_ASSERT(false && "not implemented"); break;
  1335. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_im2col_f16]; break;
  1336. default: GGML_ASSERT(false);
  1337. };
  1338. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:0];
  1339. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1340. [encoder setBytes:&ofs0 length:sizeof( int32_t) atIndex:2];
  1341. [encoder setBytes:&ofs1 length:sizeof( int32_t) atIndex:3];
  1342. [encoder setBytes:&IW length:sizeof( int32_t) atIndex:4];
  1343. [encoder setBytes:&IH length:sizeof( int32_t) atIndex:5];
  1344. [encoder setBytes:&CHW length:sizeof( int32_t) atIndex:6];
  1345. [encoder setBytes:&s0 length:sizeof( int32_t) atIndex:7];
  1346. [encoder setBytes:&s1 length:sizeof( int32_t) atIndex:8];
  1347. [encoder setBytes:&p0 length:sizeof( int32_t) atIndex:9];
  1348. [encoder setBytes:&p1 length:sizeof( int32_t) atIndex:10];
  1349. [encoder setBytes:&d0 length:sizeof( int32_t) atIndex:11];
  1350. [encoder setBytes:&d1 length:sizeof( int32_t) atIndex:12];
  1351. [encoder dispatchThreadgroups:MTLSizeMake(IC, OH, OW) threadsPerThreadgroup:MTLSizeMake(N, KH, KW)];
  1352. } break;
  1353. case GGML_OP_DUP:
  1354. case GGML_OP_CPY:
  1355. case GGML_OP_CONT:
  1356. {
  1357. GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0);
  1358. int nth = MIN(1024, ne00/ggml_blck_size(src0->type));
  1359. switch (src0t) {
  1360. case GGML_TYPE_F32:
  1361. {
  1362. GGML_ASSERT(ne0 % ggml_blck_size(dst->type) == 0);
  1363. switch (dstt) {
  1364. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  1365. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  1366. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q8_0]; break;
  1367. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q4_0]; break;
  1368. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q4_1]; break;
  1369. //case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q5_0]; break;
  1370. //case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q5_1]; break;
  1371. default: GGML_ASSERT(false && "not implemented");
  1372. };
  1373. } break;
  1374. case GGML_TYPE_F16:
  1375. {
  1376. switch (dstt) {
  1377. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  1378. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  1379. default: GGML_ASSERT(false && "not implemented");
  1380. };
  1381. } break;
  1382. default: GGML_ASSERT(false && "not implemented");
  1383. }
  1384. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1385. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1386. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1387. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1388. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1389. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1390. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1391. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1392. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1393. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1394. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1395. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1396. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1397. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1398. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1399. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1400. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1401. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1402. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1403. } break;
  1404. default:
  1405. {
  1406. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1407. GGML_ASSERT(false);
  1408. }
  1409. }
  1410. }
  1411. if (encoder != nil) {
  1412. [encoder endEncoding];
  1413. encoder = nil;
  1414. }
  1415. [command_buffer commit];
  1416. });
  1417. }
  1418. // wait for all threads to finish
  1419. dispatch_barrier_sync(ctx->d_queue, ^{});
  1420. // check status of command buffers
  1421. // needed to detect if the device ran out-of-memory for example (#1881)
  1422. for (int i = 0; i < n_cb; i++) {
  1423. [ctx->command_buffers[i] waitUntilCompleted];
  1424. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  1425. if (status != MTLCommandBufferStatusCompleted) {
  1426. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  1427. GGML_ASSERT(false);
  1428. }
  1429. }
  1430. }
  1431. }
  1432. ////////////////////////////////////////////////////////////////////////////////
  1433. // backend interface
  1434. static const char * ggml_backend_metal_name(ggml_backend_t backend) {
  1435. return "Metal";
  1436. UNUSED(backend);
  1437. }
  1438. static void ggml_backend_metal_free(ggml_backend_t backend) {
  1439. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1440. ggml_metal_free(ctx);
  1441. free(backend);
  1442. }
  1443. static void * ggml_backend_metal_buffer_get_base(ggml_backend_buffer_t buffer) {
  1444. return (void *)buffer->context;
  1445. }
  1446. static void ggml_backend_metal_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1447. free(buffer->context);
  1448. UNUSED(buffer);
  1449. }
  1450. static struct ggml_backend_buffer_i metal_backend_buffer_i = {
  1451. /* .free_buffer = */ ggml_backend_metal_buffer_free_buffer,
  1452. /* .get_base = */ ggml_backend_metal_buffer_get_base,
  1453. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  1454. /* .init_tensor = */ NULL, // no initialization required
  1455. /* .free_tensor = */ NULL, // no cleanup required
  1456. };
  1457. static ggml_backend_buffer_t ggml_backend_metal_alloc_buffer(ggml_backend_t backend, size_t size) {
  1458. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1459. void * data = ggml_metal_host_malloc(size);
  1460. // TODO: set proper name of the buffers
  1461. ggml_metal_add_buffer(ctx, "backend", data, size, 0);
  1462. return ggml_backend_buffer_init(backend, metal_backend_buffer_i, data, size);
  1463. }
  1464. static size_t ggml_backend_metal_get_alignment(ggml_backend_t backend) {
  1465. return 32;
  1466. UNUSED(backend);
  1467. }
  1468. static void ggml_backend_metal_set_tensor_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  1469. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  1470. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  1471. memcpy((char *)tensor->data + offset, data, size);
  1472. UNUSED(backend);
  1473. }
  1474. static void ggml_backend_metal_get_tensor_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  1475. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  1476. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  1477. memcpy(data, (const char *)tensor->data + offset, size);
  1478. UNUSED(backend);
  1479. }
  1480. static void ggml_backend_metal_synchronize(ggml_backend_t backend) {
  1481. UNUSED(backend);
  1482. }
  1483. static void ggml_backend_metal_cpy_tensor_from(ggml_backend_t backend, struct ggml_tensor * src, struct ggml_tensor * dst) {
  1484. ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
  1485. UNUSED(backend);
  1486. }
  1487. static void ggml_backend_metal_cpy_tensor_to(ggml_backend_t backend, struct ggml_tensor * src, struct ggml_tensor * dst) {
  1488. ggml_backend_tensor_set_async(dst, src->data, 0, ggml_nbytes(src));
  1489. UNUSED(backend);
  1490. }
  1491. static void ggml_backend_metal_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  1492. struct ggml_metal_context * metal_ctx = (struct ggml_metal_context *)backend->context;
  1493. ggml_metal_graph_compute(metal_ctx, cgraph);
  1494. }
  1495. static bool ggml_backend_metal_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  1496. return true;
  1497. UNUSED(backend);
  1498. UNUSED(op);
  1499. }
  1500. static struct ggml_backend_i metal_backend_i = {
  1501. /* .get_name = */ ggml_backend_metal_name,
  1502. /* .free = */ ggml_backend_metal_free,
  1503. /* .alloc_buffer = */ ggml_backend_metal_alloc_buffer,
  1504. /* .get_alignment = */ ggml_backend_metal_get_alignment,
  1505. /* .set_tensor_async = */ ggml_backend_metal_set_tensor_async,
  1506. /* .get_tensor_async = */ ggml_backend_metal_get_tensor_async,
  1507. /* .synchronize = */ ggml_backend_metal_synchronize,
  1508. /* .cpy_tensor_from = */ ggml_backend_metal_cpy_tensor_from,
  1509. /* .cpy_tensor_to = */ ggml_backend_metal_cpy_tensor_to,
  1510. /* .graph_plan_create = */ NULL, // the metal implementation does not require creating graph plans atm
  1511. /* .graph_plan_free = */ NULL,
  1512. /* .graph_plan_compute = */ NULL,
  1513. /* .graph_compute = */ ggml_backend_metal_graph_compute,
  1514. /* .supports_op = */ ggml_backend_metal_supports_op,
  1515. };
  1516. ggml_backend_t ggml_backend_metal_init(void) {
  1517. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  1518. ctx = ggml_metal_init(GGML_DEFAULT_N_THREADS);
  1519. ggml_backend_t metal_backend = malloc(sizeof(struct ggml_backend));
  1520. *metal_backend = (struct ggml_backend) {
  1521. /* .interface = */ metal_backend_i,
  1522. /* .context = */ ctx,
  1523. };
  1524. return metal_backend;
  1525. }
  1526. bool ggml_backend_is_metal(ggml_backend_t backend) {
  1527. return backend->iface.get_name == ggml_backend_metal_name;
  1528. }
  1529. void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
  1530. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1531. ggml_metal_set_n_cb(ctx, n_cb);
  1532. }