ggml-metal.m 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. //go:build darwin
  2. /**
  3. * llama.cpp - git e782c9e735f93ab4767ffc37462c523b73a17ddc
  4. *
  5. * MIT License
  6. *
  7. * Copyright (c) 2023 Georgi Gerganov
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in all
  17. * copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. * SOFTWARE.
  26. */
  27. #import "ggml-metal.h"
  28. #import "ggml.h"
  29. #import <Foundation/Foundation.h>
  30. #import <Metal/Metal.h>
  31. #import <MetalPerformanceShaders/MetalPerformanceShaders.h>
  32. #ifdef GGML_METAL_NDEBUG
  33. #define metal_printf(...)
  34. #else
  35. #define metal_printf(...) fprintf(stderr, __VA_ARGS__)
  36. #endif
  37. #define UNUSED(x) (void)(x)
  38. struct ggml_metal_buffer {
  39. const char * name;
  40. void * data;
  41. size_t size;
  42. id<MTLBuffer> metal;
  43. };
  44. struct ggml_metal_context {
  45. int n_cb;
  46. float * logits;
  47. id<MTLDevice> device;
  48. id<MTLCommandQueue> queue;
  49. id<MTLLibrary> library;
  50. int n_buffers;
  51. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  52. // custom kernels
  53. #define GGML_METAL_DECL_KERNEL(name) \
  54. id<MTLFunction> function_##name; \
  55. id<MTLComputePipelineState> pipeline_##name
  56. GGML_METAL_DECL_KERNEL(add);
  57. GGML_METAL_DECL_KERNEL(mul);
  58. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  59. GGML_METAL_DECL_KERNEL(scale);
  60. GGML_METAL_DECL_KERNEL(silu);
  61. GGML_METAL_DECL_KERNEL(relu);
  62. GGML_METAL_DECL_KERNEL(gelu);
  63. GGML_METAL_DECL_KERNEL(soft_max);
  64. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  65. GGML_METAL_DECL_KERNEL(get_rows_f16);
  66. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  67. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  68. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  69. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  70. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  71. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  72. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  73. GGML_METAL_DECL_KERNEL(rms_norm);
  74. GGML_METAL_DECL_KERNEL(norm);
  75. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mat_q4_0_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mat_q4_1_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mat_q2_K_f32);
  79. GGML_METAL_DECL_KERNEL(mul_mat_q3_K_f32);
  80. GGML_METAL_DECL_KERNEL(mul_mat_q4_K_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mat_q5_K_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mat_q6_K_f32);
  83. GGML_METAL_DECL_KERNEL(rope);
  84. GGML_METAL_DECL_KERNEL(alibi_f32);
  85. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  86. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  87. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  88. #undef GGML_METAL_DECL_KERNEL
  89. };
  90. // MSL code
  91. // TODO: move the contents here when ready
  92. // for now it is easier to work in a separate file
  93. static NSString * const msl_library_source = @"see metal.metal";
  94. // Here to assist with NSBundle Path Hack
  95. @interface GGMLMetalClass : NSObject
  96. @end
  97. @implementation GGMLMetalClass
  98. @end
  99. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  100. fprintf(stderr, "%s: allocating\n", __func__);
  101. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  102. ctx->n_cb = n_cb;
  103. ctx->device = MTLCreateSystemDefaultDevice();
  104. ctx->queue = [ctx->device newCommandQueue];
  105. ctx->n_buffers = 0;
  106. // determine if we can use MPS
  107. if (MPSSupportsMTLDevice(ctx->device)) {
  108. fprintf(stderr, "%s: using MPS\n", __func__);
  109. } else {
  110. fprintf(stderr, "%s: not using MPS\n", __func__);
  111. GGML_ASSERT(false && "MPS not supported");
  112. }
  113. #if 0
  114. // compile from source string and show compile log
  115. {
  116. NSError * error = nil;
  117. ctx->library = [ctx->device newLibraryWithSource:msl_library_source options:nil error:&error];
  118. if (error) {
  119. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  120. exit(1);
  121. }
  122. }
  123. #else
  124. UNUSED(msl_library_source);
  125. // read the source from "ggml-metal.metal" into a string and use newLibraryWithSource
  126. {
  127. NSError * error = nil;
  128. //NSString * path = [[NSBundle mainBundle] pathForResource:@"../../examples/metal/metal" ofType:@"metal"];
  129. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  130. NSString * path = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  131. fprintf(stderr, "%s: loading '%s'\n", __func__, [path UTF8String]);
  132. NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
  133. if (error) {
  134. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  135. exit(1);
  136. }
  137. #ifdef GGML_QKK_64
  138. MTLCompileOptions* options = [MTLCompileOptions new];
  139. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  140. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  141. #else
  142. ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];
  143. #endif
  144. if (error) {
  145. fprintf(stderr, "%s: error: %s\n", __func__, [[error description] UTF8String]);
  146. exit(1);
  147. }
  148. }
  149. #endif
  150. // load kernels
  151. {
  152. #define GGML_METAL_ADD_KERNEL(name) \
  153. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  154. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:nil]; \
  155. fprintf(stderr, "%s: loaded %-32s %16p\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name);
  156. GGML_METAL_ADD_KERNEL(add);
  157. GGML_METAL_ADD_KERNEL(mul);
  158. GGML_METAL_ADD_KERNEL(mul_row);
  159. GGML_METAL_ADD_KERNEL(scale);
  160. GGML_METAL_ADD_KERNEL(silu);
  161. GGML_METAL_ADD_KERNEL(relu);
  162. GGML_METAL_ADD_KERNEL(gelu);
  163. GGML_METAL_ADD_KERNEL(soft_max);
  164. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  165. GGML_METAL_ADD_KERNEL(get_rows_f16);
  166. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  167. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  168. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  169. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  170. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  171. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  172. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  173. GGML_METAL_ADD_KERNEL(rms_norm);
  174. GGML_METAL_ADD_KERNEL(norm);
  175. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32);
  176. GGML_METAL_ADD_KERNEL(mul_mat_q4_0_f32);
  177. GGML_METAL_ADD_KERNEL(mul_mat_q4_1_f32);
  178. GGML_METAL_ADD_KERNEL(mul_mat_q2_K_f32);
  179. GGML_METAL_ADD_KERNEL(mul_mat_q3_K_f32);
  180. GGML_METAL_ADD_KERNEL(mul_mat_q4_K_f32);
  181. GGML_METAL_ADD_KERNEL(mul_mat_q5_K_f32);
  182. GGML_METAL_ADD_KERNEL(mul_mat_q6_K_f32);
  183. GGML_METAL_ADD_KERNEL(rope);
  184. GGML_METAL_ADD_KERNEL(alibi_f32);
  185. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  186. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  187. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  188. #undef GGML_METAL_ADD_KERNEL
  189. }
  190. fprintf(stderr, "%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  191. fprintf(stderr, "%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  192. if (ctx->device.maxTransferRate != 0) {
  193. fprintf(stderr, "%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  194. } else {
  195. fprintf(stderr, "%s: maxTransferRate = built-in GPU\n", __func__);
  196. }
  197. return ctx;
  198. }
  199. void ggml_metal_free(struct ggml_metal_context * ctx) {
  200. fprintf(stderr, "%s: deallocating\n", __func__);
  201. for (int i = 0; i < ctx->n_buffers; ++i) {
  202. [ctx->buffers[i].metal release];
  203. }
  204. free(ctx);
  205. }
  206. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  207. ctx->n_cb = n_cb;
  208. }
  209. // finds the Metal buffer that contains the tensor data on the GPU device
  210. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  211. // Metal buffer based on the host memory pointer
  212. //
  213. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  214. //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);
  215. const int64_t tsize = ggml_nbytes(t);
  216. // find the view that contains the tensor fully
  217. for (int i = 0; i < ctx->n_buffers; ++i) {
  218. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  219. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  220. *offs = (size_t) ioffs;
  221. //fprintf(stderr, "%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  222. return ctx->buffers[i].metal;
  223. }
  224. }
  225. fprintf(stderr, "%s: error: buffer is nil\n", __func__);
  226. return nil;
  227. }
  228. bool ggml_metal_add_buffer(
  229. struct ggml_metal_context * ctx,
  230. const char * name,
  231. void * data,
  232. size_t size,
  233. size_t max_size) {
  234. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  235. fprintf(stderr, "%s: too many buffers\n", __func__);
  236. return false;
  237. }
  238. if (data) {
  239. // verify that the buffer does not overlap with any of the existing buffers
  240. for (int i = 0; i < ctx->n_buffers; ++i) {
  241. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  242. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  243. fprintf(stderr, "%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  244. return false;
  245. }
  246. }
  247. const size_t size_page = getpagesize();
  248. size_t size_aligned = size;
  249. if ((size_aligned % size_page) != 0) {
  250. size_aligned += (size_page - (size_aligned % size_page));
  251. }
  252. // the buffer fits into the max buffer size allowed by the device
  253. if (size_aligned <= ctx->device.maxBufferLength) {
  254. ctx->buffers[ctx->n_buffers].name = name;
  255. ctx->buffers[ctx->n_buffers].data = data;
  256. ctx->buffers[ctx->n_buffers].size = size;
  257. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  258. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  259. fprintf(stderr, "%s: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  260. return false;
  261. }
  262. fprintf(stderr, "%s: allocated '%-16s' buffer, size = %8.2f MB", __func__, name, size_aligned / 1024.0 / 1024.0);
  263. ++ctx->n_buffers;
  264. } else {
  265. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  266. // one of the views
  267. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  268. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  269. const size_t size_view = ctx->device.maxBufferLength;
  270. for (size_t i = 0; i < size; i += size_step) {
  271. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  272. ctx->buffers[ctx->n_buffers].name = name;
  273. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  274. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  275. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  276. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  277. fprintf(stderr, "%s: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  278. return false;
  279. }
  280. fprintf(stderr, "%s: allocated '%-16s' buffer, size = %8.2f MB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  281. if (i + size_step < size) {
  282. fprintf(stderr, "\n");
  283. }
  284. ++ctx->n_buffers;
  285. }
  286. }
  287. fprintf(stderr, ", (%8.2f / %8.2f)",
  288. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  289. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  290. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  291. fprintf(stderr, ", warning: current allocated size is greater than the recommended max working set size\n");
  292. } else {
  293. fprintf(stderr, "\n");
  294. }
  295. }
  296. return true;
  297. }
  298. void ggml_metal_set_tensor(
  299. struct ggml_metal_context * ctx,
  300. struct ggml_tensor * t) {
  301. metal_printf("%s: set input for tensor '%s'\n", __func__, t->name);
  302. size_t offs;
  303. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  304. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  305. }
  306. void ggml_metal_get_tensor(
  307. struct ggml_metal_context * ctx,
  308. struct ggml_tensor * t) {
  309. metal_printf("%s: extract results for tensor '%s'\n", __func__, t->name);
  310. size_t offs;
  311. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  312. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  313. }
  314. void ggml_metal_graph_compute(
  315. struct ggml_metal_context * ctx,
  316. struct ggml_cgraph * gf) {
  317. metal_printf("%s: evaluating graph\n", __func__);
  318. // create multiple command buffers and enqueue them
  319. // then, we encode the graph into the command buffers in parallel
  320. const int n_cb = ctx->n_cb;
  321. NSMutableArray * command_buffers = [NSMutableArray arrayWithCapacity:n_cb];
  322. for (int i = 0; i < n_cb; ++i) {
  323. command_buffers[i] = [ctx->queue commandBuffer];
  324. // enqueue the command buffers in order to specify their execution order
  325. [command_buffers[i] enqueue];
  326. }
  327. // TODO: is this the best way to start threads?
  328. dispatch_queue_t queue = dispatch_queue_create("llama.cpp", DISPATCH_QUEUE_CONCURRENT);
  329. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  330. const int n_nodes_per_cb = (gf->n_nodes + n_cb - 1) / n_cb;
  331. dispatch_async(queue, ^{
  332. size_t offs_src0 = 0;
  333. size_t offs_src1 = 0;
  334. size_t offs_dst = 0;
  335. id<MTLCommandBuffer> command_buffer = command_buffers[cb_idx];
  336. id<MTLComputeCommandEncoder> encoder = nil;
  337. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  338. const int node_end = (cb_idx == n_cb - 1) ? gf->n_nodes : (cb_idx + 1) * n_nodes_per_cb;
  339. for (int i = node_start; i < node_end; ++i) {
  340. metal_printf("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  341. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  342. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  343. struct ggml_tensor * dst = gf->nodes[i];
  344. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  345. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  346. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  347. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  348. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  349. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  350. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  351. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  352. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  353. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  354. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  355. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  356. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  357. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  358. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  359. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  360. const int64_t ne0 = dst ? dst->ne[0] : 0;
  361. const int64_t ne1 = dst ? dst->ne[1] : 0;
  362. const int64_t ne2 = dst ? dst->ne[2] : 0;
  363. const int64_t ne3 = dst ? dst->ne[3] : 0;
  364. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  365. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  366. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  367. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  368. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  369. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  370. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  371. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  372. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  373. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  374. //metal_printf("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  375. //if (src0) {
  376. // metal_printf("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  377. // ggml_is_contiguous(src0), src0->name);
  378. //}
  379. //if (src1) {
  380. // metal_printf("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  381. // ggml_is_contiguous(src1), src1->name);
  382. //}
  383. //if (dst) {
  384. // metal_printf("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  385. // dst->name);
  386. //}
  387. switch (dst->op) {
  388. case GGML_OP_NONE:
  389. case GGML_OP_RESHAPE:
  390. case GGML_OP_VIEW:
  391. case GGML_OP_TRANSPOSE:
  392. case GGML_OP_PERMUTE:
  393. {
  394. // noop
  395. } break;
  396. case GGML_OP_ADD:
  397. {
  398. if (encoder == nil) {
  399. encoder = [command_buffer computeCommandEncoder];
  400. }
  401. [encoder setComputePipelineState:ctx->pipeline_add];
  402. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  403. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  404. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  405. const int64_t n = ggml_nelements(dst);
  406. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  407. } break;
  408. case GGML_OP_MUL:
  409. {
  410. if (encoder == nil) {
  411. encoder = [command_buffer computeCommandEncoder];
  412. }
  413. if (ggml_nelements(src1) == ne10) {
  414. // src1 is a row
  415. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  416. } else {
  417. [encoder setComputePipelineState:ctx->pipeline_mul];
  418. }
  419. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  420. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  421. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  422. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  423. const int64_t n = ggml_nelements(dst);
  424. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  425. } break;
  426. case GGML_OP_SCALE:
  427. {
  428. if (encoder == nil) {
  429. encoder = [command_buffer computeCommandEncoder];
  430. }
  431. const float scale = *(const float *) src1->data;
  432. [encoder setComputePipelineState:ctx->pipeline_scale];
  433. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  434. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  435. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  436. const int64_t n = ggml_nelements(dst);
  437. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  438. } break;
  439. case GGML_OP_SILU:
  440. {
  441. if (encoder == nil) {
  442. encoder = [command_buffer computeCommandEncoder];
  443. }
  444. [encoder setComputePipelineState:ctx->pipeline_silu];
  445. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  446. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  447. const int64_t n = ggml_nelements(dst);
  448. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  449. } break;
  450. case GGML_OP_RELU:
  451. {
  452. if (encoder == nil) {
  453. encoder = [command_buffer computeCommandEncoder];
  454. }
  455. [encoder setComputePipelineState:ctx->pipeline_relu];
  456. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  457. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  458. const int64_t n = ggml_nelements(dst);
  459. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  460. } break;
  461. case GGML_OP_GELU:
  462. {
  463. if (encoder == nil) {
  464. encoder = [command_buffer computeCommandEncoder];
  465. }
  466. [encoder setComputePipelineState:ctx->pipeline_gelu];
  467. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  468. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  469. const int64_t n = ggml_nelements(dst);
  470. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  471. } break;
  472. case GGML_OP_SOFT_MAX:
  473. {
  474. if (encoder == nil) {
  475. encoder = [command_buffer computeCommandEncoder];
  476. }
  477. const int nth = 32;
  478. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  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(ne00) atIndex:2];
  482. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  483. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  484. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  485. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  486. } break;
  487. case GGML_OP_DIAG_MASK_INF:
  488. {
  489. if (encoder == nil) {
  490. encoder = [command_buffer computeCommandEncoder];
  491. }
  492. const int n_past = ((int32_t *)(src1->data))[0];
  493. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  494. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  495. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  496. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  497. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  498. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  499. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  500. } break;
  501. case GGML_OP_MUL_MAT:
  502. {
  503. // TODO: needs to be updated after PR: https://github.com/ggerganov/ggml/pull/224
  504. GGML_ASSERT(ne00 == ne10);
  505. GGML_ASSERT(ne02 == ne12);
  506. if (ggml_is_contiguous(src0) &&
  507. ggml_is_contiguous(src1) &&
  508. (src0t == GGML_TYPE_F32 || src0t == GGML_TYPE_F16) && ne11 > 1) {
  509. if (encoder != nil) {
  510. [encoder endEncoding];
  511. encoder = nil;
  512. }
  513. MPSDataType src0dt = src0t == GGML_TYPE_F32 ? MPSDataTypeFloat32 : MPSDataTypeFloat16;
  514. MPSDataType src1dt = src1t == GGML_TYPE_F32 ? MPSDataTypeFloat32 : MPSDataTypeFloat16;
  515. // for F32 x F32 we use MPS
  516. MPSMatrixDescriptor * desc0 = [MPSMatrixDescriptor
  517. matrixDescriptorWithRows:ne01 columns:ne00 rowBytes:src0->nb[1] dataType:src0dt];
  518. MPSMatrixDescriptor * desc1 = [MPSMatrixDescriptor
  519. matrixDescriptorWithRows:ne11 columns:ne10 rowBytes:src1->nb[1] dataType:src1dt];
  520. MPSMatrixDescriptor * desc = [MPSMatrixDescriptor
  521. matrixDescriptorWithRows:ne1 columns:ne0 rowBytes:dst->nb[1] dataType:MPSDataTypeFloat32];
  522. MPSMatrixMultiplication * mul = [[MPSMatrixMultiplication alloc]
  523. initWithDevice:ctx->device transposeLeft:false transposeRight:true
  524. resultRows:ne11 resultColumns:ne01 interiorColumns:ne00 alpha:1.0 beta:0.0];
  525. // we need to do ne02 multiplications
  526. // TODO: is there a way to do this in parallel - currently very slow ..
  527. // TODO: might be possible to offload part of the computation to ANE using Accelerate's CBLAS
  528. for (int64_t i02 = 0; i02 < ne02; ++i02) {
  529. size_t offs_src0_cur = offs_src0 + i02*nb02;
  530. size_t offs_src1_cur = offs_src1 + i02*nb12;
  531. size_t offs_dst_cur = offs_dst + i02*nb2;
  532. MPSMatrix * mat_src0 = [[MPSMatrix alloc] initWithBuffer:id_src0 offset:offs_src0_cur descriptor:desc0];
  533. MPSMatrix * mat_src1 = [[MPSMatrix alloc] initWithBuffer:id_src1 offset:offs_src1_cur descriptor:desc1];
  534. MPSMatrix * mat_dst = [[MPSMatrix alloc] initWithBuffer:id_dst offset:offs_dst_cur descriptor:desc ];
  535. [mul encodeToCommandBuffer:command_buffer leftMatrix:mat_src1 rightMatrix:mat_src0 resultMatrix:mat_dst];
  536. }
  537. } else {
  538. if (encoder == nil) {
  539. encoder = [command_buffer computeCommandEncoder];
  540. }
  541. int nth0 = 32;
  542. int nth1 = 1;
  543. // use custom matrix x vector kernel
  544. switch (src0t) {
  545. case GGML_TYPE_F16:
  546. {
  547. GGML_ASSERT(ne02 == ne12);
  548. nth0 = 64;
  549. nth1 = 1;
  550. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32];
  551. } break;
  552. case GGML_TYPE_Q4_0:
  553. {
  554. GGML_ASSERT(ne02 == 1);
  555. GGML_ASSERT(ne12 == 1);
  556. nth0 = 8;
  557. nth1 = 8;
  558. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_0_f32];
  559. } break;
  560. case GGML_TYPE_Q4_1:
  561. {
  562. GGML_ASSERT(ne02 == 1);
  563. GGML_ASSERT(ne12 == 1);
  564. nth0 = 8;
  565. nth1 = 8;
  566. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_1_f32];
  567. } break;
  568. case GGML_TYPE_Q2_K:
  569. {
  570. GGML_ASSERT(ne02 == 1);
  571. GGML_ASSERT(ne12 == 1);
  572. nth0 = 4;
  573. nth1 = 16;
  574. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q2_K_f32];
  575. } break;
  576. case GGML_TYPE_Q3_K:
  577. {
  578. GGML_ASSERT(ne02 == 1);
  579. GGML_ASSERT(ne12 == 1);
  580. nth0 = 4;
  581. nth1 = 16;
  582. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q3_K_f32];
  583. } break;
  584. case GGML_TYPE_Q4_K:
  585. {
  586. GGML_ASSERT(ne02 == 1);
  587. GGML_ASSERT(ne12 == 1);
  588. nth0 = 2;
  589. nth1 = 32;
  590. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_K_f32];
  591. } break;
  592. case GGML_TYPE_Q5_K:
  593. {
  594. GGML_ASSERT(ne02 == 1);
  595. GGML_ASSERT(ne12 == 1);
  596. nth0 = 2;
  597. nth1 = 32;
  598. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q5_K_f32];
  599. } break;
  600. case GGML_TYPE_Q6_K:
  601. {
  602. GGML_ASSERT(ne02 == 1);
  603. GGML_ASSERT(ne12 == 1);
  604. nth0 = 2;
  605. nth1 = 32;
  606. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q6_K_f32];
  607. } break;
  608. default:
  609. {
  610. fprintf(stderr, "Asserting on type %d\n",(int)src0t);
  611. GGML_ASSERT(false && "not implemented");
  612. }
  613. };
  614. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  615. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  616. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  617. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  618. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  619. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:5];
  620. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:6];
  621. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:7];
  622. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:8];
  623. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:9];
  624. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:10];
  625. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:11];
  626. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:12];
  627. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:13];
  628. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:14];
  629. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 ||
  630. src0t == GGML_TYPE_Q4_K) {
  631. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7) / 8, ne11, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  632. }
  633. else if (src0t == GGML_TYPE_Q5_K) {
  634. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3) / 4, ne11, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  635. }
  636. else if (src0t == GGML_TYPE_Q6_K) {
  637. [encoder dispatchThreadgroups:MTLSizeMake((ne01+1)/2, ne11, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  638. }
  639. else if (src0t == GGML_TYPE_Q2_K ||
  640. src0t == GGML_TYPE_Q3_K) {
  641. [encoder setThreadgroupMemoryLength:nth0*nth1*sizeof(float) atIndex:0];
  642. [encoder dispatchThreadgroups:MTLSizeMake(ne01, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  643. } else {
  644. [encoder setThreadgroupMemoryLength:nth0*sizeof(float) atIndex:0];
  645. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  646. }
  647. }
  648. } break;
  649. case GGML_OP_GET_ROWS:
  650. {
  651. if (encoder == nil) {
  652. encoder = [command_buffer computeCommandEncoder];
  653. }
  654. switch (src0->type) {
  655. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  656. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  657. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  658. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  659. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  660. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  661. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  662. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  663. default: GGML_ASSERT(false && "not implemented");
  664. }
  665. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  666. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  667. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  668. [encoder setBytes:&(src0->ne[0]) length:sizeof( int64_t) atIndex:3];
  669. [encoder setBytes:&(src0->nb[1]) length:sizeof(uint64_t) atIndex:4];
  670. [encoder setBytes:&(dst->nb[1]) length:sizeof(uint64_t) atIndex:5];
  671. const int64_t n = ggml_nelements(src1);
  672. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  673. } break;
  674. case GGML_OP_RMS_NORM:
  675. {
  676. if (encoder == nil) {
  677. encoder = [command_buffer computeCommandEncoder];
  678. }
  679. const float eps = 1e-6f;
  680. const int nth = 512;
  681. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  682. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  683. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  684. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  685. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  686. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  687. [encoder setThreadgroupMemoryLength:nth/32*sizeof(float) atIndex:0];
  688. const int64_t nrows = ggml_nrows(src0);
  689. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  690. } break;
  691. case GGML_OP_NORM:
  692. {
  693. if (encoder == nil) {
  694. encoder = [command_buffer computeCommandEncoder];
  695. }
  696. const float eps = 1e-5f;
  697. const int nth = 256;
  698. [encoder setComputePipelineState:ctx->pipeline_norm];
  699. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  700. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  701. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  702. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  703. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  704. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  705. const int64_t nrows = ggml_nrows(src0);
  706. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  707. } break;
  708. case GGML_OP_ALIBI:
  709. {
  710. if (encoder == nil) {
  711. encoder = [command_buffer computeCommandEncoder];
  712. }
  713. GGML_ASSERT((src0t == GGML_TYPE_F32));
  714. const int n_past = ((int32_t *) src1->data)[0]; UNUSED(n_past);
  715. const int n_head = ((int32_t *) src1->data)[1];
  716. const float max_bias = ((float *) src1->data)[2];
  717. if (__builtin_popcount(n_head) != 1) {
  718. GGML_ASSERT(false && "only power-of-two n_head implemented");
  719. }
  720. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  721. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  722. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  723. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  724. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  725. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  726. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  727. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  728. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  729. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  730. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  731. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  732. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  733. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  734. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  735. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  736. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  737. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  738. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  739. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  740. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  741. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  742. const int nth = 32;
  743. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  744. } break;
  745. case GGML_OP_ROPE:
  746. {
  747. if (encoder == nil) {
  748. encoder = [command_buffer computeCommandEncoder];
  749. }
  750. const int n_dims = ((int32_t *) src1->data)[1];
  751. const int mode = ((int32_t *) src1->data)[2];
  752. const int n_past = ((int32_t *)(src1->data))[0];
  753. float freq_base;
  754. float freq_scale;
  755. memcpy(&freq_base, (int32_t *) src1->data + 4, sizeof(float));
  756. memcpy(&freq_scale, (int32_t *) src1->data + 5, sizeof(float));
  757. [encoder setComputePipelineState:ctx->pipeline_rope];
  758. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  759. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  760. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  761. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  762. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  763. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  764. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  765. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  766. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  767. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  768. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  769. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  770. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  771. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  772. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  773. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  774. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  775. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  776. [encoder setBytes:&n_past length:sizeof( int) atIndex:18];
  777. [encoder setBytes:&n_dims length:sizeof( int) atIndex:19];
  778. [encoder setBytes:&mode length:sizeof( int) atIndex:20];
  779. [encoder setBytes:&freq_base length:sizeof(float) atIndex:21];
  780. [encoder setBytes:&freq_scale length:sizeof(float) atIndex:22];
  781. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  782. } break;
  783. case GGML_OP_CPY:
  784. {
  785. if (encoder == nil) {
  786. encoder = [command_buffer computeCommandEncoder];
  787. }
  788. const int nth = 32;
  789. switch (src0t) {
  790. case GGML_TYPE_F32:
  791. {
  792. switch (dstt) {
  793. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  794. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  795. default: GGML_ASSERT(false && "not implemented");
  796. };
  797. } break;
  798. case GGML_TYPE_F16:
  799. {
  800. switch (dstt) {
  801. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  802. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  803. default: GGML_ASSERT(false && "not implemented");
  804. };
  805. } break;
  806. default: GGML_ASSERT(false && "not implemented");
  807. }
  808. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  809. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  810. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  811. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  812. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  813. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  814. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  815. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  816. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  817. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  818. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  819. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  820. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  821. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  822. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  823. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  824. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  825. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  826. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  827. } break;
  828. default:
  829. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  830. GGML_ASSERT(false);
  831. }
  832. }
  833. if (encoder != nil) {
  834. [encoder endEncoding];
  835. encoder = nil;
  836. }
  837. [command_buffer commit];
  838. });
  839. }
  840. // wait for all threads to finish
  841. dispatch_barrier_sync(queue, ^{});
  842. [command_buffers[n_cb - 1] waitUntilCompleted];
  843. // check status of command buffers
  844. // needed to detect if the device ran out-of-memory for example (#1881)
  845. for (int i = 0; i < n_cb; i++) {
  846. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [command_buffers[i] status];
  847. if (status != MTLCommandBufferStatusCompleted) {
  848. fprintf(stderr, "%s: command buffer %d failed with status %lu\n", __func__, i, status);
  849. GGML_ASSERT(false);
  850. }
  851. }
  852. }