ggml-metal.m 142 KB

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