ggml-metal.m 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. #ifdef GGML_METAL_NDEBUG
  7. #define metal_printf(...)
  8. #else
  9. #define metal_printf(...) fprintf(stderr, __VA_ARGS__)
  10. #endif
  11. #define UNUSED(x) (void)(x)
  12. struct ggml_metal_buffer {
  13. const char * name;
  14. void * data;
  15. size_t size;
  16. id<MTLBuffer> metal;
  17. };
  18. struct ggml_metal_context {
  19. float * logits;
  20. id<MTLDevice> device;
  21. id<MTLCommandQueue> queue;
  22. id<MTLLibrary> library;
  23. int n_buffers;
  24. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  25. // custom kernels
  26. #define GGML_METAL_DECL_KERNEL(name) \
  27. id<MTLFunction> function_##name; \
  28. id<MTLComputePipelineState> pipeline_##name
  29. GGML_METAL_DECL_KERNEL(add);
  30. GGML_METAL_DECL_KERNEL(mul);
  31. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  32. GGML_METAL_DECL_KERNEL(scale);
  33. GGML_METAL_DECL_KERNEL(silu);
  34. GGML_METAL_DECL_KERNEL(relu);
  35. GGML_METAL_DECL_KERNEL(gelu);
  36. GGML_METAL_DECL_KERNEL(soft_max);
  37. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  38. GGML_METAL_DECL_KERNEL(get_rows_f16);
  39. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  40. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  41. GGML_METAL_DECL_KERNEL(get_rows_q2_k);
  42. GGML_METAL_DECL_KERNEL(get_rows_q3_k);
  43. GGML_METAL_DECL_KERNEL(get_rows_q4_k);
  44. GGML_METAL_DECL_KERNEL(get_rows_q5_k);
  45. GGML_METAL_DECL_KERNEL(get_rows_q6_k);
  46. GGML_METAL_DECL_KERNEL(rms_norm);
  47. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32);
  48. GGML_METAL_DECL_KERNEL(mul_mat_q4_0_f32);
  49. GGML_METAL_DECL_KERNEL(mul_mat_q4_1_f32);
  50. GGML_METAL_DECL_KERNEL(mul_mat_q2_k_f32);
  51. GGML_METAL_DECL_KERNEL(mul_mat_q3_k_f32);
  52. GGML_METAL_DECL_KERNEL(mul_mat_q4_k_f32);
  53. GGML_METAL_DECL_KERNEL(mul_mat_q5_k_f32);
  54. GGML_METAL_DECL_KERNEL(mul_mat_q6_k_f32);
  55. GGML_METAL_DECL_KERNEL(rope);
  56. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  57. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  58. #undef GGML_METAL_DECL_KERNEL
  59. };
  60. // MSL code
  61. // TODO: move the contents here when ready
  62. // for now it is easier to work in a separate file
  63. static NSString * const msl_library_source = @"see metal.metal";
  64. // Here to assist with NSBundle Path Hack
  65. @interface GGMLMetalClass : NSObject
  66. @end
  67. @implementation GGMLMetalClass
  68. @end
  69. struct ggml_metal_context * ggml_metal_init(void) {
  70. fprintf(stderr, "%s: allocating\n", __func__);
  71. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  72. ctx->device = MTLCreateSystemDefaultDevice();
  73. ctx->queue = [ctx->device newCommandQueue];
  74. ctx->n_buffers = 0;
  75. // determine if we can use MPS
  76. if (MPSSupportsMTLDevice(ctx->device)) {
  77. fprintf(stderr, "%s: using MPS\n", __func__);
  78. } else {
  79. fprintf(stderr, "%s: not using MPS\n", __func__);
  80. GGML_ASSERT(false && "MPS not supported");
  81. }
  82. #if 0
  83. // compile from source string and show compile log
  84. {
  85. NSError * error = nil;
  86. ctx->library = [ctx->device newLibraryWithSource:msl_library_source options:nil error:&error];
  87. if (error) {
  88. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  89. exit(1);
  90. }
  91. }
  92. #else
  93. UNUSED(msl_library_source);
  94. // read the source from "ggml-metal.metal" into a string and use newLibraryWithSource
  95. {
  96. NSError * error = nil;
  97. //NSString * path = [[NSBundle mainBundle] pathForResource:@"../../examples/metal/metal" ofType:@"metal"];
  98. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  99. NSString * path = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  100. fprintf(stderr, "%s: loading '%s'\n", __func__, [path UTF8String]);
  101. NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
  102. if (error) {
  103. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  104. exit(1);
  105. }
  106. ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];
  107. if (error) {
  108. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  109. exit(1);
  110. }
  111. }
  112. #endif
  113. // load kernels
  114. {
  115. #define GGML_METAL_ADD_KERNEL(name) \
  116. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  117. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:nil]; \
  118. fprintf(stderr, "%s: loaded %-32s %16p\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name);
  119. GGML_METAL_ADD_KERNEL(add);
  120. GGML_METAL_ADD_KERNEL(mul);
  121. GGML_METAL_ADD_KERNEL(mul_row);
  122. GGML_METAL_ADD_KERNEL(scale);
  123. GGML_METAL_ADD_KERNEL(silu);
  124. GGML_METAL_ADD_KERNEL(relu);
  125. GGML_METAL_ADD_KERNEL(gelu);
  126. GGML_METAL_ADD_KERNEL(soft_max);
  127. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  128. GGML_METAL_ADD_KERNEL(get_rows_f16);
  129. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  130. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  131. GGML_METAL_ADD_KERNEL(get_rows_q2_k);
  132. GGML_METAL_ADD_KERNEL(get_rows_q3_k);
  133. GGML_METAL_ADD_KERNEL(get_rows_q4_k);
  134. GGML_METAL_ADD_KERNEL(get_rows_q5_k);
  135. GGML_METAL_ADD_KERNEL(get_rows_q6_k);
  136. GGML_METAL_ADD_KERNEL(rms_norm);
  137. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32);
  138. GGML_METAL_ADD_KERNEL(mul_mat_q4_0_f32);
  139. GGML_METAL_ADD_KERNEL(mul_mat_q4_1_f32);
  140. GGML_METAL_ADD_KERNEL(mul_mat_q2_k_f32);
  141. GGML_METAL_ADD_KERNEL(mul_mat_q3_k_f32);
  142. GGML_METAL_ADD_KERNEL(mul_mat_q4_k_f32);
  143. GGML_METAL_ADD_KERNEL(mul_mat_q5_k_f32);
  144. GGML_METAL_ADD_KERNEL(mul_mat_q6_k_f32);
  145. GGML_METAL_ADD_KERNEL(rope);
  146. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  147. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  148. #undef GGML_METAL_ADD_KERNEL
  149. }
  150. return ctx;
  151. }
  152. void ggml_metal_free(struct ggml_metal_context * ctx) {
  153. fprintf(stderr, "%s: deallocating\n", __func__);
  154. free(ctx);
  155. }
  156. // finds the Metal buffer that contains the tensor data on the GPU device
  157. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  158. // Metal buffer based on the host memory pointer
  159. //
  160. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  161. //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);
  162. for (int i = 0; i < ctx->n_buffers; ++i) {
  163. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  164. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  165. *offs = (size_t) ioffs;
  166. //fprintf(stderr, "%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  167. return ctx->buffers[i].metal;
  168. }
  169. }
  170. fprintf(stderr, "%s: error: buffer is nil\n", __func__);
  171. return nil;
  172. }
  173. bool ggml_metal_add_buffer(
  174. struct ggml_metal_context * ctx,
  175. const char * name,
  176. void * data,
  177. size_t size) {
  178. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  179. fprintf(stderr, "%s: too many buffers\n", __func__);
  180. return false;
  181. }
  182. if (data) {
  183. // verify that the buffer does not overlap with any of the existing buffers
  184. for (int i = 0; i < ctx->n_buffers; ++i) {
  185. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  186. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  187. fprintf(stderr, "%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  188. return false;
  189. }
  190. }
  191. size_t page_size = getpagesize();
  192. size_t aligned_size = size;
  193. if ((aligned_size % page_size) != 0) {
  194. aligned_size += (page_size - (aligned_size % page_size));
  195. }
  196. ctx->buffers[ctx->n_buffers].name = name;
  197. ctx->buffers[ctx->n_buffers].data = data;
  198. ctx->buffers[ctx->n_buffers].size = size;
  199. if (ctx->device.maxBufferLength < aligned_size) {
  200. fprintf(stderr, "%s: buffer '%s' size %zu is larger than buffer maximum of %zu\n", __func__, name, aligned_size, ctx->device.maxBufferLength);
  201. return false;
  202. }
  203. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:aligned_size options:MTLResourceStorageModeShared deallocator:nil];
  204. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  205. fprintf(stderr, "%s: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, aligned_size / 1024.0 / 1024.0);
  206. return false;
  207. } else {
  208. fprintf(stderr, "%s: allocated '%-16s' buffer, size = %8.2f MB\n", __func__, name, aligned_size / 1024.0 / 1024.0);
  209. }
  210. ++ctx->n_buffers;
  211. }
  212. return true;
  213. }
  214. void ggml_metal_set_tensor(
  215. struct ggml_metal_context * ctx,
  216. struct ggml_tensor * t) {
  217. metal_printf("%s: set input for tensor '%s'\n", __func__, t->name);
  218. size_t offs;
  219. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  220. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  221. }
  222. void ggml_metal_get_tensor(
  223. struct ggml_metal_context * ctx,
  224. struct ggml_tensor * t) {
  225. metal_printf("%s: extract results for tensor '%s'\n", __func__, t->name);
  226. size_t offs;
  227. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  228. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  229. }
  230. void ggml_metal_graph_compute(
  231. struct ggml_metal_context * ctx,
  232. struct ggml_cgraph * gf) {
  233. metal_printf("%s: evaluating graph\n", __func__);
  234. // create multiple command buffers and enqueue them
  235. // then, we encode the graph into the command buffers in parallel
  236. const int n_cb = gf->n_threads;
  237. NSMutableArray * command_buffers = [NSMutableArray arrayWithCapacity:n_cb];
  238. for (int i = 0; i < n_cb; ++i) {
  239. command_buffers[i] = [ctx->queue commandBuffer];
  240. // enqueue the command buffers in order to specify their execution order
  241. [command_buffers[i] enqueue];
  242. }
  243. // TODO: is this the best way to start threads?
  244. dispatch_queue_t queue = dispatch_queue_create("llama.cpp", DISPATCH_QUEUE_CONCURRENT);
  245. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  246. const int n_nodes_per_cb = (gf->n_nodes + n_cb - 1) / n_cb;
  247. dispatch_async(queue, ^{
  248. size_t offs_src0 = 0;
  249. size_t offs_src1 = 0;
  250. size_t offs_dst = 0;
  251. id<MTLCommandBuffer> command_buffer = command_buffers[cb_idx];
  252. id<MTLComputeCommandEncoder> encoder = nil;
  253. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  254. const int node_end = (cb_idx == n_cb - 1) ? gf->n_nodes : (cb_idx + 1) * n_nodes_per_cb;
  255. for (int i = node_start; i < node_end; ++i) {
  256. metal_printf("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  257. struct ggml_tensor * src0 = gf->nodes[i]->src0;
  258. struct ggml_tensor * src1 = gf->nodes[i]->src1;
  259. struct ggml_tensor * dst = gf->nodes[i];
  260. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  261. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  262. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  263. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  264. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  265. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  266. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  267. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  268. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  269. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  270. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  271. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  272. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  273. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  274. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  275. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  276. const int64_t ne0 = dst ? dst->ne[0] : 0;
  277. const int64_t ne1 = dst ? dst->ne[1] : 0;
  278. const int64_t ne2 = dst ? dst->ne[2] : 0;
  279. const int64_t ne3 = dst ? dst->ne[3] : 0;
  280. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  281. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  282. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  283. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  284. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  285. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  286. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  287. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  288. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  289. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  290. //metal_printf("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  291. //if (src0) {
  292. // metal_printf("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  293. // ggml_is_contiguous(src0), src0->name);
  294. //}
  295. //if (src1) {
  296. // metal_printf("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  297. // ggml_is_contiguous(src1), src1->name);
  298. //}
  299. //if (dst) {
  300. // metal_printf("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  301. // dst->name);
  302. //}
  303. switch (dst->op) {
  304. case GGML_OP_RESHAPE:
  305. case GGML_OP_VIEW:
  306. case GGML_OP_TRANSPOSE:
  307. case GGML_OP_PERMUTE:
  308. {
  309. // noop
  310. } break;
  311. case GGML_OP_ADD:
  312. {
  313. if (encoder == nil) {
  314. encoder = [command_buffer computeCommandEncoder];
  315. }
  316. [encoder setComputePipelineState:ctx->pipeline_add];
  317. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  318. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  319. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  320. const int64_t n = ggml_nelements(dst);
  321. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  322. } break;
  323. case GGML_OP_MUL:
  324. {
  325. if (encoder == nil) {
  326. encoder = [command_buffer computeCommandEncoder];
  327. }
  328. if (ggml_nelements(src1) == ne10) {
  329. // src1 is a row
  330. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  331. } else {
  332. [encoder setComputePipelineState:ctx->pipeline_mul];
  333. }
  334. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  335. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  336. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  337. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  338. const int64_t n = ggml_nelements(dst);
  339. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  340. } break;
  341. case GGML_OP_SCALE:
  342. {
  343. if (encoder == nil) {
  344. encoder = [command_buffer computeCommandEncoder];
  345. }
  346. const float scale = *(const float *) src1->data;
  347. [encoder setComputePipelineState:ctx->pipeline_scale];
  348. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  349. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  350. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  351. const int64_t n = ggml_nelements(dst);
  352. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  353. } break;
  354. case GGML_OP_SILU:
  355. {
  356. if (encoder == nil) {
  357. encoder = [command_buffer computeCommandEncoder];
  358. }
  359. [encoder setComputePipelineState:ctx->pipeline_silu];
  360. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  361. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  362. const int64_t n = ggml_nelements(dst);
  363. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  364. } break;
  365. case GGML_OP_RELU:
  366. {
  367. if (encoder == nil) {
  368. encoder = [command_buffer computeCommandEncoder];
  369. }
  370. [encoder setComputePipelineState:ctx->pipeline_relu];
  371. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  372. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  373. const int64_t n = ggml_nelements(dst);
  374. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  375. } break;
  376. case GGML_OP_GELU:
  377. {
  378. if (encoder == nil) {
  379. encoder = [command_buffer computeCommandEncoder];
  380. }
  381. [encoder setComputePipelineState:ctx->pipeline_gelu];
  382. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  383. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  384. const int64_t n = ggml_nelements(dst);
  385. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  386. } break;
  387. case GGML_OP_SOFT_MAX:
  388. {
  389. if (encoder == nil) {
  390. encoder = [command_buffer computeCommandEncoder];
  391. }
  392. const int nth = 32;
  393. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  394. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  395. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  396. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  397. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  398. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  399. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  400. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  401. } break;
  402. case GGML_OP_DIAG_MASK_INF:
  403. {
  404. if (encoder == nil) {
  405. encoder = [command_buffer computeCommandEncoder];
  406. }
  407. const int n_past = ((int32_t *)(src1->data))[0];
  408. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  409. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  410. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  411. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  412. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  413. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  414. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  415. } break;
  416. case GGML_OP_MUL_MAT:
  417. {
  418. // TODO: needs to be updated after PR: https://github.com/ggerganov/ggml/pull/224
  419. GGML_ASSERT(ne00 == ne10);
  420. GGML_ASSERT(ne02 == ne12);
  421. if (ggml_is_contiguous(src0) &&
  422. ggml_is_contiguous(src1) &&
  423. (src0t == GGML_TYPE_F32 || src0t == GGML_TYPE_F16) && ne11 > 1) {
  424. if (encoder != nil) {
  425. [encoder endEncoding];
  426. encoder = nil;
  427. }
  428. MPSDataType src0dt = src0t == GGML_TYPE_F32 ? MPSDataTypeFloat32 : MPSDataTypeFloat16;
  429. MPSDataType src1dt = src1t == GGML_TYPE_F32 ? MPSDataTypeFloat32 : MPSDataTypeFloat16;
  430. // for F32 x F32 we use MPS
  431. MPSMatrixDescriptor * desc0 = [MPSMatrixDescriptor
  432. matrixDescriptorWithRows:ne01 columns:ne00 rowBytes:src0->nb[1] dataType:src0dt];
  433. MPSMatrixDescriptor * desc1 = [MPSMatrixDescriptor
  434. matrixDescriptorWithRows:ne11 columns:ne10 rowBytes:src1->nb[1] dataType:src1dt];
  435. MPSMatrixDescriptor * desc = [MPSMatrixDescriptor
  436. matrixDescriptorWithRows:ne1 columns:ne0 rowBytes:dst->nb[1] dataType:MPSDataTypeFloat32];
  437. MPSMatrixMultiplication * mul = [[MPSMatrixMultiplication alloc]
  438. initWithDevice:ctx->device transposeLeft:false transposeRight:true
  439. resultRows:ne11 resultColumns:ne01 interiorColumns:ne00 alpha:1.0 beta:0.0];
  440. // we need to do ne02 multiplications
  441. // TODO: is there a way to do this in parallel - currently very slow ..
  442. // TODO: might be possible to offload part of the computation to ANE using Accelerate's CBLAS
  443. for (int64_t i02 = 0; i02 < ne02; ++i02) {
  444. size_t offs_src0_cur = offs_src0 + i02*nb02;
  445. size_t offs_src1_cur = offs_src1 + i02*nb12;
  446. size_t offs_dst_cur = offs_dst + i02*nb2;
  447. MPSMatrix * mat_src0 = [[MPSMatrix alloc] initWithBuffer:id_src0 offset:offs_src0_cur descriptor:desc0];
  448. MPSMatrix * mat_src1 = [[MPSMatrix alloc] initWithBuffer:id_src1 offset:offs_src1_cur descriptor:desc1];
  449. MPSMatrix * mat_dst = [[MPSMatrix alloc] initWithBuffer:id_dst offset:offs_dst_cur descriptor:desc ];
  450. [mul encodeToCommandBuffer:command_buffer leftMatrix:mat_src1 rightMatrix:mat_src0 resultMatrix:mat_dst];
  451. }
  452. } else {
  453. if (encoder == nil) {
  454. encoder = [command_buffer computeCommandEncoder];
  455. }
  456. int nth0 = 32;
  457. int nth1 = 1;
  458. // use custom matrix x vector kernel
  459. switch (src0t) {
  460. case GGML_TYPE_F16:
  461. {
  462. GGML_ASSERT(ne02 == ne12);
  463. nth0 = 64;
  464. nth1 = 1;
  465. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32];
  466. } break;
  467. case GGML_TYPE_Q4_0:
  468. {
  469. GGML_ASSERT(ne02 == 1);
  470. GGML_ASSERT(ne12 == 1);
  471. nth0 = 8;
  472. nth1 = 8;
  473. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_0_f32];
  474. } break;
  475. case GGML_TYPE_Q4_1:
  476. {
  477. GGML_ASSERT(ne02 == 1);
  478. GGML_ASSERT(ne12 == 1);
  479. nth0 = 8;
  480. nth1 = 8;
  481. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_1_f32];
  482. } break;
  483. case GGML_TYPE_Q2_K:
  484. {
  485. GGML_ASSERT(ne02 == 1);
  486. GGML_ASSERT(ne12 == 1);
  487. nth0 = 4;
  488. nth1 = 16;
  489. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q2_k_f32];
  490. } break;
  491. case GGML_TYPE_Q3_K:
  492. {
  493. GGML_ASSERT(ne02 == 1);
  494. GGML_ASSERT(ne12 == 1);
  495. nth0 = 4;
  496. nth1 = 16;
  497. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q3_k_f32];
  498. } break;
  499. case GGML_TYPE_Q4_K:
  500. {
  501. GGML_ASSERT(ne02 == 1);
  502. GGML_ASSERT(ne12 == 1);
  503. nth0 = 4;
  504. nth1 = 16;
  505. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_k_f32];
  506. } break;
  507. case GGML_TYPE_Q5_K:
  508. {
  509. GGML_ASSERT(ne02 == 1);
  510. GGML_ASSERT(ne12 == 1);
  511. nth0 = 4;
  512. nth1 = 16;
  513. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q5_k_f32];
  514. } break;
  515. case GGML_TYPE_Q6_K:
  516. {
  517. GGML_ASSERT(ne02 == 1);
  518. GGML_ASSERT(ne12 == 1);
  519. nth0 = 4;
  520. nth1 = 16;
  521. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q6_k_f32];
  522. } break;
  523. default:
  524. {
  525. fprintf(stderr, "Asserting on type %d\n",(int)src0t);
  526. GGML_ASSERT(false && "not implemented");
  527. }
  528. };
  529. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  530. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  531. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  532. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  533. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  534. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:5];
  535. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:6];
  536. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:7];
  537. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:8];
  538. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:9];
  539. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:10];
  540. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:11];
  541. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:12];
  542. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:13];
  543. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:14];
  544. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1) {
  545. [encoder setThreadgroupMemoryLength:nth0*nth1*sizeof(float) atIndex:0];
  546. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne11, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  547. }
  548. else if (src0t == GGML_TYPE_Q2_K ||
  549. src0t == GGML_TYPE_Q3_K ||
  550. src0t == GGML_TYPE_Q4_K ||
  551. src0t == GGML_TYPE_Q5_K ||
  552. src0t == GGML_TYPE_Q6_K) {
  553. [encoder setThreadgroupMemoryLength:nth0*nth1*sizeof(float) atIndex:0];
  554. [encoder dispatchThreadgroups:MTLSizeMake(ne01, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  555. } else {
  556. [encoder setThreadgroupMemoryLength:nth0*sizeof(float) atIndex:0];
  557. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  558. }
  559. }
  560. } break;
  561. case GGML_OP_GET_ROWS:
  562. {
  563. if (encoder == nil) {
  564. encoder = [command_buffer computeCommandEncoder];
  565. }
  566. switch (src0->type) {
  567. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  568. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  569. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  570. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_k]; break;
  571. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_k]; break;
  572. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_k]; break;
  573. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_k]; break;
  574. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_k]; break;
  575. default: GGML_ASSERT(false && "not implemented");
  576. }
  577. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  578. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  579. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  580. [encoder setBytes:&(src0->ne[0]) length:sizeof( int64_t) atIndex:3];
  581. [encoder setBytes:&(src0->nb[1]) length:sizeof(uint64_t) atIndex:4];
  582. [encoder setBytes:&(dst->nb[1]) length:sizeof(uint64_t) atIndex:5];
  583. const int64_t n = ggml_nelements(src1);
  584. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  585. } break;
  586. case GGML_OP_RMS_NORM:
  587. {
  588. if (encoder == nil) {
  589. encoder = [command_buffer computeCommandEncoder];
  590. }
  591. const float eps = 1e-6f;
  592. const int nth = 256;
  593. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  594. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  595. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  596. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  597. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  598. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  599. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  600. const int64_t nrows = ggml_nrows(src0);
  601. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  602. } break;
  603. case GGML_OP_ROPE:
  604. {
  605. if (encoder == nil) {
  606. encoder = [command_buffer computeCommandEncoder];
  607. }
  608. const int n_dims = ((int32_t *) src1->data)[1];
  609. const int mode = ((int32_t *) src1->data)[2];
  610. const int n_past = ((int32_t *)(src1->data))[0];
  611. [encoder setComputePipelineState:ctx->pipeline_rope];
  612. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  613. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  614. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  615. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  616. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  617. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  618. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  619. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  620. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  621. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  622. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  623. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  624. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  625. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  626. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  627. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  628. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  629. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  630. [encoder setBytes:&n_past length:sizeof( int) atIndex:18];
  631. [encoder setBytes:&n_dims length:sizeof( int) atIndex:19];
  632. [encoder setBytes:&mode length:sizeof( int) atIndex:20];
  633. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  634. } break;
  635. case GGML_OP_CPY:
  636. {
  637. if (encoder == nil) {
  638. encoder = [command_buffer computeCommandEncoder];
  639. }
  640. const int nth = 32;
  641. switch (src0t) {
  642. case GGML_TYPE_F32:
  643. {
  644. switch (dstt) {
  645. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  646. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  647. default: GGML_ASSERT(false && "not implemented");
  648. };
  649. } break;
  650. default: GGML_ASSERT(false && "not implemented");
  651. }
  652. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  653. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  654. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  655. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  656. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  657. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  658. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  659. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  660. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  661. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  662. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  663. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  664. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  665. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  666. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  667. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  668. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  669. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  670. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  671. } break;
  672. default:
  673. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  674. GGML_ASSERT(false);
  675. }
  676. }
  677. if (encoder != nil) {
  678. [encoder endEncoding];
  679. encoder = nil;
  680. }
  681. [command_buffer commit];
  682. });
  683. }
  684. // wait for all threads to finish
  685. dispatch_barrier_sync(queue, ^{});
  686. [command_buffers[n_cb - 1] waitUntilCompleted];
  687. }