ggml-metal.m 148 KB

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