ggml-metal.m 57 KB

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