ggml-metal.m 64 KB

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