ggml-metal.m 107 KB

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