ggml-metal.m 30 KB

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