ggml-metal.m 121 KB

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