ggml-metal.m 148 KB

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