ggml-metal.m 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. #import "ggml-metal.h"
  2. #import "ggml.h"
  3. #import <Foundation/Foundation.h>
  4. #import <Metal/Metal.h>
  5. #undef MIN
  6. #undef MAX
  7. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  8. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  9. #ifdef GGML_METAL_NDEBUG
  10. #define GGML_METAL_LOG_INFO(...)
  11. #define GGML_METAL_LOG_WARN(...)
  12. #define GGML_METAL_LOG_ERROR(...)
  13. #else
  14. #define GGML_METAL_LOG_INFO(...) ggml_metal_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  15. #define GGML_METAL_LOG_WARN(...) ggml_metal_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  16. #define GGML_METAL_LOG_ERROR(...) ggml_metal_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  17. #endif
  18. #define UNUSED(x) (void)(x)
  19. #define GGML_MAX_CONCUR (2*GGML_MAX_NODES)
  20. struct ggml_metal_buffer {
  21. const char * name;
  22. void * data;
  23. size_t size;
  24. id<MTLBuffer> metal;
  25. };
  26. struct ggml_metal_context {
  27. int n_cb;
  28. id<MTLDevice> device;
  29. id<MTLCommandQueue> queue;
  30. id<MTLLibrary> library;
  31. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  32. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  33. dispatch_queue_t d_queue;
  34. int n_buffers;
  35. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  36. int concur_list[GGML_MAX_CONCUR];
  37. int concur_list_len;
  38. // custom kernels
  39. #define GGML_METAL_DECL_KERNEL(name) \
  40. id<MTLFunction> function_##name; \
  41. id<MTLComputePipelineState> pipeline_##name
  42. GGML_METAL_DECL_KERNEL(add);
  43. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  44. GGML_METAL_DECL_KERNEL(mul);
  45. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  46. GGML_METAL_DECL_KERNEL(scale);
  47. GGML_METAL_DECL_KERNEL(silu);
  48. GGML_METAL_DECL_KERNEL(relu);
  49. GGML_METAL_DECL_KERNEL(gelu);
  50. GGML_METAL_DECL_KERNEL(soft_max);
  51. GGML_METAL_DECL_KERNEL(soft_max_4);
  52. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  53. GGML_METAL_DECL_KERNEL(diag_mask_inf_8);
  54. GGML_METAL_DECL_KERNEL(get_rows_f32);
  55. GGML_METAL_DECL_KERNEL(get_rows_f16);
  56. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  57. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  58. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  59. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  60. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  61. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  62. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  63. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  64. GGML_METAL_DECL_KERNEL(rms_norm);
  65. GGML_METAL_DECL_KERNEL(norm);
  66. GGML_METAL_DECL_KERNEL(mul_mat_f32_f32);
  67. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32);
  68. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32_1row);
  69. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32_l4);
  70. GGML_METAL_DECL_KERNEL(mul_mat_q4_0_f32);
  71. GGML_METAL_DECL_KERNEL(mul_mat_q4_1_f32);
  72. GGML_METAL_DECL_KERNEL(mul_mat_q8_0_f32);
  73. GGML_METAL_DECL_KERNEL(mul_mat_q2_K_f32);
  74. GGML_METAL_DECL_KERNEL(mul_mat_q3_K_f32);
  75. GGML_METAL_DECL_KERNEL(mul_mat_q4_K_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mat_q5_K_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mat_q6_K_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mm_f32_f32);
  79. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  80. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  83. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  84. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  85. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  86. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  87. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  88. GGML_METAL_DECL_KERNEL(rope_f32);
  89. GGML_METAL_DECL_KERNEL(rope_f16);
  90. GGML_METAL_DECL_KERNEL(alibi_f32);
  91. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  92. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  93. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  94. #undef GGML_METAL_DECL_KERNEL
  95. };
  96. // MSL code
  97. // TODO: move the contents here when ready
  98. // for now it is easier to work in a separate file
  99. static NSString * const msl_library_source = @"see metal.metal";
  100. // Here to assist with NSBundle Path Hack
  101. @interface GGMLMetalClass : NSObject
  102. @end
  103. @implementation GGMLMetalClass
  104. @end
  105. ggml_log_callback ggml_metal_log_callback = NULL;
  106. void * ggml_metal_log_user_data = NULL;
  107. void ggml_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  108. ggml_metal_log_callback = log_callback;
  109. ggml_metal_log_user_data = user_data;
  110. }
  111. static void ggml_metal_log(enum ggml_log_level level, const char* format, ...){
  112. if (ggml_metal_log_callback != NULL) {
  113. va_list args;
  114. va_start(args, format);
  115. char buffer[128];
  116. int len = vsnprintf(buffer, 128, format, args);
  117. if (len < 128) {
  118. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  119. } else {
  120. char* buffer2 = malloc(len+1);
  121. vsnprintf(buffer2, len+1, format, args);
  122. buffer2[len] = 0;
  123. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  124. free(buffer2);
  125. }
  126. va_end(args);
  127. }
  128. }
  129. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  130. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  131. id <MTLDevice> device;
  132. NSString * s;
  133. #if TARGET_OS_OSX
  134. // Show all the Metal device instances in the system
  135. NSArray * devices = MTLCopyAllDevices();
  136. for (device in devices) {
  137. s = [device name];
  138. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [s UTF8String]);
  139. }
  140. #endif
  141. // Pick and show default Metal device
  142. device = MTLCreateSystemDefaultDevice();
  143. s = [device name];
  144. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [s UTF8String]);
  145. // Configure context
  146. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  147. ctx->device = device;
  148. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  149. ctx->queue = [ctx->device newCommandQueue];
  150. ctx->n_buffers = 0;
  151. ctx->concur_list_len = 0;
  152. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  153. #ifdef GGML_SWIFT
  154. // load the default.metallib file
  155. {
  156. NSError * error = nil;
  157. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  158. NSString * llamaBundlePath = [bundle pathForResource:@"llama_llama" ofType:@"bundle"];
  159. NSBundle * llamaBundle = [NSBundle bundleWithPath:llamaBundlePath];
  160. NSString * libPath = [llamaBundle pathForResource:@"default" ofType:@"metallib"];
  161. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  162. // Load the metallib file into a Metal library
  163. ctx->library = [ctx->device newLibraryWithURL:libURL error:&error];
  164. if (error) {
  165. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  166. return NULL;
  167. }
  168. }
  169. #else
  170. UNUSED(msl_library_source);
  171. // read the source from "ggml-metal.metal" into a string and use newLibraryWithSource
  172. {
  173. NSError * error = nil;
  174. //NSString * path = [[NSBundle mainBundle] pathForResource:@"../../examples/metal/metal" ofType:@"metal"];
  175. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  176. NSString * path = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  177. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [path UTF8String]);
  178. NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
  179. if (error) {
  180. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  181. return NULL;
  182. }
  183. #ifdef GGML_QKK_64
  184. MTLCompileOptions* options = [MTLCompileOptions new];
  185. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  186. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  187. #else
  188. ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];
  189. #endif
  190. if (error) {
  191. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  192. return NULL;
  193. }
  194. }
  195. #endif
  196. // load kernels
  197. {
  198. NSError * error = nil;
  199. #define GGML_METAL_ADD_KERNEL(name) \
  200. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  201. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  202. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  203. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  204. (int) ctx->pipeline_##name.threadExecutionWidth); \
  205. if (error) { \
  206. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  207. return NULL; \
  208. }
  209. GGML_METAL_ADD_KERNEL(add);
  210. GGML_METAL_ADD_KERNEL(add_row);
  211. GGML_METAL_ADD_KERNEL(mul);
  212. GGML_METAL_ADD_KERNEL(mul_row);
  213. GGML_METAL_ADD_KERNEL(scale);
  214. GGML_METAL_ADD_KERNEL(silu);
  215. GGML_METAL_ADD_KERNEL(relu);
  216. GGML_METAL_ADD_KERNEL(gelu);
  217. GGML_METAL_ADD_KERNEL(soft_max);
  218. GGML_METAL_ADD_KERNEL(soft_max_4);
  219. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  220. GGML_METAL_ADD_KERNEL(diag_mask_inf_8);
  221. GGML_METAL_ADD_KERNEL(get_rows_f32);
  222. GGML_METAL_ADD_KERNEL(get_rows_f16);
  223. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  224. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  225. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  226. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  227. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  228. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  229. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  230. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  231. GGML_METAL_ADD_KERNEL(rms_norm);
  232. GGML_METAL_ADD_KERNEL(norm);
  233. GGML_METAL_ADD_KERNEL(mul_mat_f32_f32);
  234. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32);
  235. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32_1row);
  236. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32_l4);
  237. GGML_METAL_ADD_KERNEL(mul_mat_q4_0_f32);
  238. GGML_METAL_ADD_KERNEL(mul_mat_q4_1_f32);
  239. GGML_METAL_ADD_KERNEL(mul_mat_q8_0_f32);
  240. GGML_METAL_ADD_KERNEL(mul_mat_q2_K_f32);
  241. GGML_METAL_ADD_KERNEL(mul_mat_q3_K_f32);
  242. GGML_METAL_ADD_KERNEL(mul_mat_q4_K_f32);
  243. GGML_METAL_ADD_KERNEL(mul_mat_q5_K_f32);
  244. GGML_METAL_ADD_KERNEL(mul_mat_q6_K_f32);
  245. GGML_METAL_ADD_KERNEL(mul_mm_f32_f32);
  246. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  247. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  248. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  249. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  250. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  251. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  252. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  253. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  254. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  255. GGML_METAL_ADD_KERNEL(rope_f32);
  256. GGML_METAL_ADD_KERNEL(rope_f16);
  257. GGML_METAL_ADD_KERNEL(alibi_f32);
  258. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  259. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  260. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  261. #undef GGML_METAL_ADD_KERNEL
  262. }
  263. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  264. #if TARGET_OS_OSX
  265. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  266. if (ctx->device.maxTransferRate != 0) {
  267. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  268. } else {
  269. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  270. }
  271. #endif
  272. return ctx;
  273. }
  274. void ggml_metal_free(struct ggml_metal_context * ctx) {
  275. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  276. #define GGML_METAL_DEL_KERNEL(name) \
  277. [ctx->function_##name release]; \
  278. [ctx->pipeline_##name release];
  279. GGML_METAL_DEL_KERNEL(add);
  280. GGML_METAL_DEL_KERNEL(add_row);
  281. GGML_METAL_DEL_KERNEL(mul);
  282. GGML_METAL_DEL_KERNEL(mul_row);
  283. GGML_METAL_DEL_KERNEL(scale);
  284. GGML_METAL_DEL_KERNEL(silu);
  285. GGML_METAL_DEL_KERNEL(relu);
  286. GGML_METAL_DEL_KERNEL(gelu);
  287. GGML_METAL_DEL_KERNEL(soft_max);
  288. GGML_METAL_DEL_KERNEL(soft_max_4);
  289. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  290. GGML_METAL_DEL_KERNEL(diag_mask_inf_8);
  291. GGML_METAL_DEL_KERNEL(get_rows_f32);
  292. GGML_METAL_DEL_KERNEL(get_rows_f16);
  293. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  294. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  295. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  296. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  297. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  298. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  299. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  300. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  301. GGML_METAL_DEL_KERNEL(rms_norm);
  302. GGML_METAL_DEL_KERNEL(norm);
  303. GGML_METAL_DEL_KERNEL(mul_mat_f32_f32);
  304. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32);
  305. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32_1row);
  306. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32_l4);
  307. GGML_METAL_DEL_KERNEL(mul_mat_q4_0_f32);
  308. GGML_METAL_DEL_KERNEL(mul_mat_q4_1_f32);
  309. GGML_METAL_DEL_KERNEL(mul_mat_q8_0_f32);
  310. GGML_METAL_DEL_KERNEL(mul_mat_q2_K_f32);
  311. GGML_METAL_DEL_KERNEL(mul_mat_q3_K_f32);
  312. GGML_METAL_DEL_KERNEL(mul_mat_q4_K_f32);
  313. GGML_METAL_DEL_KERNEL(mul_mat_q5_K_f32);
  314. GGML_METAL_DEL_KERNEL(mul_mat_q6_K_f32);
  315. GGML_METAL_DEL_KERNEL(mul_mm_f32_f32);
  316. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  317. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  318. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  319. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  320. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  321. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  322. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  323. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  324. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  325. GGML_METAL_DEL_KERNEL(rope_f32);
  326. GGML_METAL_DEL_KERNEL(rope_f16);
  327. GGML_METAL_DEL_KERNEL(alibi_f32);
  328. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  329. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  330. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  331. #undef GGML_METAL_DEL_KERNEL
  332. for (int i = 0; i < ctx->n_buffers; ++i) {
  333. [ctx->buffers[i].metal release];
  334. }
  335. [ctx->library release];
  336. [ctx->queue release];
  337. [ctx->device release];
  338. dispatch_release(ctx->d_queue);
  339. free(ctx);
  340. }
  341. void * ggml_metal_host_malloc(size_t n) {
  342. void * data = NULL;
  343. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  344. if (result != 0) {
  345. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  346. return NULL;
  347. }
  348. return data;
  349. }
  350. void ggml_metal_host_free(void * data) {
  351. free(data);
  352. }
  353. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  354. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  355. }
  356. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  357. return ctx->concur_list_len;
  358. }
  359. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  360. return ctx->concur_list;
  361. }
  362. // finds the Metal buffer that contains the tensor data on the GPU device
  363. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  364. // Metal buffer based on the host memory pointer
  365. //
  366. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  367. //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);
  368. const int64_t tsize = ggml_nbytes(t);
  369. // find the view that contains the tensor fully
  370. for (int i = 0; i < ctx->n_buffers; ++i) {
  371. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  372. //metal_printf("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);
  373. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  374. *offs = (size_t) ioffs;
  375. //GGML_METAL_LOG_INFO("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  376. return ctx->buffers[i].metal;
  377. }
  378. }
  379. GGML_METAL_LOG_ERROR("%s: error: buffer is nil\n", __func__);
  380. return nil;
  381. }
  382. bool ggml_metal_add_buffer(
  383. struct ggml_metal_context * ctx,
  384. const char * name,
  385. void * data,
  386. size_t size,
  387. size_t max_size) {
  388. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  389. GGML_METAL_LOG_ERROR("%s: error: too many buffers\n", __func__);
  390. return false;
  391. }
  392. if (data) {
  393. // verify that the buffer does not overlap with any of the existing buffers
  394. for (int i = 0; i < ctx->n_buffers; ++i) {
  395. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  396. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  397. GGML_METAL_LOG_ERROR("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  398. return false;
  399. }
  400. }
  401. const size_t size_page = sysconf(_SC_PAGESIZE);
  402. size_t size_aligned = size;
  403. if ((size_aligned % size_page) != 0) {
  404. size_aligned += (size_page - (size_aligned % size_page));
  405. }
  406. // the buffer fits into the max buffer size allowed by the device
  407. if (size_aligned <= ctx->device.maxBufferLength) {
  408. ctx->buffers[ctx->n_buffers].name = name;
  409. ctx->buffers[ctx->n_buffers].data = data;
  410. ctx->buffers[ctx->n_buffers].size = size;
  411. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  412. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  413. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  414. return false;
  415. }
  416. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB", __func__, name, size_aligned / 1024.0 / 1024.0);
  417. ++ctx->n_buffers;
  418. } else {
  419. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  420. // one of the views
  421. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  422. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  423. const size_t size_view = ctx->device.maxBufferLength;
  424. for (size_t i = 0; i < size; i += size_step) {
  425. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  426. ctx->buffers[ctx->n_buffers].name = name;
  427. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  428. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  429. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  430. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  431. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  432. return false;
  433. }
  434. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  435. if (i + size_step < size) {
  436. GGML_METAL_LOG_INFO("\n");
  437. }
  438. ++ctx->n_buffers;
  439. }
  440. }
  441. #if TARGET_OS_OSX
  442. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  443. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  444. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  445. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  446. GGML_METAL_LOG_WARN(", warning: current allocated size is greater than the recommended max working set size\n", __func__);
  447. } else {
  448. GGML_METAL_LOG_INFO("\n");
  449. }
  450. #else
  451. GGML_METAL_LOG_INFO(", (%8.2f)\n", ctx->device.currentAllocatedSize / 1024.0 / 1024.0);
  452. #endif
  453. }
  454. return true;
  455. }
  456. void ggml_metal_set_tensor(
  457. struct ggml_metal_context * ctx,
  458. struct ggml_tensor * t) {
  459. size_t offs;
  460. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  461. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  462. }
  463. void ggml_metal_get_tensor(
  464. struct ggml_metal_context * ctx,
  465. struct ggml_tensor * t) {
  466. size_t offs;
  467. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  468. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  469. }
  470. void ggml_metal_graph_find_concurrency(
  471. struct ggml_metal_context * ctx,
  472. struct ggml_cgraph * gf, bool check_mem) {
  473. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  474. int nodes_unused[GGML_MAX_CONCUR];
  475. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  476. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  477. ctx->concur_list_len = 0;
  478. int n_left = gf->n_nodes;
  479. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  480. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  481. while (n_left > 0) {
  482. // number of nodes at a layer (that can be issued concurrently)
  483. int concurrency = 0;
  484. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  485. if (nodes_unused[i]) {
  486. // if the requirements for gf->nodes[i] are satisfied
  487. int exe_flag = 1;
  488. // scan all srcs
  489. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  490. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  491. if (src_cur) {
  492. // if is leaf nodes it's satisfied.
  493. // TODO: ggml_is_leaf()
  494. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  495. continue;
  496. }
  497. // otherwise this src should be the output from previous nodes.
  498. int is_found = 0;
  499. // scan 2*search_depth back because we inserted barrier.
  500. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  501. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  502. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  503. is_found = 1;
  504. break;
  505. }
  506. }
  507. if (is_found == 0) {
  508. exe_flag = 0;
  509. break;
  510. }
  511. }
  512. }
  513. if (exe_flag && check_mem) {
  514. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  515. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  516. int64_t data_start = (int64_t) gf->nodes[i]->data;
  517. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  518. for (int j = n_start; j < i; j++) {
  519. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  520. && gf->nodes[j]->op != GGML_OP_VIEW \
  521. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  522. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  523. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  524. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  525. continue;
  526. }
  527. exe_flag = 0;
  528. }
  529. }
  530. }
  531. if (exe_flag) {
  532. ctx->concur_list[level_pos + concurrency] = i;
  533. nodes_unused[i] = 0;
  534. concurrency++;
  535. ctx->concur_list_len++;
  536. }
  537. }
  538. }
  539. n_left -= concurrency;
  540. // adding a barrier different layer
  541. ctx->concur_list[level_pos + concurrency] = -1;
  542. ctx->concur_list_len++;
  543. // jump all sorted nodes at nodes_bak
  544. while (!nodes_unused[n_start]) {
  545. n_start++;
  546. }
  547. level_pos += concurrency + 1;
  548. }
  549. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  550. GGML_METAL_LOG_WARN("%s: too many elements for metal ctx->concur_list!\n", __func__);
  551. }
  552. }
  553. void ggml_metal_graph_compute(
  554. struct ggml_metal_context * ctx,
  555. struct ggml_cgraph * gf) {
  556. @autoreleasepool {
  557. // if there is ctx->concur_list, dispatch concurrently
  558. // else fallback to serial dispatch
  559. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  560. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  561. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  562. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  563. // create multiple command buffers and enqueue them
  564. // then, we encode the graph into the command buffers in parallel
  565. const int n_cb = ctx->n_cb;
  566. for (int i = 0; i < n_cb; ++i) {
  567. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  568. // enqueue the command buffers in order to specify their execution order
  569. [ctx->command_buffers[i] enqueue];
  570. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  571. }
  572. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  573. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  574. dispatch_async(ctx->d_queue, ^{
  575. size_t offs_src0 = 0;
  576. size_t offs_src1 = 0;
  577. size_t offs_dst = 0;
  578. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  579. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  580. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  581. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  582. for (int ind = node_start; ind < node_end; ++ind) {
  583. const int i = has_concur ? ctx->concur_list[ind] : ind;
  584. if (i == -1) {
  585. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  586. continue;
  587. }
  588. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  589. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  590. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  591. struct ggml_tensor * dst = gf->nodes[i];
  592. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  593. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  594. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  595. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  596. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  597. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  598. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  599. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  600. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  601. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  602. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  603. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  604. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  605. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  606. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  607. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  608. const int64_t ne0 = dst ? dst->ne[0] : 0;
  609. const int64_t ne1 = dst ? dst->ne[1] : 0;
  610. const int64_t ne2 = dst ? dst->ne[2] : 0;
  611. const int64_t ne3 = dst ? dst->ne[3] : 0;
  612. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  613. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  614. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  615. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  616. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  617. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  618. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  619. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  620. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  621. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  622. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  623. //if (src0) {
  624. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  625. // ggml_is_contiguous(src0), src0->name);
  626. //}
  627. //if (src1) {
  628. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  629. // ggml_is_contiguous(src1), src1->name);
  630. //}
  631. //if (dst) {
  632. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  633. // dst->name);
  634. //}
  635. switch (dst->op) {
  636. case GGML_OP_NONE:
  637. case GGML_OP_RESHAPE:
  638. case GGML_OP_VIEW:
  639. case GGML_OP_TRANSPOSE:
  640. case GGML_OP_PERMUTE:
  641. {
  642. // noop
  643. } break;
  644. case GGML_OP_ADD:
  645. {
  646. GGML_ASSERT(ggml_is_contiguous(src0));
  647. GGML_ASSERT(ggml_is_contiguous(src1));
  648. bool bcast_row = false;
  649. int64_t nb = ne00;
  650. if (ggml_nelements(src1) == ne10 && ne00 % 4 == 0) {
  651. // src1 is a row
  652. GGML_ASSERT(ne11 == 1);
  653. nb = ne00 / 4;
  654. [encoder setComputePipelineState:ctx->pipeline_add_row];
  655. bcast_row = true;
  656. } else {
  657. [encoder setComputePipelineState:ctx->pipeline_add];
  658. }
  659. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  660. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  661. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  662. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  663. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  664. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  665. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  666. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  667. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  668. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  669. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  670. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  671. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  672. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  673. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  674. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  675. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  676. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  677. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  678. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  679. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  680. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  681. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  682. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  683. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  684. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  685. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  686. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  687. if (bcast_row) {
  688. const int64_t n = ggml_nelements(dst)/4;
  689. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  690. } else {
  691. const int nth = MIN(1024, ne0);
  692. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  693. }
  694. } break;
  695. case GGML_OP_MUL:
  696. {
  697. GGML_ASSERT(ggml_is_contiguous(src0));
  698. GGML_ASSERT(ggml_is_contiguous(src1));
  699. // utilize float4
  700. GGML_ASSERT(ne00 % 4 == 0);
  701. const int64_t nb = ne00/4;
  702. if (ggml_nelements(src1) == ne10) {
  703. // src1 is a row
  704. GGML_ASSERT(ne11 == 1);
  705. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  706. } else {
  707. [encoder setComputePipelineState:ctx->pipeline_mul];
  708. }
  709. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  710. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  711. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  712. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  713. const int64_t n = ggml_nelements(dst)/4;
  714. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  715. } break;
  716. case GGML_OP_SCALE:
  717. {
  718. GGML_ASSERT(ggml_is_contiguous(src0));
  719. const float scale = *(const float *) src1->data;
  720. [encoder setComputePipelineState:ctx->pipeline_scale];
  721. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  722. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  723. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  724. const int64_t n = ggml_nelements(dst)/4;
  725. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  726. } break;
  727. case GGML_OP_UNARY:
  728. switch (ggml_get_unary_op(gf->nodes[i])) {
  729. case GGML_UNARY_OP_SILU:
  730. {
  731. [encoder setComputePipelineState:ctx->pipeline_silu];
  732. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  733. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  734. const int64_t n = ggml_nelements(dst)/4;
  735. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  736. } break;
  737. case GGML_UNARY_OP_RELU:
  738. {
  739. [encoder setComputePipelineState:ctx->pipeline_relu];
  740. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  741. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  742. const int64_t n = ggml_nelements(dst);
  743. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  744. } break;
  745. case GGML_UNARY_OP_GELU:
  746. {
  747. [encoder setComputePipelineState:ctx->pipeline_gelu];
  748. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  749. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  750. const int64_t n = ggml_nelements(dst)/4;
  751. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  752. } break;
  753. default:
  754. {
  755. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  756. GGML_ASSERT(false);
  757. }
  758. } break;
  759. case GGML_OP_SOFT_MAX:
  760. {
  761. const int nth = MIN(32, ne00);
  762. if (ne00%4 == 0) {
  763. [encoder setComputePipelineState:ctx->pipeline_soft_max_4];
  764. } else {
  765. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  766. }
  767. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  768. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  769. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  770. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  771. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  772. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  773. } break;
  774. case GGML_OP_DIAG_MASK_INF:
  775. {
  776. const int n_past = ((int32_t *)(dst->op_params))[0];
  777. if (ne00%8 == 0) {
  778. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf_8];
  779. } else {
  780. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  781. }
  782. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  783. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  784. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  785. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  786. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  787. if (ne00%8 == 0) {
  788. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  789. }
  790. else {
  791. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  792. }
  793. } break;
  794. case GGML_OP_MUL_MAT:
  795. {
  796. // TODO: needs to be updated after PR: https://github.com/ggerganov/ggml/pull/224
  797. GGML_ASSERT(ne00 == ne10);
  798. // GGML_ASSERT(ne02 == ne12); // Should be checked on individual data types until broadcast is implemented everywhere
  799. uint gqa = ne12/ne02;
  800. GGML_ASSERT(ne03 == ne13);
  801. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  802. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  803. if (!ggml_is_transposed(src0) &&
  804. !ggml_is_transposed(src1) &&
  805. src1t == GGML_TYPE_F32 &&
  806. [ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  807. ne00%32 == 0 &&
  808. ne11 > 2) {
  809. switch (src0->type) {
  810. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f32_f32]; break;
  811. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  812. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  813. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  814. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  815. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  816. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  817. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  818. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  819. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  820. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  821. }
  822. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  823. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  824. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  825. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  826. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  827. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  828. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  829. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  830. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  831. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  832. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  833. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  834. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  835. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:13];
  836. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  837. [encoder dispatchThreadgroups:MTLSizeMake( (ne11+31)/32, (ne01+63) / 64, ne12) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  838. } else {
  839. int nth0 = 32;
  840. int nth1 = 1;
  841. int nrows = 1;
  842. // use custom matrix x vector kernel
  843. switch (src0t) {
  844. case GGML_TYPE_F32:
  845. {
  846. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f32_f32];
  847. nrows = 4;
  848. } break;
  849. case GGML_TYPE_F16:
  850. {
  851. nth0 = 32;
  852. nth1 = 1;
  853. if (ne11 * ne12 < 4) {
  854. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32_1row];
  855. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  856. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32_l4];
  857. nrows = ne11;
  858. } else {
  859. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32];
  860. nrows = 4;
  861. }
  862. } break;
  863. case GGML_TYPE_Q4_0:
  864. {
  865. GGML_ASSERT(ne02 == 1);
  866. GGML_ASSERT(ne12 == 1);
  867. nth0 = 8;
  868. nth1 = 8;
  869. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_0_f32];
  870. } break;
  871. case GGML_TYPE_Q4_1:
  872. {
  873. GGML_ASSERT(ne02 == 1);
  874. GGML_ASSERT(ne12 == 1);
  875. nth0 = 8;
  876. nth1 = 8;
  877. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_1_f32];
  878. } break;
  879. case GGML_TYPE_Q8_0:
  880. {
  881. GGML_ASSERT(ne02 == 1);
  882. GGML_ASSERT(ne12 == 1);
  883. nth0 = 8;
  884. nth1 = 8;
  885. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q8_0_f32];
  886. } break;
  887. case GGML_TYPE_Q2_K:
  888. {
  889. GGML_ASSERT(ne02 == 1);
  890. GGML_ASSERT(ne12 == 1);
  891. nth0 = 2;
  892. nth1 = 32;
  893. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q2_K_f32];
  894. } break;
  895. case GGML_TYPE_Q3_K:
  896. {
  897. GGML_ASSERT(ne02 == 1);
  898. GGML_ASSERT(ne12 == 1);
  899. nth0 = 2;
  900. nth1 = 32;
  901. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q3_K_f32];
  902. } break;
  903. case GGML_TYPE_Q4_K:
  904. {
  905. GGML_ASSERT(ne02 == 1);
  906. GGML_ASSERT(ne12 == 1);
  907. nth0 = 4; //1;
  908. nth1 = 8; //32;
  909. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_K_f32];
  910. } break;
  911. case GGML_TYPE_Q5_K:
  912. {
  913. GGML_ASSERT(ne02 == 1);
  914. GGML_ASSERT(ne12 == 1);
  915. nth0 = 2;
  916. nth1 = 32;
  917. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q5_K_f32];
  918. } break;
  919. case GGML_TYPE_Q6_K:
  920. {
  921. GGML_ASSERT(ne02 == 1);
  922. GGML_ASSERT(ne12 == 1);
  923. nth0 = 2;
  924. nth1 = 32;
  925. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q6_K_f32];
  926. } break;
  927. default:
  928. {
  929. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  930. GGML_ASSERT(false && "not implemented");
  931. }
  932. };
  933. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  934. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  935. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  936. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  937. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  938. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  939. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  940. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  941. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  942. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  943. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  944. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  945. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  946. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  947. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  948. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  949. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  950. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:17];
  951. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 || src0t == GGML_TYPE_Q8_0 ||
  952. src0t == GGML_TYPE_Q2_K) {// || src0t == GGML_TYPE_Q4_K) {
  953. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  954. }
  955. else if (src0t == GGML_TYPE_Q4_K) {
  956. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  957. }
  958. else if (src0t == GGML_TYPE_Q3_K) {
  959. #ifdef GGML_QKK_64
  960. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  961. #else
  962. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  963. #endif
  964. }
  965. else if (src0t == GGML_TYPE_Q5_K) {
  966. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  967. }
  968. else if (src0t == GGML_TYPE_Q6_K) {
  969. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  970. } else {
  971. int64_t ny = (ne11 + nrows - 1)/nrows;
  972. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  973. }
  974. }
  975. } break;
  976. case GGML_OP_GET_ROWS:
  977. {
  978. switch (src0->type) {
  979. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_get_rows_f32]; break;
  980. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  981. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  982. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  983. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  984. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  985. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  986. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  987. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  988. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  989. default: GGML_ASSERT(false && "not implemented");
  990. }
  991. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  992. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  993. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  994. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  995. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  996. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:5];
  997. const int64_t n = ggml_nelements(src1);
  998. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  999. } break;
  1000. case GGML_OP_RMS_NORM:
  1001. {
  1002. float eps;
  1003. memcpy(&eps, dst->op_params, sizeof(float));
  1004. const int nth = MIN(512, ne00);
  1005. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  1006. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1007. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1008. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1009. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1010. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1011. [encoder setThreadgroupMemoryLength:nth/32*sizeof(float) atIndex:0];
  1012. const int64_t nrows = ggml_nrows(src0);
  1013. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1014. } break;
  1015. case GGML_OP_NORM:
  1016. {
  1017. float eps;
  1018. memcpy(&eps, dst->op_params, sizeof(float));
  1019. const int nth = MIN(256, ne00);
  1020. [encoder setComputePipelineState:ctx->pipeline_norm];
  1021. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1022. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1023. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1024. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1025. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1026. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  1027. const int64_t nrows = ggml_nrows(src0);
  1028. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1029. } break;
  1030. case GGML_OP_ALIBI:
  1031. {
  1032. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1033. const int nth = MIN(1024, ne00);
  1034. const int n_past = ((int32_t *) dst->op_params)[0]; UNUSED(n_past);
  1035. const int n_head = ((int32_t *) dst->op_params)[1];
  1036. float max_bias;
  1037. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1038. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1039. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1040. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  1041. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  1042. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1043. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1044. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1045. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1046. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1047. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1048. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1049. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1050. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1051. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1052. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1053. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1054. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1055. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1056. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1057. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1058. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1059. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1060. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1061. [encoder setBytes:&m1 length:sizeof( float) atIndex:19];
  1062. [encoder setBytes:&n_heads_log2_floor length:sizeof(int) atIndex:20];
  1063. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1064. } break;
  1065. case GGML_OP_ROPE:
  1066. {
  1067. GGML_ASSERT(ne10 == ne02);
  1068. const int nth = MIN(1024, ne00);
  1069. const int n_past = ((int32_t *) dst->op_params)[0];
  1070. const int n_dims = ((int32_t *) dst->op_params)[1];
  1071. const int mode = ((int32_t *) dst->op_params)[2];
  1072. float freq_base;
  1073. float freq_scale;
  1074. memcpy(&freq_base, (int32_t *) dst->op_params + 4, sizeof(float));
  1075. memcpy(&freq_scale, (int32_t *) dst->op_params + 5, sizeof(float));
  1076. switch (src0->type) {
  1077. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_rope_f32]; break;
  1078. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_rope_f16]; break;
  1079. default: GGML_ASSERT(false);
  1080. };
  1081. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1082. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1083. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1084. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1085. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:4];
  1086. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:5];
  1087. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:6];
  1088. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:7];
  1089. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:8];
  1090. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:9];
  1091. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:10];
  1092. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:11];
  1093. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:12];
  1094. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:13];
  1095. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:14];
  1096. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:15];
  1097. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:16];
  1098. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:17];
  1099. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:18];
  1100. [encoder setBytes:&n_past length:sizeof( int) atIndex:19];
  1101. [encoder setBytes:&n_dims length:sizeof( int) atIndex:20];
  1102. [encoder setBytes:&mode length:sizeof( int) atIndex:21];
  1103. [encoder setBytes:&freq_base length:sizeof(float) atIndex:22];
  1104. [encoder setBytes:&freq_scale length:sizeof(float) atIndex:23];
  1105. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1106. } break;
  1107. case GGML_OP_DUP:
  1108. case GGML_OP_CPY:
  1109. case GGML_OP_CONT:
  1110. {
  1111. const int nth = MIN(1024, ne00);
  1112. switch (src0t) {
  1113. case GGML_TYPE_F32:
  1114. {
  1115. switch (dstt) {
  1116. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  1117. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  1118. default: GGML_ASSERT(false && "not implemented");
  1119. };
  1120. } break;
  1121. case GGML_TYPE_F16:
  1122. {
  1123. switch (dstt) {
  1124. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  1125. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  1126. default: GGML_ASSERT(false && "not implemented");
  1127. };
  1128. } break;
  1129. default: GGML_ASSERT(false && "not implemented");
  1130. }
  1131. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1132. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1133. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1134. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1135. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1136. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1137. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1138. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1139. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1140. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1141. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1142. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1143. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1144. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1145. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1146. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1147. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1148. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1149. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1150. } break;
  1151. default:
  1152. {
  1153. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1154. GGML_ASSERT(false);
  1155. }
  1156. }
  1157. }
  1158. if (encoder != nil) {
  1159. [encoder endEncoding];
  1160. encoder = nil;
  1161. }
  1162. [command_buffer commit];
  1163. });
  1164. }
  1165. // wait for all threads to finish
  1166. dispatch_barrier_sync(ctx->d_queue, ^{});
  1167. // check status of command buffers
  1168. // needed to detect if the device ran out-of-memory for example (#1881)
  1169. for (int i = 0; i < n_cb; i++) {
  1170. [ctx->command_buffers[i] waitUntilCompleted];
  1171. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  1172. if (status != MTLCommandBufferStatusCompleted) {
  1173. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  1174. GGML_ASSERT(false);
  1175. }
  1176. }
  1177. }
  1178. }