ggml-metal.m 148 KB

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