ggml-metal.m 35 KB

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