ggml-metal.m 159 KB

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