ggml-metal.m 45 KB

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