ggml-metal.m 30 KB

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