ggml-metal.m 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715
  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. struct ggml_metal_kernel {
  21. id<MTLComputePipelineState> pipeline;
  22. };
  23. enum ggml_metal_kernel_type {
  24. GGML_METAL_KERNEL_TYPE_ADD,
  25. GGML_METAL_KERNEL_TYPE_ADD_ROW,
  26. GGML_METAL_KERNEL_TYPE_MUL,
  27. GGML_METAL_KERNEL_TYPE_MUL_ROW,
  28. GGML_METAL_KERNEL_TYPE_DIV,
  29. GGML_METAL_KERNEL_TYPE_DIV_ROW,
  30. GGML_METAL_KERNEL_TYPE_SCALE,
  31. GGML_METAL_KERNEL_TYPE_SCALE_4,
  32. GGML_METAL_KERNEL_TYPE_TANH,
  33. GGML_METAL_KERNEL_TYPE_RELU,
  34. GGML_METAL_KERNEL_TYPE_GELU,
  35. GGML_METAL_KERNEL_TYPE_GELU_QUICK,
  36. GGML_METAL_KERNEL_TYPE_SILU,
  37. GGML_METAL_KERNEL_TYPE_SOFT_MAX,
  38. GGML_METAL_KERNEL_TYPE_SOFT_MAX_4,
  39. GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF,
  40. GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF_8,
  41. GGML_METAL_KERNEL_TYPE_GET_ROWS_F32,
  42. GGML_METAL_KERNEL_TYPE_GET_ROWS_F16,
  43. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_0,
  44. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_1,
  45. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_0,
  46. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_1,
  47. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q8_0,
  48. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q2_K,
  49. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q3_K,
  50. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_K,
  51. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_K,
  52. GGML_METAL_KERNEL_TYPE_GET_ROWS_Q6_K,
  53. GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XXS,
  54. GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XS,
  55. GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ3_XXS,
  56. GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ1_S,
  57. GGML_METAL_KERNEL_TYPE_GET_ROWS_I32,
  58. GGML_METAL_KERNEL_TYPE_RMS_NORM,
  59. GGML_METAL_KERNEL_TYPE_GROUP_NORM,
  60. GGML_METAL_KERNEL_TYPE_NORM,
  61. GGML_METAL_KERNEL_TYPE_MUL_MV_F32_F32,
  62. GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F16,
  63. GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32,
  64. GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_1ROW,
  65. GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_L4,
  66. GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_0_F32,
  67. GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_1_F32,
  68. GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_0_F32,
  69. GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_1_F32,
  70. GGML_METAL_KERNEL_TYPE_MUL_MV_Q8_0_F32,
  71. GGML_METAL_KERNEL_TYPE_MUL_MV_Q2_K_F32,
  72. GGML_METAL_KERNEL_TYPE_MUL_MV_Q3_K_F32,
  73. GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_K_F32,
  74. GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_K_F32,
  75. GGML_METAL_KERNEL_TYPE_MUL_MV_Q6_K_F32,
  76. GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XXS_F32,
  77. GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XS_F32,
  78. GGML_METAL_KERNEL_TYPE_MUL_MV_IQ3_XXS_F32,
  79. GGML_METAL_KERNEL_TYPE_MUL_MV_IQ1_S_F32,
  80. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F32_F32,
  81. //GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F16,
  82. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32,
  83. //GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32_1ROW,
  84. //GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32_L4,
  85. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_0_F32,
  86. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_1_F32,
  87. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_0_F32,
  88. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_1_F32,
  89. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q8_0_F32,
  90. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q2_K_F32,
  91. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q3_K_F32,
  92. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_K_F32,
  93. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_K_F32,
  94. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q6_K_F32,
  95. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XXS_F32,
  96. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XS_F32,
  97. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ3_XXS_F32,
  98. GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ1_S_F32,
  99. GGML_METAL_KERNEL_TYPE_MUL_MM_F32_F32,
  100. GGML_METAL_KERNEL_TYPE_MUL_MM_F16_F32,
  101. GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_0_F32,
  102. GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_1_F32,
  103. GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_0_F32,
  104. GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_1_F32,
  105. GGML_METAL_KERNEL_TYPE_MUL_MM_Q8_0_F32,
  106. GGML_METAL_KERNEL_TYPE_MUL_MM_Q2_K_F32,
  107. GGML_METAL_KERNEL_TYPE_MUL_MM_Q3_K_F32,
  108. GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_K_F32,
  109. GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_K_F32,
  110. GGML_METAL_KERNEL_TYPE_MUL_MM_Q6_K_F32,
  111. GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XXS_F32,
  112. GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XS_F32,
  113. GGML_METAL_KERNEL_TYPE_MUL_MM_IQ3_XXS_F32,
  114. GGML_METAL_KERNEL_TYPE_MUL_MM_IQ1_S_F32,
  115. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F32_F32,
  116. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F16_F32,
  117. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_0_F32,
  118. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_1_F32,
  119. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_0_F32,
  120. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_1_F32,
  121. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q8_0_F32,
  122. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q2_K_F32,
  123. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q3_K_F32,
  124. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_K_F32,
  125. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_K_F32,
  126. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q6_K_F32,
  127. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XXS_F32,
  128. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XS_F32,
  129. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ3_XXS_F32,
  130. GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ1_S_F32,
  131. GGML_METAL_KERNEL_TYPE_ROPE_F32,
  132. GGML_METAL_KERNEL_TYPE_ROPE_F16,
  133. GGML_METAL_KERNEL_TYPE_ALIBI_F32,
  134. GGML_METAL_KERNEL_TYPE_IM2COL_F16,
  135. GGML_METAL_KERNEL_TYPE_IM2COL_F32,
  136. GGML_METAL_KERNEL_TYPE_UPSCALE_F32,
  137. GGML_METAL_KERNEL_TYPE_PAD_F32,
  138. GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_ASC,
  139. GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_DESC,
  140. GGML_METAL_KERNEL_TYPE_LEAKY_RELU_F32,
  141. GGML_METAL_KERNEL_TYPE_CPY_F32_F16,
  142. GGML_METAL_KERNEL_TYPE_CPY_F32_F32,
  143. GGML_METAL_KERNEL_TYPE_CPY_F32_Q8_0,
  144. GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_0,
  145. GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_1,
  146. //GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_0,
  147. //GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_1,
  148. GGML_METAL_KERNEL_TYPE_CPY_F16_F16,
  149. GGML_METAL_KERNEL_TYPE_CPY_F16_F32,
  150. GGML_METAL_KERNEL_TYPE_CONCAT,
  151. GGML_METAL_KERNEL_TYPE_SQR,
  152. GGML_METAL_KERNEL_TYPE_SUM_ROWS,
  153. GGML_METAL_KERNEL_TYPE_COUNT
  154. };
  155. struct ggml_metal_context {
  156. int n_cb;
  157. id<MTLDevice> device;
  158. id<MTLCommandQueue> queue;
  159. dispatch_queue_t d_queue;
  160. struct ggml_metal_kernel kernels[GGML_METAL_KERNEL_TYPE_COUNT];
  161. bool support_simdgroup_reduction;
  162. bool support_simdgroup_mm;
  163. bool should_capture_next_compute;
  164. };
  165. // MSL code
  166. // TODO: move the contents here when ready
  167. // for now it is easier to work in a separate file
  168. // static NSString * const msl_library_source = @"see metal.metal";
  169. // Here to assist with NSBundle Path Hack
  170. @interface GGMLMetalClass : NSObject
  171. @end
  172. @implementation GGMLMetalClass
  173. @end
  174. static void ggml_metal_default_log_callback(enum ggml_log_level level, const char * msg, void * user_data) {
  175. fprintf(stderr, "%s", msg);
  176. UNUSED(level);
  177. UNUSED(user_data);
  178. }
  179. ggml_log_callback ggml_metal_log_callback = ggml_metal_default_log_callback;
  180. void * ggml_metal_log_user_data = NULL;
  181. GGML_ATTRIBUTE_FORMAT(2, 3)
  182. static void ggml_metal_log(enum ggml_log_level level, const char * format, ...){
  183. if (ggml_metal_log_callback != NULL) {
  184. va_list args;
  185. va_start(args, format);
  186. char buffer[128];
  187. int len = vsnprintf(buffer, 128, format, args);
  188. if (len < 128) {
  189. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  190. } else {
  191. char* buffer2 = malloc(len+1);
  192. va_end(args);
  193. va_start(args, format);
  194. vsnprintf(buffer2, len+1, format, args);
  195. buffer2[len] = 0;
  196. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  197. free(buffer2);
  198. }
  199. va_end(args);
  200. }
  201. }
  202. static void * ggml_metal_host_malloc(size_t n) {
  203. void * data = NULL;
  204. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  205. if (result != 0) {
  206. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  207. return NULL;
  208. }
  209. return data;
  210. }
  211. static struct ggml_metal_context * ggml_metal_init(int n_cb) {
  212. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  213. #if TARGET_OS_OSX && !GGML_METAL_NDEBUG
  214. // Show all the Metal device instances in the system
  215. NSArray * devices = MTLCopyAllDevices();
  216. for (id<MTLDevice> device in devices) {
  217. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [[device name] UTF8String]);
  218. }
  219. [devices release]; // since it was created by a *Copy* C method
  220. #endif
  221. // Pick and show default Metal device
  222. id<MTLDevice> device = MTLCreateSystemDefaultDevice();
  223. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [[device name] UTF8String]);
  224. // Configure context
  225. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  226. ctx->device = device;
  227. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  228. ctx->queue = [ctx->device newCommandQueue];
  229. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  230. id<MTLLibrary> metal_library;
  231. // load library
  232. {
  233. NSBundle * bundle = nil;
  234. #ifdef SWIFT_PACKAGE
  235. bundle = SWIFTPM_MODULE_BUNDLE;
  236. #else
  237. bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  238. #endif
  239. NSError * error = nil;
  240. NSString * libPath = [bundle pathForResource:@"default" ofType:@"metallib"];
  241. if (libPath != nil) {
  242. // pre-compiled library found
  243. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  244. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [libPath UTF8String]);
  245. metal_library = [ctx->device newLibraryWithURL:libURL error:&error];
  246. if (error) {
  247. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  248. return NULL;
  249. }
  250. } else {
  251. #if GGML_METAL_EMBED_LIBRARY
  252. GGML_METAL_LOG_INFO("%s: using embedded metal library\n", __func__);
  253. extern const char ggml_metallib_start[];
  254. extern const char ggml_metallib_end[];
  255. NSString * src = [[NSString alloc] initWithBytes:ggml_metallib_start length:(ggml_metallib_end-ggml_metallib_start) encoding:NSUTF8StringEncoding];
  256. #else
  257. GGML_METAL_LOG_INFO("%s: default.metallib not found, loading from source\n", __func__);
  258. NSString * sourcePath;
  259. NSString * ggmlMetalPathResources = [[NSProcessInfo processInfo].environment objectForKey:@"GGML_METAL_PATH_RESOURCES"];
  260. GGML_METAL_LOG_INFO("%s: GGML_METAL_PATH_RESOURCES = %s\n", __func__, ggmlMetalPathResources ? [ggmlMetalPathResources UTF8String] : "nil");
  261. if (ggmlMetalPathResources) {
  262. sourcePath = [ggmlMetalPathResources stringByAppendingPathComponent:@"ggml-metal.metal"];
  263. } else {
  264. sourcePath = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  265. }
  266. if (sourcePath == nil) {
  267. GGML_METAL_LOG_WARN("%s: error: could not use bundle path to find ggml-metal.metal, falling back to trying cwd\n", __func__);
  268. sourcePath = @"ggml-metal.metal";
  269. }
  270. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [sourcePath UTF8String]);
  271. NSString * src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:&error];
  272. if (error) {
  273. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  274. return NULL;
  275. }
  276. #endif
  277. @autoreleasepool {
  278. // dictionary of preprocessor macros
  279. NSMutableDictionary * prep = [NSMutableDictionary dictionary];
  280. #ifdef GGML_QKK_64
  281. prep[@"QK_K"] = @(64);
  282. #endif
  283. MTLCompileOptions* options = [MTLCompileOptions new];
  284. options.preprocessorMacros = prep;
  285. //[options setFastMathEnabled:false];
  286. metal_library = [ctx->device newLibraryWithSource:src options:options error:&error];
  287. if (error) {
  288. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  289. return NULL;
  290. }
  291. }
  292. }
  293. }
  294. // print MTL GPU family:
  295. GGML_METAL_LOG_INFO("%s: GPU name: %s\n", __func__, [[ctx->device name] UTF8String]);
  296. const NSInteger MTLGPUFamilyMetal3 = 5001;
  297. // determine max supported GPU family
  298. // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
  299. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  300. {
  301. for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) {
  302. if ([ctx->device supportsFamily:i]) {
  303. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, i - (int) MTLGPUFamilyApple1 + 1, i);
  304. break;
  305. }
  306. }
  307. for (int i = MTLGPUFamilyCommon1 + 5; i >= MTLGPUFamilyCommon1; --i) {
  308. if ([ctx->device supportsFamily:i]) {
  309. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyCommon%d (%d)\n", __func__, i - (int) MTLGPUFamilyCommon1 + 1, i);
  310. break;
  311. }
  312. }
  313. for (int i = MTLGPUFamilyMetal3 + 5; i >= MTLGPUFamilyMetal3; --i) {
  314. if ([ctx->device supportsFamily:i]) {
  315. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyMetal%d (%d)\n", __func__, i - (int) MTLGPUFamilyMetal3 + 3, i);
  316. break;
  317. }
  318. }
  319. }
  320. ctx->support_simdgroup_reduction = [ctx->device supportsFamily:MTLGPUFamilyApple7];
  321. ctx->support_simdgroup_reduction |= [ctx->device supportsFamily:MTLGPUFamilyMetal3];
  322. ctx->support_simdgroup_mm = [ctx->device supportsFamily:MTLGPUFamilyApple7];
  323. GGML_METAL_LOG_INFO("%s: simdgroup reduction support = %s\n", __func__, ctx->support_simdgroup_reduction ? "true" : "false");
  324. GGML_METAL_LOG_INFO("%s: simdgroup matrix mul. support = %s\n", __func__, ctx->support_simdgroup_mm ? "true" : "false");
  325. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  326. ctx->should_capture_next_compute = false;
  327. #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15)
  328. if (@available(macOS 10.12, iOS 16.0, *)) {
  329. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1e6);
  330. }
  331. #elif TARGET_OS_OSX
  332. if (ctx->device.maxTransferRate != 0) {
  333. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1e6);
  334. } else {
  335. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  336. }
  337. #endif
  338. // load kernels
  339. {
  340. NSError * error = nil;
  341. for (int i = 0; i < GGML_METAL_KERNEL_TYPE_COUNT; ++i) {
  342. ctx->kernels[i].pipeline = nil;
  343. }
  344. /*
  345. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) kernel->pipeline, \
  346. (int) kernel->pipeline.maxTotalThreadsPerThreadgroup, \
  347. (int) kernel->pipeline.threadExecutionWidth); \
  348. */
  349. #define GGML_METAL_ADD_KERNEL(e, name, supported) \
  350. if (supported) { \
  351. struct ggml_metal_kernel * kernel = &ctx->kernels[e]; \
  352. id<MTLFunction> metal_function = [metal_library newFunctionWithName:@"kernel_"#name]; \
  353. kernel->pipeline = [ctx->device newComputePipelineStateWithFunction:metal_function error:&error]; \
  354. [metal_function release]; \
  355. if (error) { \
  356. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  357. [metal_library release]; \
  358. return NULL; \
  359. } \
  360. } else { \
  361. GGML_METAL_LOG_WARN("%s: skipping %-32s (not supported)\n", __func__, "kernel_"#name); \
  362. }
  363. // simd_sum and simd_max requires MTLGPUFamilyApple7
  364. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ADD, add, true);
  365. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ADD_ROW, add_row, true);
  366. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL, mul, true);
  367. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_ROW, mul_row, true);
  368. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_DIV, div, true);
  369. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_DIV_ROW, div_row, true);
  370. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SCALE, scale, true);
  371. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SCALE_4, scale_4, true);
  372. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_TANH, tanh, true);
  373. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_RELU, relu, true);
  374. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GELU, gelu, true);
  375. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GELU_QUICK, gelu_quick, true);
  376. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SILU, silu, true);
  377. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SOFT_MAX, soft_max, ctx->support_simdgroup_reduction);
  378. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SOFT_MAX_4, soft_max_4, ctx->support_simdgroup_reduction);
  379. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF, diag_mask_inf, true);
  380. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF_8, diag_mask_inf_8, true);
  381. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_F32, get_rows_f32, true);
  382. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_F16, get_rows_f16, true);
  383. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_0, get_rows_q4_0, true);
  384. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_1, get_rows_q4_1, true);
  385. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_0, get_rows_q5_0, true);
  386. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_1, get_rows_q5_1, true);
  387. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q8_0, get_rows_q8_0, true);
  388. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q2_K, get_rows_q2_K, true);
  389. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q3_K, get_rows_q3_K, true);
  390. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_K, get_rows_q4_K, true);
  391. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_K, get_rows_q5_K, true);
  392. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_Q6_K, get_rows_q6_K, true);
  393. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XXS, get_rows_iq2_xxs, true);
  394. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XS, get_rows_iq2_xs, true);
  395. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ3_XXS, get_rows_iq3_xxs, true);
  396. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ1_S, get_rows_iq1_s, true);
  397. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GET_ROWS_I32, get_rows_i32, true);
  398. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_RMS_NORM, rms_norm, ctx->support_simdgroup_reduction);
  399. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_GROUP_NORM, group_norm, ctx->support_simdgroup_reduction);
  400. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_NORM, norm, true);
  401. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_F32_F32, mul_mv_f32_f32, ctx->support_simdgroup_reduction);
  402. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F16, mul_mv_f16_f16, ctx->support_simdgroup_reduction);
  403. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32, mul_mv_f16_f32, ctx->support_simdgroup_reduction);
  404. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_1ROW, mul_mv_f16_f32_1row, ctx->support_simdgroup_reduction);
  405. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_L4, mul_mv_f16_f32_l4, ctx->support_simdgroup_reduction);
  406. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_0_F32, mul_mv_q4_0_f32, ctx->support_simdgroup_reduction);
  407. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_1_F32, mul_mv_q4_1_f32, ctx->support_simdgroup_reduction);
  408. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_0_F32, mul_mv_q5_0_f32, ctx->support_simdgroup_reduction);
  409. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_1_F32, mul_mv_q5_1_f32, ctx->support_simdgroup_reduction);
  410. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q8_0_F32, mul_mv_q8_0_f32, ctx->support_simdgroup_reduction);
  411. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q2_K_F32, mul_mv_q2_K_f32, ctx->support_simdgroup_reduction);
  412. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q3_K_F32, mul_mv_q3_K_f32, ctx->support_simdgroup_reduction);
  413. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_K_F32, mul_mv_q4_K_f32, ctx->support_simdgroup_reduction);
  414. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_K_F32, mul_mv_q5_K_f32, ctx->support_simdgroup_reduction);
  415. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_Q6_K_F32, mul_mv_q6_K_f32, ctx->support_simdgroup_reduction);
  416. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XXS_F32, mul_mv_iq2_xxs_f32, ctx->support_simdgroup_reduction);
  417. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XS_F32, mul_mv_iq2_xs_f32, ctx->support_simdgroup_reduction);
  418. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_IQ3_XXS_F32, mul_mv_iq3_xxs_f32, ctx->support_simdgroup_reduction);
  419. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_IQ1_S_F32, mul_mv_iq1_s_f32, ctx->support_simdgroup_reduction);
  420. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F32_F32, mul_mv_id_f32_f32, ctx->support_simdgroup_reduction);
  421. //GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F16, mul_mv_id_f16_f16, ctx->support_simdgroup_reduction);
  422. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32, mul_mv_id_f16_f32, ctx->support_simdgroup_reduction);
  423. //GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32_1ROW, mul_mv_id_f16_f32_1row, ctx->support_simdgroup_reduction);
  424. //GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32_L4, mul_mv_id_f16_f32_l4, ctx->support_simdgroup_reduction);
  425. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_0_F32, mul_mv_id_q4_0_f32, ctx->support_simdgroup_reduction);
  426. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_1_F32, mul_mv_id_q4_1_f32, ctx->support_simdgroup_reduction);
  427. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_0_F32, mul_mv_id_q5_0_f32, ctx->support_simdgroup_reduction);
  428. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_1_F32, mul_mv_id_q5_1_f32, ctx->support_simdgroup_reduction);
  429. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q8_0_F32, mul_mv_id_q8_0_f32, ctx->support_simdgroup_reduction);
  430. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q2_K_F32, mul_mv_id_q2_K_f32, ctx->support_simdgroup_reduction);
  431. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q3_K_F32, mul_mv_id_q3_K_f32, ctx->support_simdgroup_reduction);
  432. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_K_F32, mul_mv_id_q4_K_f32, ctx->support_simdgroup_reduction);
  433. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_K_F32, mul_mv_id_q5_K_f32, ctx->support_simdgroup_reduction);
  434. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q6_K_F32, mul_mv_id_q6_K_f32, ctx->support_simdgroup_reduction);
  435. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XXS_F32, mul_mv_id_iq2_xxs_f32, ctx->support_simdgroup_reduction);
  436. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XS_F32, mul_mv_id_iq2_xs_f32, ctx->support_simdgroup_reduction);
  437. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ3_XXS_F32, mul_mv_id_iq3_xxs_f32, ctx->support_simdgroup_reduction);
  438. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ1_S_F32, mul_mv_id_iq1_s_f32, ctx->support_simdgroup_reduction);
  439. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_F32_F32, mul_mm_f32_f32, ctx->support_simdgroup_mm);
  440. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_F16_F32, mul_mm_f16_f32, ctx->support_simdgroup_mm);
  441. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_0_F32, mul_mm_q4_0_f32, ctx->support_simdgroup_mm);
  442. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_1_F32, mul_mm_q4_1_f32, ctx->support_simdgroup_mm);
  443. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_0_F32, mul_mm_q5_0_f32, ctx->support_simdgroup_mm);
  444. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_1_F32, mul_mm_q5_1_f32, ctx->support_simdgroup_mm);
  445. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q8_0_F32, mul_mm_q8_0_f32, ctx->support_simdgroup_mm);
  446. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q2_K_F32, mul_mm_q2_K_f32, ctx->support_simdgroup_mm);
  447. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q3_K_F32, mul_mm_q3_K_f32, ctx->support_simdgroup_mm);
  448. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_K_F32, mul_mm_q4_K_f32, ctx->support_simdgroup_mm);
  449. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_K_F32, mul_mm_q5_K_f32, ctx->support_simdgroup_mm);
  450. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_Q6_K_F32, mul_mm_q6_K_f32, ctx->support_simdgroup_mm);
  451. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XXS_F32, mul_mm_iq2_xxs_f32, ctx->support_simdgroup_mm);
  452. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XS_F32, mul_mm_iq2_xs_f32, ctx->support_simdgroup_mm);
  453. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_IQ3_XXS_F32, mul_mm_iq3_xxs_f32, ctx->support_simdgroup_mm);
  454. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_IQ1_S_F32, mul_mm_iq1_s_f32, ctx->support_simdgroup_mm);
  455. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F32_F32, mul_mm_id_f32_f32, ctx->support_simdgroup_mm);
  456. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F16_F32, mul_mm_id_f16_f32, ctx->support_simdgroup_mm);
  457. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_0_F32, mul_mm_id_q4_0_f32, ctx->support_simdgroup_mm);
  458. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_1_F32, mul_mm_id_q4_1_f32, ctx->support_simdgroup_mm);
  459. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_0_F32, mul_mm_id_q5_0_f32, ctx->support_simdgroup_mm);
  460. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_1_F32, mul_mm_id_q5_1_f32, ctx->support_simdgroup_mm);
  461. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q8_0_F32, mul_mm_id_q8_0_f32, ctx->support_simdgroup_mm);
  462. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q2_K_F32, mul_mm_id_q2_K_f32, ctx->support_simdgroup_mm);
  463. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q3_K_F32, mul_mm_id_q3_K_f32, ctx->support_simdgroup_mm);
  464. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_K_F32, mul_mm_id_q4_K_f32, ctx->support_simdgroup_mm);
  465. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_K_F32, mul_mm_id_q5_K_f32, ctx->support_simdgroup_mm);
  466. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q6_K_F32, mul_mm_id_q6_K_f32, ctx->support_simdgroup_mm);
  467. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XXS_F32, mul_mm_id_iq2_xxs_f32, ctx->support_simdgroup_mm);
  468. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XS_F32, mul_mm_id_iq2_xs_f32, ctx->support_simdgroup_mm);
  469. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ3_XXS_F32, mul_mm_id_iq3_xxs_f32, ctx->support_simdgroup_mm);
  470. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ1_S_F32, mul_mm_id_iq1_s_f32, ctx->support_simdgroup_mm);
  471. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ROPE_F32, rope_f32, true);
  472. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ROPE_F16, rope_f16, true);
  473. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ALIBI_F32, alibi_f32, true);
  474. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_IM2COL_F16, im2col_f16, true);
  475. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_IM2COL_F32, im2col_f32, true);
  476. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_UPSCALE_F32, upscale_f32, true);
  477. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_PAD_F32, pad_f32, true);
  478. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_ASC, argsort_f32_i32_asc, true);
  479. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_DESC, argsort_f32_i32_desc, true);
  480. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_LEAKY_RELU_F32, leaky_relu_f32, true);
  481. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_F16, cpy_f32_f16, true);
  482. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_F32, cpy_f32_f32, true);
  483. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_Q8_0, cpy_f32_q8_0, true);
  484. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_0, cpy_f32_q4_0, true);
  485. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_1, cpy_f32_q4_1, true);
  486. //GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_0, cpy_f32_q5_0, true);
  487. //GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_1, cpy_f32_q5_1, true);
  488. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F16_F16, cpy_f16_f16, true);
  489. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CPY_F16_F32, cpy_f16_f32, true);
  490. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_CONCAT, concat, true);
  491. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SQR, sqr, true);
  492. GGML_METAL_ADD_KERNEL(GGML_METAL_KERNEL_TYPE_SUM_ROWS, sum_rows, true);
  493. }
  494. [metal_library release];
  495. return ctx;
  496. }
  497. static void ggml_metal_free(struct ggml_metal_context * ctx) {
  498. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  499. for (int i = 0; i < GGML_METAL_KERNEL_TYPE_COUNT; ++i) {
  500. [ctx->kernels[i].pipeline release];
  501. }
  502. [ctx->queue release];
  503. [ctx->device release];
  504. dispatch_release(ctx->d_queue);
  505. free(ctx);
  506. }
  507. // temporarily defined here for compatibility between ggml-backend and the old API
  508. struct ggml_backend_metal_buffer {
  509. void * data;
  510. size_t size;
  511. id<MTLBuffer> metal;
  512. };
  513. struct ggml_backend_metal_buffer_context {
  514. void * all_data;
  515. size_t all_size;
  516. bool owned;
  517. // multiple buffers are used only to avoid the maximum buffer size limitation when using mmap
  518. int n_buffers;
  519. struct ggml_backend_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  520. };
  521. // finds the Metal buffer that contains the tensor data on the GPU device
  522. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  523. // Metal buffer based on the host memory pointer
  524. //
  525. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_tensor * t, size_t * offs) {
  526. //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);
  527. const int64_t tsize = ggml_nbytes(t);
  528. ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
  529. struct ggml_backend_metal_buffer_context * buf_ctx = (struct ggml_backend_metal_buffer_context *) buffer->context;
  530. // find the view that contains the tensor fully
  531. for (int i = 0; i < buf_ctx->n_buffers; ++i) {
  532. const int64_t ioffs = (int64_t) t->data - (int64_t) buf_ctx->buffers[i].data;
  533. //GGML_METAL_LOG_INFO("ioffs = %10ld, tsize = %10ld, sum = %10ld, buf_ctx->buffers[%d].size = %10ld\n", ioffs, tsize, ioffs + tsize, i, buf_ctx->buffers[i].size);
  534. if (ioffs >= 0 && ioffs + tsize <= (int64_t) buf_ctx->buffers[i].size) {
  535. *offs = (size_t) ioffs;
  536. //GGML_METAL_LOG_INFO("%s: tensor '%16s', offs = %8ld\n", __func__, t->name, *offs);
  537. return buf_ctx->buffers[i].metal;
  538. }
  539. }
  540. GGML_METAL_LOG_ERROR("%s: error: tensor '%s' buffer is nil\n", __func__, t->name);
  541. return nil;
  542. }
  543. static bool ggml_metal_supports_op(const struct ggml_metal_context * ctx, const struct ggml_tensor * op) {
  544. switch (op->op) {
  545. case GGML_OP_UNARY:
  546. switch (ggml_get_unary_op(op)) {
  547. case GGML_UNARY_OP_TANH:
  548. case GGML_UNARY_OP_RELU:
  549. case GGML_UNARY_OP_GELU:
  550. case GGML_UNARY_OP_GELU_QUICK:
  551. case GGML_UNARY_OP_SILU:
  552. return true;
  553. default:
  554. return false;
  555. }
  556. case GGML_OP_NONE:
  557. case GGML_OP_RESHAPE:
  558. case GGML_OP_VIEW:
  559. case GGML_OP_TRANSPOSE:
  560. case GGML_OP_PERMUTE:
  561. case GGML_OP_CONCAT:
  562. case GGML_OP_ADD:
  563. case GGML_OP_ACC:
  564. case GGML_OP_MUL:
  565. case GGML_OP_DIV:
  566. case GGML_OP_SCALE:
  567. case GGML_OP_SQR:
  568. case GGML_OP_SUM_ROWS:
  569. return true;
  570. case GGML_OP_SOFT_MAX:
  571. case GGML_OP_RMS_NORM:
  572. case GGML_OP_GROUP_NORM:
  573. return ctx->support_simdgroup_reduction;
  574. case GGML_OP_NORM:
  575. case GGML_OP_ALIBI:
  576. case GGML_OP_ROPE:
  577. case GGML_OP_IM2COL:
  578. return true;
  579. case GGML_OP_POOL_1D:
  580. case GGML_OP_POOL_2D:
  581. return false;
  582. case GGML_OP_UPSCALE:
  583. case GGML_OP_PAD:
  584. case GGML_OP_ARGSORT:
  585. case GGML_OP_LEAKY_RELU:
  586. return true;
  587. case GGML_OP_MUL_MAT:
  588. case GGML_OP_MUL_MAT_ID:
  589. return ctx->support_simdgroup_reduction &&
  590. (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F32);
  591. case GGML_OP_CPY:
  592. case GGML_OP_DUP:
  593. case GGML_OP_CONT:
  594. {
  595. switch (op->src[0]->type) {
  596. case GGML_TYPE_F32:
  597. switch (op->type) {
  598. case GGML_TYPE_F16:
  599. case GGML_TYPE_F32:
  600. case GGML_TYPE_Q8_0:
  601. case GGML_TYPE_Q4_0:
  602. case GGML_TYPE_Q4_1:
  603. return true;
  604. default:
  605. return false;
  606. }
  607. case GGML_TYPE_F16:
  608. switch (op->type) {
  609. case GGML_TYPE_F16:
  610. case GGML_TYPE_F32:
  611. return true;
  612. default:
  613. return false;
  614. }
  615. default:
  616. return false;
  617. };
  618. }
  619. case GGML_OP_DIAG_MASK_INF:
  620. case GGML_OP_GET_ROWS:
  621. {
  622. return op->ne[3] == 1;
  623. }
  624. default:
  625. return false;
  626. }
  627. }
  628. static bool ggml_metal_graph_compute(
  629. struct ggml_metal_context * ctx,
  630. struct ggml_cgraph * gf) {
  631. @autoreleasepool {
  632. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  633. edesc.dispatchType = MTLDispatchTypeSerial;
  634. // create multiple command buffers and enqueue them
  635. // then, we encode the graph into the command buffers in parallel
  636. const int n_nodes = gf->n_nodes;
  637. const int n_cb = ctx->n_cb;
  638. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  639. const bool should_capture = ctx->should_capture_next_compute;
  640. if (should_capture) {
  641. ctx->should_capture_next_compute = false;
  642. MTLCaptureDescriptor * descriptor = [MTLCaptureDescriptor new];
  643. descriptor.captureObject = ctx->queue;
  644. NSError * error = nil;
  645. if (![[MTLCaptureManager sharedCaptureManager] startCaptureWithDescriptor:descriptor error:&error]) {
  646. GGML_METAL_LOG_ERROR("%s: error: unable to start capture '%s'\n", __func__, [[error localizedDescription] UTF8String]);
  647. GGML_ASSERT(!"capture failed");
  648. }
  649. }
  650. id<MTLCommandBuffer> command_buffer_builder[n_cb];
  651. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  652. id<MTLCommandBuffer> command_buffer = [ctx->queue commandBufferWithUnretainedReferences];
  653. command_buffer_builder[cb_idx] = command_buffer;
  654. // enqueue the command buffers in order to specify their execution order
  655. [command_buffer enqueue];
  656. }
  657. const id<MTLCommandBuffer> *command_buffers = command_buffer_builder;
  658. dispatch_apply(n_cb, ctx->d_queue, ^(size_t iter) {
  659. const int cb_idx = iter;
  660. size_t offs_src0 = 0;
  661. size_t offs_src1 = 0;
  662. size_t offs_src2 = 0;
  663. size_t offs_dst = 0;
  664. id<MTLCommandBuffer> command_buffer = command_buffers[cb_idx];
  665. id<MTLComputeCommandEncoder> encoder = [command_buffer computeCommandEncoderWithDescriptor: edesc];
  666. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  667. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  668. for (int i = node_start; i < node_end; ++i) {
  669. if (i == -1) {
  670. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  671. continue;
  672. }
  673. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  674. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  675. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  676. struct ggml_tensor * src2 = gf->nodes[i]->src[2];
  677. struct ggml_tensor * dst = gf->nodes[i];
  678. switch (dst->op) {
  679. case GGML_OP_NONE:
  680. case GGML_OP_RESHAPE:
  681. case GGML_OP_VIEW:
  682. case GGML_OP_TRANSPOSE:
  683. case GGML_OP_PERMUTE:
  684. {
  685. // noop -> next node
  686. } continue;
  687. default:
  688. {
  689. } break;
  690. }
  691. if (!ggml_metal_supports_op(ctx, dst)) {
  692. GGML_METAL_LOG_ERROR("%s: error: unsupported op '%s'\n", __func__, ggml_op_desc(dst));
  693. GGML_ASSERT(!"unsupported op");
  694. }
  695. if (should_capture) {
  696. [encoder pushDebugGroup:[NSString stringWithCString:ggml_op_desc(dst) encoding:NSUTF8StringEncoding]];
  697. }
  698. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  699. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  700. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  701. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  702. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  703. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  704. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  705. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  706. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  707. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  708. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  709. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  710. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  711. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  712. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  713. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  714. const int64_t ne0 = dst ? dst->ne[0] : 0;
  715. const int64_t ne1 = dst ? dst->ne[1] : 0;
  716. const int64_t ne2 = dst ? dst->ne[2] : 0;
  717. const int64_t ne3 = dst ? dst->ne[3] : 0;
  718. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  719. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  720. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  721. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  722. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  723. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  724. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  725. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(src0, &offs_src0) : nil;
  726. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(src1, &offs_src1) : nil;
  727. id<MTLBuffer> id_src2 = src2 ? ggml_metal_get_buffer(src2, &offs_src2) : nil;
  728. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(dst, &offs_dst) : nil;
  729. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  730. //if (src0) {
  731. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  732. // ggml_is_contiguous(src0), src0->name);
  733. //}
  734. //if (src1) {
  735. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  736. // ggml_is_contiguous(src1), src1->name);
  737. //}
  738. //if (dst) {
  739. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  740. // dst->name);
  741. //}
  742. switch (dst->op) {
  743. case GGML_OP_CONCAT:
  744. {
  745. const int64_t nb = ne00;
  746. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CONCAT].pipeline;
  747. [encoder setComputePipelineState:pipeline];
  748. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  749. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  750. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  751. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  752. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  753. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  754. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  755. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  756. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  757. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  758. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  759. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  760. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  761. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  762. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  763. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  764. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  765. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  766. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  767. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  768. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  769. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  770. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  771. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  772. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  773. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  774. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  775. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  776. const int nth = MIN(1024, ne0);
  777. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  778. } break;
  779. case GGML_OP_ADD:
  780. case GGML_OP_MUL:
  781. case GGML_OP_DIV:
  782. {
  783. const size_t offs = 0;
  784. bool bcast_row = false;
  785. int64_t nb = ne00;
  786. id<MTLComputePipelineState> pipeline = nil;
  787. if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) {
  788. GGML_ASSERT(ggml_is_contiguous(src0));
  789. // src1 is a row
  790. GGML_ASSERT(ne11 == 1);
  791. nb = ne00 / 4;
  792. switch (dst->op) {
  793. case GGML_OP_ADD: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ADD_ROW].pipeline; break;
  794. case GGML_OP_MUL: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_ROW].pipeline; break;
  795. case GGML_OP_DIV: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_DIV_ROW].pipeline; break;
  796. default: GGML_ASSERT(false);
  797. }
  798. bcast_row = true;
  799. } else {
  800. switch (dst->op) {
  801. case GGML_OP_ADD: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ADD].pipeline; break;
  802. case GGML_OP_MUL: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL].pipeline; break;
  803. case GGML_OP_DIV: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_DIV].pipeline; break;
  804. default: GGML_ASSERT(false);
  805. }
  806. }
  807. [encoder setComputePipelineState:pipeline];
  808. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  809. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  810. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  811. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  812. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  813. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  814. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  815. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  816. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  817. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  818. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  819. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  820. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  821. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  822. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  823. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  824. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  825. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  826. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  827. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  828. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  829. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  830. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  831. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  832. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  833. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  834. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  835. [encoder setBytes:&offs length:sizeof(offs) atIndex:27];
  836. [encoder setBytes:&nb length:sizeof(nb) atIndex:28];
  837. if (bcast_row) {
  838. const int64_t n = ggml_nelements(dst)/4;
  839. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  840. } else {
  841. const int nth = MIN((int) pipeline.maxTotalThreadsPerThreadgroup, ne0);
  842. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  843. }
  844. } break;
  845. case GGML_OP_ACC:
  846. {
  847. GGML_ASSERT(src0t == GGML_TYPE_F32);
  848. GGML_ASSERT(src1t == GGML_TYPE_F32);
  849. GGML_ASSERT(dstt == GGML_TYPE_F32);
  850. GGML_ASSERT(ggml_is_contiguous(src0));
  851. GGML_ASSERT(ggml_is_contiguous(src1));
  852. const size_t pnb1 = ((int32_t *) dst->op_params)[0];
  853. const size_t pnb2 = ((int32_t *) dst->op_params)[1];
  854. const size_t pnb3 = ((int32_t *) dst->op_params)[2];
  855. const size_t offs = ((int32_t *) dst->op_params)[3];
  856. const bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  857. if (!inplace) {
  858. // run a separete kernel to cpy src->dst
  859. // not sure how to avoid this
  860. // TODO: make a simpler cpy_bytes kernel
  861. const id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_F32].pipeline;
  862. [encoder setComputePipelineState:pipeline];
  863. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  864. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  865. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  866. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  867. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  868. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  869. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  870. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  871. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  872. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  873. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  874. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  875. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  876. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  877. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  878. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  879. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  880. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  881. const int nth = MIN((int) pipeline.maxTotalThreadsPerThreadgroup, ne00);
  882. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  883. }
  884. const id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ADD].pipeline;
  885. [encoder setComputePipelineState:pipeline];
  886. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  887. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  888. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  889. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  890. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  891. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  892. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  893. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  894. [encoder setBytes:&pnb1 length:sizeof(pnb1) atIndex:8];
  895. [encoder setBytes:&pnb2 length:sizeof(pnb2) atIndex:9];
  896. [encoder setBytes:&pnb3 length:sizeof(pnb3) atIndex:10];
  897. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  898. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  899. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  900. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  901. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  902. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  903. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  904. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  905. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  906. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  907. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  908. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  909. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  910. [encoder setBytes:&pnb1 length:sizeof(pnb1) atIndex:24];
  911. [encoder setBytes:&pnb2 length:sizeof(pnb2) atIndex:25];
  912. [encoder setBytes:&pnb3 length:sizeof(pnb3) atIndex:26];
  913. [encoder setBytes:&offs length:sizeof(offs) atIndex:27];
  914. const int nth = MIN((int) pipeline.maxTotalThreadsPerThreadgroup, ne00);
  915. [encoder dispatchThreadgroups:MTLSizeMake(ne11, ne12, ne13) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  916. } break;
  917. case GGML_OP_SCALE:
  918. {
  919. GGML_ASSERT(ggml_is_contiguous(src0));
  920. const float scale = *(const float *) dst->op_params;
  921. int64_t n = ggml_nelements(dst);
  922. id<MTLComputePipelineState> pipeline = nil;
  923. if (n % 4 == 0) {
  924. n /= 4;
  925. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SCALE_4].pipeline;
  926. } else {
  927. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SCALE].pipeline;
  928. }
  929. [encoder setComputePipelineState:pipeline];
  930. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  931. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  932. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  933. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  934. } break;
  935. case GGML_OP_UNARY:
  936. switch (ggml_get_unary_op(gf->nodes[i])) {
  937. case GGML_UNARY_OP_TANH:
  938. {
  939. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_TANH].pipeline;
  940. [encoder setComputePipelineState:pipeline];
  941. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  942. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  943. const int64_t n = ggml_nelements(dst);
  944. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  945. } break;
  946. case GGML_UNARY_OP_RELU:
  947. {
  948. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_RELU].pipeline;
  949. [encoder setComputePipelineState:pipeline];
  950. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  951. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  952. const int64_t n = ggml_nelements(dst);
  953. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  954. } break;
  955. case GGML_UNARY_OP_GELU:
  956. {
  957. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GELU].pipeline;
  958. [encoder setComputePipelineState:pipeline];
  959. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  960. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  961. const int64_t n = ggml_nelements(dst);
  962. GGML_ASSERT(n % 4 == 0);
  963. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  964. } break;
  965. case GGML_UNARY_OP_GELU_QUICK:
  966. {
  967. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GELU_QUICK].pipeline;
  968. [encoder setComputePipelineState:pipeline];
  969. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  970. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  971. const int64_t n = ggml_nelements(dst);
  972. GGML_ASSERT(n % 4 == 0);
  973. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  974. } break;
  975. case GGML_UNARY_OP_SILU:
  976. {
  977. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SILU].pipeline;
  978. [encoder setComputePipelineState:pipeline];
  979. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  980. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  981. const int64_t n = ggml_nelements(dst);
  982. GGML_ASSERT(n % 4 == 0);
  983. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  984. } break;
  985. default:
  986. {
  987. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  988. GGML_ASSERT(false);
  989. }
  990. } break;
  991. case GGML_OP_SQR:
  992. {
  993. GGML_ASSERT(ggml_is_contiguous(src0));
  994. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SQR].pipeline;
  995. [encoder setComputePipelineState:pipeline];
  996. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  997. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  998. const int64_t n = ggml_nelements(dst);
  999. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1000. } break;
  1001. case GGML_OP_SUM_ROWS:
  1002. {
  1003. GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type));
  1004. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SUM_ROWS].pipeline;
  1005. [encoder setComputePipelineState:pipeline];
  1006. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1007. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1008. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1009. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1010. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1011. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1012. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1013. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1014. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1015. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1016. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:10];
  1017. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:11];
  1018. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:12];
  1019. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:13];
  1020. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:14];
  1021. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:15];
  1022. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:16];
  1023. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:17];
  1024. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:18];
  1025. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:19];
  1026. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:20];
  1027. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:21];
  1028. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:22];
  1029. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:23];
  1030. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:24];
  1031. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:25];
  1032. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1033. } break;
  1034. case GGML_OP_SOFT_MAX:
  1035. {
  1036. int nth = 32; // SIMD width
  1037. id<MTLComputePipelineState> pipeline = nil;
  1038. if (ne00%4 == 0) {
  1039. while (nth < ne00/4 && nth < 256) {
  1040. nth *= 2;
  1041. }
  1042. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SOFT_MAX_4].pipeline;
  1043. } else {
  1044. while (nth < ne00 && nth < 1024) {
  1045. nth *= 2;
  1046. }
  1047. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_SOFT_MAX].pipeline;
  1048. }
  1049. const float scale = ((float *) dst->op_params)[0];
  1050. const float max_bias = ((float *) dst->op_params)[1];
  1051. const int64_t nrows_x = ggml_nrows(src0);
  1052. const int64_t nrows_y = src0->ne[1];
  1053. const uint32_t n_head_kv = nrows_x/nrows_y;
  1054. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  1055. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  1056. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  1057. [encoder setComputePipelineState:pipeline];
  1058. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1059. if (id_src1) {
  1060. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1061. } else {
  1062. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:1];
  1063. }
  1064. if (id_src2) {
  1065. [encoder setBuffer:id_src2 offset:offs_src2 atIndex:2];
  1066. } else {
  1067. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:2];
  1068. }
  1069. [encoder setBuffer:id_dst offset:offs_dst atIndex:3];
  1070. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:4];
  1071. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:5];
  1072. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:6];
  1073. [encoder setBytes:&scale length:sizeof(scale) atIndex:7];
  1074. [encoder setBytes:&max_bias length:sizeof(max_bias) atIndex:8];
  1075. [encoder setBytes:&m0 length:sizeof(m0) atIndex:9];
  1076. [encoder setBytes:&m1 length:sizeof(m1) atIndex:10];
  1077. [encoder setBytes:&n_head_log2 length:sizeof(n_head_log2) atIndex:11];
  1078. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1079. [encoder dispatchThreadgroups:MTLSizeMake(ne01*ne02*ne03, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1080. } break;
  1081. case GGML_OP_DIAG_MASK_INF:
  1082. {
  1083. const int n_past = ((int32_t *)(dst->op_params))[0];
  1084. id<MTLComputePipelineState> pipeline = nil;
  1085. if (ne00%8 == 0) {
  1086. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF_8].pipeline;
  1087. } else {
  1088. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_DIAG_MASK_INF].pipeline;
  1089. }
  1090. [encoder setComputePipelineState:pipeline];
  1091. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1092. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1093. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1094. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1095. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  1096. if (ne00%8 == 0) {
  1097. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1098. }
  1099. else {
  1100. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1101. }
  1102. } break;
  1103. case GGML_OP_MUL_MAT:
  1104. {
  1105. GGML_ASSERT(ne00 == ne10);
  1106. // TODO: assert that dim2 and dim3 are contiguous
  1107. GGML_ASSERT(ne12 % ne02 == 0);
  1108. GGML_ASSERT(ne13 % ne03 == 0);
  1109. const uint r2 = ne12/ne02;
  1110. const uint r3 = ne13/ne03;
  1111. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  1112. // to the matrix-vector kernel
  1113. int ne11_mm_min = 1;
  1114. #if 0
  1115. // the numbers below are measured on M2 Ultra for 7B and 13B models
  1116. // these numbers do not translate to other devices or model sizes
  1117. // TODO: need to find a better approach
  1118. if ([ctx->device.name isEqualToString:@"Apple M2 Ultra"]) {
  1119. switch (src0t) {
  1120. case GGML_TYPE_F16: ne11_mm_min = 2; break;
  1121. case GGML_TYPE_Q8_0: ne11_mm_min = 7; break;
  1122. case GGML_TYPE_Q2_K: ne11_mm_min = 15; break;
  1123. case GGML_TYPE_Q3_K: ne11_mm_min = 7; break;
  1124. case GGML_TYPE_Q4_0:
  1125. case GGML_TYPE_Q4_1: ne11_mm_min = 15; break;
  1126. case GGML_TYPE_Q4_K: ne11_mm_min = 11; break;
  1127. case GGML_TYPE_Q5_0: // not tested yet
  1128. case GGML_TYPE_Q5_1: ne11_mm_min = 13; break; // not tested yet
  1129. case GGML_TYPE_Q5_K: ne11_mm_min = 7; break;
  1130. case GGML_TYPE_Q6_K: ne11_mm_min = 7; break;
  1131. default: ne11_mm_min = 1; break;
  1132. }
  1133. }
  1134. #endif
  1135. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  1136. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  1137. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  1138. !ggml_is_transposed(src0) &&
  1139. !ggml_is_transposed(src1) &&
  1140. src1t == GGML_TYPE_F32 &&
  1141. ne00 % 32 == 0 && ne00 >= 64 &&
  1142. (ne11 > ne11_mm_min || (ggml_is_quantized(src0t) && ne12 > 1))) {
  1143. //printf("matrix: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1144. id<MTLComputePipelineState> pipeline = nil;
  1145. switch (src0->type) {
  1146. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_F32_F32 ].pipeline; break;
  1147. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_F16_F32 ].pipeline; break;
  1148. case GGML_TYPE_Q4_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_0_F32 ].pipeline; break;
  1149. case GGML_TYPE_Q4_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_1_F32 ].pipeline; break;
  1150. case GGML_TYPE_Q5_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_0_F32 ].pipeline; break;
  1151. case GGML_TYPE_Q5_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_1_F32 ].pipeline; break;
  1152. case GGML_TYPE_Q8_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q8_0_F32 ].pipeline; break;
  1153. case GGML_TYPE_Q2_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q2_K_F32 ].pipeline; break;
  1154. case GGML_TYPE_Q3_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q3_K_F32 ].pipeline; break;
  1155. case GGML_TYPE_Q4_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q4_K_F32 ].pipeline; break;
  1156. case GGML_TYPE_Q5_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q5_K_F32 ].pipeline; break;
  1157. case GGML_TYPE_Q6_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_Q6_K_F32 ].pipeline; break;
  1158. case GGML_TYPE_IQ2_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XXS_F32].pipeline; break;
  1159. case GGML_TYPE_IQ2_XS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_IQ2_XS_F32 ].pipeline; break;
  1160. case GGML_TYPE_IQ3_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_IQ3_XXS_F32].pipeline; break;
  1161. case GGML_TYPE_IQ1_S: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_IQ1_S_F32 ].pipeline; break;
  1162. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  1163. }
  1164. [encoder setComputePipelineState:pipeline];
  1165. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1166. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1167. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1168. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1169. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1170. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  1171. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  1172. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  1173. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  1174. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  1175. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  1176. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  1177. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  1178. [encoder setBytes:&r2 length:sizeof(r2) atIndex:13];
  1179. [encoder setBytes:&r3 length:sizeof(r3) atIndex:14];
  1180. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  1181. [encoder dispatchThreadgroups:MTLSizeMake( (ne11 + 31)/32, (ne01 + 63)/64, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  1182. } else {
  1183. int nth0 = 32;
  1184. int nth1 = 1;
  1185. int nrows = 1;
  1186. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1187. id<MTLComputePipelineState> pipeline = nil;
  1188. // use custom matrix x vector kernel
  1189. switch (src0t) {
  1190. case GGML_TYPE_F32:
  1191. {
  1192. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1193. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_F32_F32].pipeline;
  1194. nrows = 4;
  1195. } break;
  1196. case GGML_TYPE_F16:
  1197. {
  1198. nth0 = 32;
  1199. nth1 = 1;
  1200. if (src1t == GGML_TYPE_F32) {
  1201. if (ne11 * ne12 < 4) {
  1202. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_1ROW].pipeline;
  1203. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  1204. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32_L4].pipeline;
  1205. nrows = ne11;
  1206. } else {
  1207. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F32].pipeline;
  1208. nrows = 4;
  1209. }
  1210. } else {
  1211. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_F16_F16].pipeline;
  1212. nrows = 4;
  1213. }
  1214. } break;
  1215. case GGML_TYPE_Q4_0:
  1216. {
  1217. nth0 = 8;
  1218. nth1 = 8;
  1219. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_0_F32].pipeline;
  1220. } break;
  1221. case GGML_TYPE_Q4_1:
  1222. {
  1223. nth0 = 8;
  1224. nth1 = 8;
  1225. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_1_F32].pipeline;
  1226. } break;
  1227. case GGML_TYPE_Q5_0:
  1228. {
  1229. nth0 = 8;
  1230. nth1 = 8;
  1231. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_0_F32].pipeline;
  1232. } break;
  1233. case GGML_TYPE_Q5_1:
  1234. {
  1235. nth0 = 8;
  1236. nth1 = 8;
  1237. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_1_F32].pipeline;
  1238. } break;
  1239. case GGML_TYPE_Q8_0:
  1240. {
  1241. nth0 = 8;
  1242. nth1 = 8;
  1243. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q8_0_F32].pipeline;
  1244. } break;
  1245. case GGML_TYPE_Q2_K:
  1246. {
  1247. nth0 = 2;
  1248. nth1 = 32;
  1249. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q2_K_F32].pipeline;
  1250. } break;
  1251. case GGML_TYPE_Q3_K:
  1252. {
  1253. nth0 = 2;
  1254. nth1 = 32;
  1255. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q3_K_F32].pipeline;
  1256. } break;
  1257. case GGML_TYPE_Q4_K:
  1258. {
  1259. nth0 = 4; //1;
  1260. nth1 = 8; //32;
  1261. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q4_K_F32].pipeline;
  1262. } break;
  1263. case GGML_TYPE_Q5_K:
  1264. {
  1265. nth0 = 2;
  1266. nth1 = 32;
  1267. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q5_K_F32].pipeline;
  1268. } break;
  1269. case GGML_TYPE_Q6_K:
  1270. {
  1271. nth0 = 2;
  1272. nth1 = 32;
  1273. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_Q6_K_F32].pipeline;
  1274. } break;
  1275. case GGML_TYPE_IQ2_XXS:
  1276. {
  1277. nth0 = 4;
  1278. nth1 = 16;
  1279. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XXS_F32].pipeline;
  1280. } break;
  1281. case GGML_TYPE_IQ2_XS:
  1282. {
  1283. nth0 = 4;
  1284. nth1 = 16;
  1285. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_IQ2_XS_F32].pipeline;
  1286. } break;
  1287. case GGML_TYPE_IQ3_XXS:
  1288. {
  1289. nth0 = 4;
  1290. nth1 = 16;
  1291. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_IQ3_XXS_F32].pipeline;
  1292. } break;
  1293. case GGML_TYPE_IQ1_S:
  1294. {
  1295. nth0 = 4;
  1296. nth1 = 16;
  1297. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_IQ1_S_F32].pipeline;
  1298. } break;
  1299. default:
  1300. {
  1301. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  1302. GGML_ASSERT(false && "not implemented");
  1303. }
  1304. };
  1305. if (ggml_is_quantized(src0t)) {
  1306. GGML_ASSERT(ne00 >= nth0*nth1);
  1307. }
  1308. [encoder setComputePipelineState:pipeline];
  1309. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1310. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1311. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1312. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1313. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1314. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1315. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1316. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1317. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1318. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  1319. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  1320. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  1321. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  1322. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  1323. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  1324. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  1325. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  1326. [encoder setBytes:&r2 length:sizeof(r2) atIndex:17];
  1327. [encoder setBytes:&r3 length:sizeof(r3) atIndex:18];
  1328. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 ||
  1329. src0t == GGML_TYPE_Q5_0 || src0t == GGML_TYPE_Q5_1 || src0t == GGML_TYPE_Q8_0 ||
  1330. src0t == GGML_TYPE_Q2_K || src0t == GGML_TYPE_IQ1_S) { // || src0t == GGML_TYPE_Q4_K) {
  1331. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1332. }
  1333. else if (src0t == GGML_TYPE_IQ2_XXS || src0t == GGML_TYPE_IQ2_XS) {
  1334. const int mem_size = src0t == GGML_TYPE_IQ2_XXS ? 256*8+128 : 512*8+128;
  1335. [encoder setThreadgroupMemoryLength:mem_size atIndex:0];
  1336. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1337. }
  1338. else if (src0t == GGML_TYPE_IQ3_XXS) {
  1339. const int mem_size = 256*4+128;
  1340. [encoder setThreadgroupMemoryLength:mem_size atIndex:0];
  1341. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1342. }
  1343. else if (src0t == GGML_TYPE_Q4_K) {
  1344. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1345. }
  1346. else if (src0t == GGML_TYPE_Q3_K) {
  1347. #ifdef GGML_QKK_64
  1348. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1349. #else
  1350. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1351. #endif
  1352. }
  1353. else if (src0t == GGML_TYPE_Q5_K) {
  1354. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1355. }
  1356. else if (src0t == GGML_TYPE_Q6_K) {
  1357. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1358. } else {
  1359. const int64_t ny = (ne11 + nrows - 1)/nrows;
  1360. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1361. }
  1362. }
  1363. } break;
  1364. case GGML_OP_MUL_MAT_ID:
  1365. {
  1366. //GGML_ASSERT(ne00 == ne10);
  1367. //GGML_ASSERT(ne03 == ne13);
  1368. GGML_ASSERT(src0t == GGML_TYPE_I32);
  1369. const int n_as = ((int32_t *) dst->op_params)[1];
  1370. // TODO: make this more general
  1371. GGML_ASSERT(n_as <= 8);
  1372. // max size of the src1ids array in the kernel stack
  1373. GGML_ASSERT(ne11 <= 512);
  1374. const int64_t ne20 = src2 ? src2->ne[0] : 0;
  1375. const int64_t ne21 = src2 ? src2->ne[1] : 0;
  1376. const int64_t ne22 = src2 ? src2->ne[2] : 0;
  1377. const int64_t ne23 = src2 ? src2->ne[3] : 0; GGML_UNUSED(ne23);
  1378. const uint64_t nb20 = src2 ? src2->nb[0] : 0; GGML_UNUSED(nb20);
  1379. const uint64_t nb21 = src2 ? src2->nb[1] : 0;
  1380. const uint64_t nb22 = src2 ? src2->nb[2] : 0;
  1381. const uint64_t nb23 = src2 ? src2->nb[3] : 0; GGML_UNUSED(nb23);
  1382. const enum ggml_type src2t = src2 ? src2->type : GGML_TYPE_COUNT; GGML_UNUSED(src2t);
  1383. GGML_ASSERT(!ggml_is_transposed(src2));
  1384. GGML_ASSERT(!ggml_is_transposed(src1));
  1385. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1386. const uint r2 = ne12/ne22;
  1387. const uint r3 = ne13/ne23;
  1388. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  1389. // to the matrix-vector kernel
  1390. int ne11_mm_min = n_as;
  1391. const int idx = ((int32_t *) dst->op_params)[0];
  1392. // batch size
  1393. GGML_ASSERT(ne01 == ne11);
  1394. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  1395. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  1396. // !!!
  1397. // TODO: for now, always use mat-vec kernels until we figure out how to improve the
  1398. // indirect matrix multiplication
  1399. // !!!
  1400. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  1401. ne20 % 32 == 0 && ne20 >= 64 &&
  1402. ne11 > ne11_mm_min) {
  1403. id<MTLComputePipelineState> pipeline = nil;
  1404. switch (src2->type) {
  1405. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F32_F32 ].pipeline; break;
  1406. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_F16_F32 ].pipeline; break;
  1407. case GGML_TYPE_Q4_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_0_F32 ].pipeline; break;
  1408. case GGML_TYPE_Q4_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_1_F32 ].pipeline; break;
  1409. case GGML_TYPE_Q5_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_0_F32 ].pipeline; break;
  1410. case GGML_TYPE_Q5_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_1_F32 ].pipeline; break;
  1411. case GGML_TYPE_Q8_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q8_0_F32 ].pipeline; break;
  1412. case GGML_TYPE_Q2_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q2_K_F32 ].pipeline; break;
  1413. case GGML_TYPE_Q3_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q3_K_F32 ].pipeline; break;
  1414. case GGML_TYPE_Q4_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q4_K_F32 ].pipeline; break;
  1415. case GGML_TYPE_Q5_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q5_K_F32 ].pipeline; break;
  1416. case GGML_TYPE_Q6_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_Q6_K_F32 ].pipeline; break;
  1417. case GGML_TYPE_IQ2_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XXS_F32].pipeline; break;
  1418. case GGML_TYPE_IQ2_XS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ2_XS_F32 ].pipeline; break;
  1419. case GGML_TYPE_IQ3_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ3_XXS_F32].pipeline; break;
  1420. case GGML_TYPE_IQ1_S: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MM_ID_IQ1_S_F32 ].pipeline; break;
  1421. default: GGML_ASSERT(false && "MUL_MAT_ID not implemented");
  1422. }
  1423. [encoder setComputePipelineState:pipeline];
  1424. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1425. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1426. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1427. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:3];
  1428. [encoder setBytes:&ne20 length:sizeof(ne20) atIndex:4];
  1429. [encoder setBytes:&ne22 length:sizeof(ne22) atIndex:5];
  1430. [encoder setBytes:&nb21 length:sizeof(nb21) atIndex:6];
  1431. [encoder setBytes:&nb22 length:sizeof(nb22) atIndex:7];
  1432. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:8];
  1433. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:9];
  1434. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:10];
  1435. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:11];
  1436. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:12];
  1437. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:13];
  1438. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:14];
  1439. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1440. [encoder setBytes:&r2 length:sizeof(r2) atIndex:16];
  1441. [encoder setBytes:&r3 length:sizeof(r3) atIndex:17];
  1442. [encoder setBytes:&idx length:sizeof(idx) atIndex:18];
  1443. // TODO: how to make this an array? read Metal docs
  1444. for (int j = 0; j < 8; ++j) {
  1445. // NOTE: this is done like this to avoid uninitialized kernel arguments when n_as < 8
  1446. struct ggml_tensor * src_cur = dst->src[2 + (j % n_as)];
  1447. size_t offs_src_cur = 0;
  1448. id<MTLBuffer> id_src_cur = ggml_metal_get_buffer(src_cur, &offs_src_cur);
  1449. [encoder setBuffer:id_src_cur offset:offs_src_cur atIndex:19 + j];
  1450. }
  1451. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  1452. [encoder dispatchThreadgroups:MTLSizeMake((ne11 + 31)/32, (ne21 + 63)/64, n_as*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  1453. } else {
  1454. int nth0 = 32;
  1455. int nth1 = 1;
  1456. int nrows = 1;
  1457. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1458. id<MTLComputePipelineState> pipeline = nil;
  1459. // use custom matrix x vector kernel
  1460. switch (src2t) {
  1461. case GGML_TYPE_F32:
  1462. {
  1463. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1464. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F32_F32].pipeline;
  1465. } break;
  1466. case GGML_TYPE_F16:
  1467. {
  1468. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1469. nth0 = 32;
  1470. nth1 = 1;
  1471. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_F16_F32].pipeline;
  1472. } break;
  1473. case GGML_TYPE_Q4_0:
  1474. {
  1475. nth0 = 8;
  1476. nth1 = 8;
  1477. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_0_F32].pipeline;
  1478. } break;
  1479. case GGML_TYPE_Q4_1:
  1480. {
  1481. nth0 = 8;
  1482. nth1 = 8;
  1483. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_1_F32].pipeline;
  1484. } break;
  1485. case GGML_TYPE_Q5_0:
  1486. {
  1487. nth0 = 8;
  1488. nth1 = 8;
  1489. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_0_F32].pipeline;
  1490. } break;
  1491. case GGML_TYPE_Q5_1:
  1492. {
  1493. nth0 = 8;
  1494. nth1 = 8;
  1495. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_1_F32].pipeline;
  1496. } break;
  1497. case GGML_TYPE_Q8_0:
  1498. {
  1499. nth0 = 8;
  1500. nth1 = 8;
  1501. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q8_0_F32].pipeline;
  1502. } break;
  1503. case GGML_TYPE_Q2_K:
  1504. {
  1505. nth0 = 2;
  1506. nth1 = 32;
  1507. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q2_K_F32].pipeline;
  1508. } break;
  1509. case GGML_TYPE_Q3_K:
  1510. {
  1511. nth0 = 2;
  1512. nth1 = 32;
  1513. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q3_K_F32].pipeline;
  1514. } break;
  1515. case GGML_TYPE_Q4_K:
  1516. {
  1517. nth0 = 4; //1;
  1518. nth1 = 8; //32;
  1519. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q4_K_F32].pipeline;
  1520. } break;
  1521. case GGML_TYPE_Q5_K:
  1522. {
  1523. nth0 = 2;
  1524. nth1 = 32;
  1525. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q5_K_F32].pipeline;
  1526. } break;
  1527. case GGML_TYPE_Q6_K:
  1528. {
  1529. nth0 = 2;
  1530. nth1 = 32;
  1531. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_Q6_K_F32].pipeline;
  1532. } break;
  1533. case GGML_TYPE_IQ2_XXS:
  1534. {
  1535. nth0 = 4;
  1536. nth1 = 16;
  1537. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XXS_F32].pipeline;
  1538. } break;
  1539. case GGML_TYPE_IQ2_XS:
  1540. {
  1541. nth0 = 4;
  1542. nth1 = 16;
  1543. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ2_XS_F32].pipeline;
  1544. } break;
  1545. case GGML_TYPE_IQ3_XXS:
  1546. {
  1547. nth0 = 4;
  1548. nth1 = 16;
  1549. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ3_XXS_F32].pipeline;
  1550. } break;
  1551. case GGML_TYPE_IQ1_S:
  1552. {
  1553. nth0 = 4;
  1554. nth1 = 16;
  1555. pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_MUL_MV_ID_IQ1_S_F32].pipeline;
  1556. } break;
  1557. default:
  1558. {
  1559. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src2t);
  1560. GGML_ASSERT(false && "not implemented");
  1561. }
  1562. };
  1563. if (ggml_is_quantized(src2t)) {
  1564. GGML_ASSERT(ne20 >= nth0*nth1);
  1565. }
  1566. const int64_t _ne1 = 1; // kernels needs a reference in constant memory
  1567. [encoder setComputePipelineState:pipeline];
  1568. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1569. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1570. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1571. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:3];
  1572. [encoder setBytes:&ne20 length:sizeof(ne20) atIndex:4];
  1573. [encoder setBytes:&ne21 length:sizeof(ne21) atIndex:5];
  1574. [encoder setBytes:&ne22 length:sizeof(ne22) atIndex:6];
  1575. [encoder setBytes:&nb20 length:sizeof(nb20) atIndex:7];
  1576. [encoder setBytes:&nb21 length:sizeof(nb21) atIndex:8];
  1577. [encoder setBytes:&nb22 length:sizeof(nb22) atIndex:9];
  1578. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:10];
  1579. [encoder setBytes:&_ne1 length:sizeof(_ne1) atIndex:11];
  1580. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:12];
  1581. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:13];
  1582. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:14];
  1583. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:15];
  1584. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:16];
  1585. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:17];
  1586. [encoder setBytes:&_ne1 length:sizeof(_ne1) atIndex:18];
  1587. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:19];
  1588. [encoder setBytes:&r2 length:sizeof(r2) atIndex:20];
  1589. [encoder setBytes:&r3 length:sizeof(r3) atIndex:21];
  1590. [encoder setBytes:&idx length:sizeof(idx) atIndex:22];
  1591. // TODO: how to make this an array? read Metal docs
  1592. for (int j = 0; j < 8; ++j) {
  1593. // NOTE: this is done like this to avoid uninitialized kernel arguments when n_as < 8
  1594. struct ggml_tensor * src_cur = dst->src[2 + (j % n_as)];
  1595. size_t offs_src_cur = 0;
  1596. id<MTLBuffer> id_src_cur = ggml_metal_get_buffer(src_cur, &offs_src_cur);
  1597. [encoder setBuffer:id_src_cur offset:offs_src_cur atIndex:23 + j];
  1598. }
  1599. if (src2t == GGML_TYPE_Q4_0 || src2t == GGML_TYPE_Q4_1 ||
  1600. src2t == GGML_TYPE_Q5_0 || src2t == GGML_TYPE_Q5_1 || src2t == GGML_TYPE_Q8_0 ||
  1601. src2t == GGML_TYPE_Q2_K || src2t == GGML_TYPE_IQ1_S) { // || src2t == GGML_TYPE_Q4_K) {
  1602. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 7)/8, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1603. }
  1604. else if (src2t == GGML_TYPE_IQ2_XXS || src2t == GGML_TYPE_IQ2_XS) {
  1605. const int mem_size = src2t == GGML_TYPE_IQ2_XXS ? 256*8+128 : 512*8+128;
  1606. [encoder setThreadgroupMemoryLength:mem_size atIndex:0];
  1607. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 7)/8, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1608. }
  1609. else if (src2t == GGML_TYPE_IQ3_XXS) {
  1610. const int mem_size = 256*4+128;
  1611. [encoder setThreadgroupMemoryLength:mem_size atIndex:0];
  1612. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 7)/8, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1613. }
  1614. else if (src2t == GGML_TYPE_Q4_K) {
  1615. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1616. }
  1617. else if (src2t == GGML_TYPE_Q3_K) {
  1618. #ifdef GGML_QKK_64
  1619. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 1)/2, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1620. #else
  1621. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1622. #endif
  1623. }
  1624. else if (src2t == GGML_TYPE_Q5_K) {
  1625. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1626. }
  1627. else if (src2t == GGML_TYPE_Q6_K) {
  1628. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 1)/2, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1629. } else {
  1630. const int64_t ny = (_ne1 + nrows - 1)/nrows;
  1631. [encoder dispatchThreadgroups:MTLSizeMake(ne21, ny, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1632. }
  1633. }
  1634. } break;
  1635. case GGML_OP_GET_ROWS:
  1636. {
  1637. id<MTLComputePipelineState> pipeline = nil;
  1638. switch (src0->type) {
  1639. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_F32 ].pipeline; break;
  1640. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_F16 ].pipeline; break;
  1641. case GGML_TYPE_Q4_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_0 ].pipeline; break;
  1642. case GGML_TYPE_Q4_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_1 ].pipeline; break;
  1643. case GGML_TYPE_Q5_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_0 ].pipeline; break;
  1644. case GGML_TYPE_Q5_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_1 ].pipeline; break;
  1645. case GGML_TYPE_Q8_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q8_0 ].pipeline; break;
  1646. case GGML_TYPE_Q2_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q2_K ].pipeline; break;
  1647. case GGML_TYPE_Q3_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q3_K ].pipeline; break;
  1648. case GGML_TYPE_Q4_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q4_K ].pipeline; break;
  1649. case GGML_TYPE_Q5_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q5_K ].pipeline; break;
  1650. case GGML_TYPE_Q6_K: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_Q6_K ].pipeline; break;
  1651. case GGML_TYPE_IQ2_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XXS].pipeline; break;
  1652. case GGML_TYPE_IQ2_XS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ2_XS ].pipeline; break;
  1653. case GGML_TYPE_IQ3_XXS: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ3_XXS].pipeline; break;
  1654. case GGML_TYPE_IQ1_S: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_IQ1_S ].pipeline; break;
  1655. case GGML_TYPE_I32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GET_ROWS_I32 ].pipeline; break;
  1656. default: GGML_ASSERT(false && "not implemented");
  1657. }
  1658. [encoder setComputePipelineState:pipeline];
  1659. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1660. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1661. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1662. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1663. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  1664. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:5];
  1665. [encoder setBytes:&ne10 length:sizeof( int64_t) atIndex:6];
  1666. [encoder setBytes:&nb10 length:sizeof( int64_t) atIndex:7];
  1667. [encoder setBytes:&nb11 length:sizeof( int64_t) atIndex:8];
  1668. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:9];
  1669. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:10];
  1670. [encoder dispatchThreadgroups:MTLSizeMake(ne10, ne11, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
  1671. } break;
  1672. case GGML_OP_RMS_NORM:
  1673. {
  1674. GGML_ASSERT(ne00 % 4 == 0);
  1675. float eps;
  1676. memcpy(&eps, dst->op_params, sizeof(float));
  1677. int nth = 32; // SIMD width
  1678. while (nth < ne00/4 && nth < 1024) {
  1679. nth *= 2;
  1680. }
  1681. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_RMS_NORM].pipeline;
  1682. [encoder setComputePipelineState:pipeline];
  1683. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1684. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1685. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1686. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1687. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1688. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1689. const int64_t nrows = ggml_nrows(src0);
  1690. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1691. } break;
  1692. case GGML_OP_GROUP_NORM:
  1693. {
  1694. GGML_ASSERT(ne00 % 4 == 0);
  1695. //float eps;
  1696. //memcpy(&eps, dst->op_params, sizeof(float));
  1697. const float eps = 1e-6f; // TODO: temporarily hardcoded
  1698. const int32_t n_groups = ((int32_t *) dst->op_params)[0];
  1699. int nth = 32; // SIMD width
  1700. //while (nth < ne00/4 && nth < 1024) {
  1701. // nth *= 2;
  1702. //}
  1703. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_GROUP_NORM].pipeline;
  1704. [encoder setComputePipelineState:pipeline];
  1705. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1706. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1707. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1708. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1709. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1710. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:5];
  1711. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:6];
  1712. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:7];
  1713. [encoder setBytes:&n_groups length:sizeof( int32_t) atIndex:8];
  1714. [encoder setBytes:&eps length:sizeof( float) atIndex:9];
  1715. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1716. [encoder dispatchThreadgroups:MTLSizeMake(n_groups, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1717. } break;
  1718. case GGML_OP_NORM:
  1719. {
  1720. float eps;
  1721. memcpy(&eps, dst->op_params, sizeof(float));
  1722. const int nth = MIN(256, ne00);
  1723. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_NORM].pipeline;
  1724. [encoder setComputePipelineState:pipeline];
  1725. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1726. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1727. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1728. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1729. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1730. [encoder setThreadgroupMemoryLength:GGML_PAD(nth*sizeof(float), 16) atIndex:0];
  1731. const int64_t nrows = ggml_nrows(src0);
  1732. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1733. } break;
  1734. case GGML_OP_ALIBI:
  1735. {
  1736. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1737. const int nth = MIN(1024, ne00);
  1738. //const int n_past = ((int32_t *) dst->op_params)[0];
  1739. const int n_head = ((int32_t *) dst->op_params)[1];
  1740. float max_bias;
  1741. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1742. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1743. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1744. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  1745. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ALIBI_F32].pipeline;
  1746. [encoder setComputePipelineState:pipeline];
  1747. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1748. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1749. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1750. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1751. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1752. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1753. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1754. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1755. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1756. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1757. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1758. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1759. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1760. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1761. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1762. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1763. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1764. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1765. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1766. [encoder setBytes:&m1 length:sizeof( float) atIndex:19];
  1767. [encoder setBytes:&n_heads_log2_floor length:sizeof(int) atIndex:20];
  1768. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1769. } break;
  1770. case GGML_OP_ROPE:
  1771. {
  1772. GGML_ASSERT(ne10 == ne02);
  1773. const int nth = MIN(1024, ne00);
  1774. const int n_past = ((int32_t *) dst->op_params)[0];
  1775. const int n_dims = ((int32_t *) dst->op_params)[1];
  1776. const int mode = ((int32_t *) dst->op_params)[2];
  1777. // skip 3, n_ctx, used in GLM RoPE, unimplemented in metal
  1778. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  1779. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1780. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  1781. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  1782. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  1783. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  1784. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  1785. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  1786. id<MTLComputePipelineState> pipeline = nil;
  1787. switch (src0->type) {
  1788. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ROPE_F32].pipeline; break;
  1789. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ROPE_F16].pipeline; break;
  1790. default: GGML_ASSERT(false);
  1791. };
  1792. [encoder setComputePipelineState:pipeline];
  1793. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1794. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1795. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1796. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1797. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:4];
  1798. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:5];
  1799. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:6];
  1800. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:7];
  1801. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:8];
  1802. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:9];
  1803. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:10];
  1804. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:11];
  1805. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:12];
  1806. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:13];
  1807. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:14];
  1808. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:15];
  1809. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:16];
  1810. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:17];
  1811. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:18];
  1812. [encoder setBytes:&n_past length:sizeof( int) atIndex:19];
  1813. [encoder setBytes:&n_dims length:sizeof( int) atIndex:20];
  1814. [encoder setBytes:&mode length:sizeof( int) atIndex:21];
  1815. [encoder setBytes:&n_orig_ctx length:sizeof( int) atIndex:22];
  1816. [encoder setBytes:&freq_base length:sizeof( float) atIndex:23];
  1817. [encoder setBytes:&freq_scale length:sizeof( float) atIndex:24];
  1818. [encoder setBytes:&ext_factor length:sizeof( float) atIndex:25];
  1819. [encoder setBytes:&attn_factor length:sizeof( float) atIndex:26];
  1820. [encoder setBytes:&beta_fast length:sizeof( float) atIndex:27];
  1821. [encoder setBytes:&beta_slow length:sizeof( float) atIndex:28];
  1822. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1823. } break;
  1824. case GGML_OP_IM2COL:
  1825. {
  1826. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  1827. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  1828. GGML_ASSERT( dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32);
  1829. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  1830. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  1831. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  1832. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  1833. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  1834. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  1835. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  1836. const int32_t N = src1->ne[is_2D ? 3 : 2];
  1837. const int32_t IC = src1->ne[is_2D ? 2 : 1];
  1838. const int32_t IH = is_2D ? src1->ne[1] : 1;
  1839. const int32_t IW = src1->ne[0];
  1840. const int32_t KH = is_2D ? src0->ne[1] : 1;
  1841. const int32_t KW = src0->ne[0];
  1842. const int32_t OH = is_2D ? dst->ne[2] : 1;
  1843. const int32_t OW = dst->ne[1];
  1844. const int32_t CHW = IC * KH * KW;
  1845. const int32_t ofs0 = src1->nb[is_2D ? 3 : 2] / 4;
  1846. const int32_t ofs1 = src1->nb[is_2D ? 2 : 1] / 4;
  1847. id<MTLComputePipelineState> pipeline = nil;
  1848. switch (dst->type) {
  1849. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_IM2COL_F32].pipeline; break;
  1850. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_IM2COL_F16].pipeline; break;
  1851. default: GGML_ASSERT(false);
  1852. };
  1853. [encoder setComputePipelineState:pipeline];
  1854. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:0];
  1855. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1856. [encoder setBytes:&ofs0 length:sizeof( int32_t) atIndex:2];
  1857. [encoder setBytes:&ofs1 length:sizeof( int32_t) atIndex:3];
  1858. [encoder setBytes:&IW length:sizeof( int32_t) atIndex:4];
  1859. [encoder setBytes:&IH length:sizeof( int32_t) atIndex:5];
  1860. [encoder setBytes:&CHW length:sizeof( int32_t) atIndex:6];
  1861. [encoder setBytes:&s0 length:sizeof( int32_t) atIndex:7];
  1862. [encoder setBytes:&s1 length:sizeof( int32_t) atIndex:8];
  1863. [encoder setBytes:&p0 length:sizeof( int32_t) atIndex:9];
  1864. [encoder setBytes:&p1 length:sizeof( int32_t) atIndex:10];
  1865. [encoder setBytes:&d0 length:sizeof( int32_t) atIndex:11];
  1866. [encoder setBytes:&d1 length:sizeof( int32_t) atIndex:12];
  1867. [encoder dispatchThreadgroups:MTLSizeMake(IC, OH, OW) threadsPerThreadgroup:MTLSizeMake(N, KH, KW)];
  1868. } break;
  1869. case GGML_OP_UPSCALE:
  1870. {
  1871. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1872. const int sf = dst->op_params[0];
  1873. const id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_UPSCALE_F32].pipeline;
  1874. [encoder setComputePipelineState:pipeline];
  1875. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1876. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1877. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1878. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1879. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1880. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1881. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1882. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1883. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1884. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1885. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:10];
  1886. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:11];
  1887. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:12];
  1888. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:13];
  1889. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:14];
  1890. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1891. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:16];
  1892. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:17];
  1893. [encoder setBytes:&sf length:sizeof(sf) atIndex:18];
  1894. const int nth = MIN((int) pipeline.maxTotalThreadsPerThreadgroup, ne0);
  1895. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1896. } break;
  1897. case GGML_OP_PAD:
  1898. {
  1899. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1900. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_PAD_F32].pipeline;
  1901. [encoder setComputePipelineState:pipeline];
  1902. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1903. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1904. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1905. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1906. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1907. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1908. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1909. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1910. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1911. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1912. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:10];
  1913. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:11];
  1914. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:12];
  1915. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:13];
  1916. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:14];
  1917. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1918. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:16];
  1919. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:17];
  1920. const int nth = MIN(1024, ne0);
  1921. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1922. } break;
  1923. case GGML_OP_ARGSORT:
  1924. {
  1925. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1926. GGML_ASSERT( dst->type == GGML_TYPE_I32);
  1927. const int nrows = ggml_nrows(src0);
  1928. enum ggml_sort_order order = (enum ggml_sort_order) dst->op_params[0];
  1929. id<MTLComputePipelineState> pipeline = nil;
  1930. switch (order) {
  1931. case GGML_SORT_ASC: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_ASC].pipeline; break;
  1932. case GGML_SORT_DESC: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_ARGSORT_F32_I32_DESC].pipeline; break;
  1933. default: GGML_ASSERT(false);
  1934. };
  1935. [encoder setComputePipelineState:pipeline];
  1936. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1937. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1938. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1939. [encoder dispatchThreadgroups:MTLSizeMake(1, nrows, 1) threadsPerThreadgroup:MTLSizeMake(ne00, 1, 1)];
  1940. } break;
  1941. case GGML_OP_LEAKY_RELU:
  1942. {
  1943. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1944. float slope;
  1945. memcpy(&slope, dst->op_params, sizeof(float));
  1946. id<MTLComputePipelineState> pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_LEAKY_RELU_F32].pipeline;
  1947. [encoder setComputePipelineState:pipeline];
  1948. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1949. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1950. [encoder setBytes:&slope length:sizeof(slope) atIndex:2];
  1951. const int64_t n = ggml_nelements(dst);
  1952. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1953. } break;
  1954. case GGML_OP_DUP:
  1955. case GGML_OP_CPY:
  1956. case GGML_OP_CONT:
  1957. {
  1958. GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0);
  1959. int nth = MIN(1024, ne00/ggml_blck_size(src0->type));
  1960. id<MTLComputePipelineState> pipeline = nil;
  1961. switch (src0t) {
  1962. case GGML_TYPE_F32:
  1963. {
  1964. GGML_ASSERT(ne0 % ggml_blck_size(dst->type) == 0);
  1965. switch (dstt) {
  1966. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_F16].pipeline; break;
  1967. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_F32].pipeline; break;
  1968. case GGML_TYPE_Q8_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_Q8_0].pipeline; break;
  1969. case GGML_TYPE_Q4_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_0].pipeline; break;
  1970. case GGML_TYPE_Q4_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_Q4_1].pipeline; break;
  1971. //case GGML_TYPE_Q5_0: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_0].pipeline; break;
  1972. //case GGML_TYPE_Q5_1: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F32_Q5_1].pipeline; break;
  1973. default: GGML_ASSERT(false && "not implemented");
  1974. };
  1975. } break;
  1976. case GGML_TYPE_F16:
  1977. {
  1978. switch (dstt) {
  1979. case GGML_TYPE_F16: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F16_F16].pipeline; break;
  1980. case GGML_TYPE_F32: pipeline = ctx->kernels[GGML_METAL_KERNEL_TYPE_CPY_F16_F32].pipeline; break;
  1981. default: GGML_ASSERT(false && "not implemented");
  1982. };
  1983. } break;
  1984. default: GGML_ASSERT(false && "not implemented");
  1985. }
  1986. [encoder setComputePipelineState:pipeline];
  1987. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1988. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1989. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1990. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1991. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1992. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1993. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1994. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1995. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1996. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1997. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1998. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1999. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  2000. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  2001. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  2002. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  2003. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  2004. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  2005. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  2006. } break;
  2007. default:
  2008. {
  2009. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  2010. GGML_ASSERT(false);
  2011. }
  2012. }
  2013. if (should_capture) {
  2014. [encoder popDebugGroup];
  2015. }
  2016. }
  2017. [encoder endEncoding];
  2018. [command_buffer commit];
  2019. });
  2020. // Wait for completion and check status of each command buffer
  2021. // needed to detect if the device ran out-of-memory for example (#1881)
  2022. for (int i = 0; i < n_cb; ++i) {
  2023. id<MTLCommandBuffer> command_buffer = command_buffers[i];
  2024. [command_buffer waitUntilCompleted];
  2025. MTLCommandBufferStatus status = [command_buffer status];
  2026. if (status != MTLCommandBufferStatusCompleted) {
  2027. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  2028. return false;
  2029. }
  2030. }
  2031. if (should_capture) {
  2032. [[MTLCaptureManager sharedCaptureManager] stopCapture];
  2033. }
  2034. }
  2035. return true;
  2036. }
  2037. ////////////////////////////////////////////////////////////////////////////////
  2038. // backend interface
  2039. // default buffer
  2040. static id<MTLDevice> g_backend_device = nil;
  2041. static int g_backend_device_ref_count = 0;
  2042. static id<MTLDevice> ggml_backend_metal_get_device(void) {
  2043. if (g_backend_device == nil) {
  2044. g_backend_device = MTLCreateSystemDefaultDevice();
  2045. }
  2046. g_backend_device_ref_count++;
  2047. return g_backend_device;
  2048. }
  2049. static void ggml_backend_metal_free_device(void) {
  2050. assert(g_backend_device_ref_count > 0);
  2051. g_backend_device_ref_count--;
  2052. if (g_backend_device_ref_count == 0) {
  2053. [g_backend_device release];
  2054. g_backend_device = nil;
  2055. }
  2056. }
  2057. GGML_CALL static const char * ggml_backend_metal_buffer_get_name(ggml_backend_buffer_t buffer) {
  2058. return "Metal";
  2059. UNUSED(buffer);
  2060. }
  2061. GGML_CALL static void ggml_backend_metal_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  2062. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2063. for (int i = 0; i < ctx->n_buffers; i++) {
  2064. [ctx->buffers[i].metal release];
  2065. }
  2066. ggml_backend_metal_free_device();
  2067. if (ctx->owned) {
  2068. free(ctx->all_data);
  2069. }
  2070. free(ctx);
  2071. }
  2072. GGML_CALL static void * ggml_backend_metal_buffer_get_base(ggml_backend_buffer_t buffer) {
  2073. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2074. return ctx->all_data;
  2075. }
  2076. GGML_CALL 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) {
  2077. memcpy((char *)tensor->data + offset, data, size);
  2078. UNUSED(buffer);
  2079. }
  2080. GGML_CALL 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) {
  2081. memcpy(data, (const char *)tensor->data + offset, size);
  2082. UNUSED(buffer);
  2083. }
  2084. GGML_CALL static bool ggml_backend_metal_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * src, struct ggml_tensor * dst) {
  2085. if (ggml_backend_buffer_is_host(src->buffer)) {
  2086. memcpy(dst->data, src->data, ggml_nbytes(src));
  2087. return true;
  2088. }
  2089. return false;
  2090. UNUSED(buffer);
  2091. }
  2092. GGML_CALL static void ggml_backend_metal_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  2093. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2094. memset(ctx->all_data, value, ctx->all_size);
  2095. }
  2096. static struct ggml_backend_buffer_i ggml_backend_metal_buffer_i = {
  2097. /* .get_name = */ ggml_backend_metal_buffer_get_name,
  2098. /* .free_buffer = */ ggml_backend_metal_buffer_free_buffer,
  2099. /* .get_base = */ ggml_backend_metal_buffer_get_base,
  2100. /* .init_tensor = */ NULL,
  2101. /* .set_tensor = */ ggml_backend_metal_buffer_set_tensor,
  2102. /* .get_tensor = */ ggml_backend_metal_buffer_get_tensor,
  2103. /* .cpy_tensor = */ ggml_backend_metal_buffer_cpy_tensor,
  2104. /* .clear = */ ggml_backend_metal_buffer_clear,
  2105. /* .reset = */ NULL,
  2106. };
  2107. // default buffer type
  2108. GGML_CALL static const char * ggml_backend_metal_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
  2109. return "Metal";
  2110. UNUSED(buft);
  2111. }
  2112. static void ggml_backend_metal_log_allocated_size(id<MTLDevice> device) {
  2113. #if TARGET_OS_OSX || (TARGET_OS_IOS && __clang_major__ >= 15)
  2114. if (@available(macOS 10.12, iOS 16.0, *)) {
  2115. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  2116. device.currentAllocatedSize / 1024.0 / 1024.0,
  2117. device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  2118. if (device.currentAllocatedSize > device.recommendedMaxWorkingSetSize) {
  2119. GGML_METAL_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
  2120. } else {
  2121. GGML_METAL_LOG_INFO("\n");
  2122. }
  2123. } else {
  2124. GGML_METAL_LOG_INFO(", (%8.2f)\n", device.currentAllocatedSize / 1024.0 / 1024.0);
  2125. }
  2126. #endif
  2127. UNUSED(device);
  2128. }
  2129. GGML_CALL static ggml_backend_buffer_t ggml_backend_metal_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  2130. struct ggml_backend_metal_buffer_context * ctx = malloc(sizeof(struct ggml_backend_metal_buffer_context));
  2131. const size_t size_page = sysconf(_SC_PAGESIZE);
  2132. size_t size_aligned = size;
  2133. if ((size_aligned % size_page) != 0) {
  2134. size_aligned += (size_page - (size_aligned % size_page));
  2135. }
  2136. id<MTLDevice> device = ggml_backend_metal_get_device();
  2137. ctx->all_data = ggml_metal_host_malloc(size_aligned);
  2138. ctx->all_size = size_aligned;
  2139. ctx->owned = true;
  2140. ctx->n_buffers = 1;
  2141. ctx->buffers[0].data = ctx->all_data;
  2142. ctx->buffers[0].size = size;
  2143. ctx->buffers[0].metal = [device newBufferWithBytesNoCopy:ctx->all_data
  2144. length:size_aligned
  2145. options:MTLResourceStorageModeShared
  2146. deallocator:nil];
  2147. if (ctx->buffers[0].metal == nil) {
  2148. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
  2149. free(ctx);
  2150. ggml_backend_metal_free_device();
  2151. return NULL;
  2152. }
  2153. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB", __func__, size_aligned / 1024.0 / 1024.0);
  2154. ggml_backend_metal_log_allocated_size(device);
  2155. return ggml_backend_buffer_init(buft, ggml_backend_metal_buffer_i, ctx, size);
  2156. }
  2157. GGML_CALL static size_t ggml_backend_metal_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  2158. return 32;
  2159. UNUSED(buft);
  2160. }
  2161. GGML_CALL static size_t ggml_backend_metal_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  2162. id<MTLDevice> device = ggml_backend_metal_get_device();
  2163. size_t max_size = device.maxBufferLength;
  2164. ggml_backend_metal_free_device();
  2165. return max_size;
  2166. UNUSED(buft);
  2167. }
  2168. GGML_CALL static bool ggml_backend_metal_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  2169. return ggml_backend_is_metal(backend) || ggml_backend_is_cpu(backend);
  2170. UNUSED(buft);
  2171. }
  2172. GGML_CALL static bool ggml_backend_metal_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  2173. return true;
  2174. UNUSED(buft);
  2175. }
  2176. GGML_CALL ggml_backend_buffer_type_t ggml_backend_metal_buffer_type(void) {
  2177. static struct ggml_backend_buffer_type ggml_backend_buffer_type_metal = {
  2178. /* .iface = */ {
  2179. /* .get_name = */ ggml_backend_metal_buffer_type_get_name,
  2180. /* .alloc_buffer = */ ggml_backend_metal_buffer_type_alloc_buffer,
  2181. /* .get_alignment = */ ggml_backend_metal_buffer_type_get_alignment,
  2182. /* .get_max_size = */ ggml_backend_metal_buffer_type_get_max_size,
  2183. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  2184. /* .supports_backend = */ ggml_backend_metal_buffer_type_supports_backend,
  2185. /* .is_host = */ ggml_backend_metal_buffer_type_is_host,
  2186. },
  2187. /* .context = */ NULL,
  2188. };
  2189. return &ggml_backend_buffer_type_metal;
  2190. }
  2191. // buffer from ptr
  2192. GGML_CALL ggml_backend_buffer_t ggml_backend_metal_buffer_from_ptr(void * data, size_t size, size_t max_size) {
  2193. struct ggml_backend_metal_buffer_context * ctx = malloc(sizeof(struct ggml_backend_metal_buffer_context));
  2194. ctx->all_data = data;
  2195. ctx->all_size = size;
  2196. ctx->owned = false;
  2197. ctx->n_buffers = 0;
  2198. const size_t size_page = sysconf(_SC_PAGESIZE);
  2199. // page-align the data ptr
  2200. {
  2201. const uintptr_t offs = (uintptr_t) data % size_page;
  2202. data = (void *) ((char *) data - offs);
  2203. size += offs;
  2204. }
  2205. size_t size_aligned = size;
  2206. if ((size_aligned % size_page) != 0) {
  2207. size_aligned += (size_page - (size_aligned % size_page));
  2208. }
  2209. id<MTLDevice> device = ggml_backend_metal_get_device();
  2210. // the buffer fits into the max buffer size allowed by the device
  2211. if (size_aligned <= device.maxBufferLength) {
  2212. ctx->buffers[ctx->n_buffers].data = data;
  2213. ctx->buffers[ctx->n_buffers].size = size;
  2214. ctx->buffers[ctx->n_buffers].metal = [device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  2215. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  2216. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
  2217. return false;
  2218. }
  2219. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB", __func__, size_aligned / 1024.0 / 1024.0);
  2220. ++ctx->n_buffers;
  2221. } else {
  2222. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  2223. // one of the views
  2224. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  2225. const size_t size_step = device.maxBufferLength - size_ovlp;
  2226. const size_t size_view = device.maxBufferLength;
  2227. for (size_t i = 0; i < size; i += size_step) {
  2228. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  2229. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  2230. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  2231. ctx->buffers[ctx->n_buffers].metal = [device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  2232. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  2233. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_step_aligned / 1024.0 / 1024.0);
  2234. return false;
  2235. }
  2236. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB, offs = %12ld", __func__, size_step_aligned / 1024.0 / 1024.0, i);
  2237. if (i + size_step < size) {
  2238. GGML_METAL_LOG_INFO("\n");
  2239. }
  2240. ++ctx->n_buffers;
  2241. }
  2242. }
  2243. ggml_backend_metal_log_allocated_size(device);
  2244. return ggml_backend_buffer_init(ggml_backend_metal_buffer_type(), ggml_backend_metal_buffer_i, ctx, size);
  2245. }
  2246. // backend
  2247. GGML_CALL static const char * ggml_backend_metal_name(ggml_backend_t backend) {
  2248. return "Metal";
  2249. UNUSED(backend);
  2250. }
  2251. GGML_CALL static void ggml_backend_metal_free(ggml_backend_t backend) {
  2252. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2253. ggml_metal_free(ctx);
  2254. free(backend);
  2255. }
  2256. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_metal_get_default_buffer_type(ggml_backend_t backend) {
  2257. return ggml_backend_metal_buffer_type();
  2258. UNUSED(backend);
  2259. }
  2260. GGML_CALL static bool ggml_backend_metal_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  2261. struct ggml_metal_context * metal_ctx = (struct ggml_metal_context *)backend->context;
  2262. return ggml_metal_graph_compute(metal_ctx, cgraph);
  2263. }
  2264. GGML_CALL static bool ggml_backend_metal_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  2265. struct ggml_metal_context * metal_ctx = (struct ggml_metal_context *)backend->context;
  2266. return ggml_metal_supports_op(metal_ctx, op);
  2267. }
  2268. static struct ggml_backend_i ggml_backend_metal_i = {
  2269. /* .get_name = */ ggml_backend_metal_name,
  2270. /* .free = */ ggml_backend_metal_free,
  2271. /* .get_default_buffer_type = */ ggml_backend_metal_get_default_buffer_type,
  2272. /* .set_tensor_async = */ NULL,
  2273. /* .get_tensor_async = */ NULL,
  2274. /* .cpy_tensor_async = */ NULL,
  2275. /* .synchronize = */ NULL,
  2276. /* .graph_plan_create = */ NULL,
  2277. /* .graph_plan_free = */ NULL,
  2278. /* .graph_plan_compute = */ NULL,
  2279. /* .graph_compute = */ ggml_backend_metal_graph_compute,
  2280. /* .supports_op = */ ggml_backend_metal_supports_op,
  2281. };
  2282. void ggml_backend_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  2283. ggml_metal_log_callback = log_callback;
  2284. ggml_metal_log_user_data = user_data;
  2285. }
  2286. ggml_backend_t ggml_backend_metal_init(void) {
  2287. struct ggml_metal_context * ctx = ggml_metal_init(GGML_DEFAULT_N_THREADS);
  2288. if (ctx == NULL) {
  2289. return NULL;
  2290. }
  2291. ggml_backend_t metal_backend = malloc(sizeof(struct ggml_backend));
  2292. *metal_backend = (struct ggml_backend) {
  2293. /* .interface = */ ggml_backend_metal_i,
  2294. /* .context = */ ctx,
  2295. };
  2296. return metal_backend;
  2297. }
  2298. bool ggml_backend_is_metal(ggml_backend_t backend) {
  2299. return backend && backend->iface.get_name == ggml_backend_metal_name;
  2300. }
  2301. void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
  2302. GGML_ASSERT(ggml_backend_is_metal(backend));
  2303. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2304. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  2305. }
  2306. bool ggml_backend_metal_supports_family(ggml_backend_t backend, int family) {
  2307. GGML_ASSERT(ggml_backend_is_metal(backend));
  2308. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2309. return [ctx->device supportsFamily:(MTLGPUFamilyApple1 + family - 1)];
  2310. }
  2311. void ggml_backend_metal_capture_next_compute(ggml_backend_t backend) {
  2312. GGML_ASSERT(ggml_backend_is_metal(backend));
  2313. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2314. ctx->should_capture_next_compute = true;
  2315. }
  2316. GGML_CALL ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data); // silence warning
  2317. GGML_CALL ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data) {
  2318. return ggml_backend_metal_init();
  2319. GGML_UNUSED(params);
  2320. GGML_UNUSED(user_data);
  2321. }