ggml-metal.m 136 KB

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