ggml-metal.m 56 KB

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