ggml-metal.m 33 KB

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