ggml-metal.m 89 KB

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