ggml-metal.m 60 KB

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