ggml-metal.m 55 KB

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