ggml-metal.m 147 KB

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