ggml-metal.m 56 KB

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