ggml-metal.m 147 KB

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