ggml-metal.m 32 KB

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