ggml-metal.m 150 KB

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