ggml-metal.m 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. // +build darwin
  2. /**
  3. * llama.cpp - git 5bf2a2771886ee86137e01dbc7492f78fb392066
  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 = 4;
  589. nth1 = 16;
  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 = 4;
  597. nth1 = 16;
  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 = 4;
  605. nth1 = 16;
  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. [encoder setThreadgroupMemoryLength:nth0*nth1*sizeof(float) atIndex:0];
  631. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne11, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  632. }
  633. else if (src0t == GGML_TYPE_Q2_K ||
  634. src0t == GGML_TYPE_Q3_K ||
  635. src0t == GGML_TYPE_Q4_K ||
  636. src0t == GGML_TYPE_Q5_K ||
  637. src0t == GGML_TYPE_Q6_K) {
  638. [encoder setThreadgroupMemoryLength:nth0*nth1*sizeof(float) atIndex:0];
  639. [encoder dispatchThreadgroups:MTLSizeMake(ne01, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  640. } else {
  641. [encoder setThreadgroupMemoryLength:nth0*sizeof(float) atIndex:0];
  642. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  643. }
  644. }
  645. } break;
  646. case GGML_OP_GET_ROWS:
  647. {
  648. if (encoder == nil) {
  649. encoder = [command_buffer computeCommandEncoder];
  650. }
  651. switch (src0->type) {
  652. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  653. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  654. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  655. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  656. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  657. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  658. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  659. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  660. default: GGML_ASSERT(false && "not implemented");
  661. }
  662. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  663. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  664. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  665. [encoder setBytes:&(src0->ne[0]) length:sizeof( int64_t) atIndex:3];
  666. [encoder setBytes:&(src0->nb[1]) length:sizeof(uint64_t) atIndex:4];
  667. [encoder setBytes:&(dst->nb[1]) length:sizeof(uint64_t) atIndex:5];
  668. const int64_t n = ggml_nelements(src1);
  669. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  670. } break;
  671. case GGML_OP_RMS_NORM:
  672. {
  673. if (encoder == nil) {
  674. encoder = [command_buffer computeCommandEncoder];
  675. }
  676. const float eps = 1e-6f;
  677. const int nth = 256;
  678. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  679. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  680. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  681. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  682. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  683. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  684. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  685. const int64_t nrows = ggml_nrows(src0);
  686. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  687. } break;
  688. case GGML_OP_NORM:
  689. {
  690. if (encoder == nil) {
  691. encoder = [command_buffer computeCommandEncoder];
  692. }
  693. const float eps = 1e-5f;
  694. const int nth = 256;
  695. [encoder setComputePipelineState:ctx->pipeline_norm];
  696. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  697. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  698. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  699. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  700. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  701. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  702. const int64_t nrows = ggml_nrows(src0);
  703. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  704. } break;
  705. case GGML_OP_ALIBI:
  706. {
  707. if (encoder == nil) {
  708. encoder = [command_buffer computeCommandEncoder];
  709. }
  710. GGML_ASSERT((src0t == GGML_TYPE_F32));
  711. const int n_past = ((int32_t *) src1->data)[0]; UNUSED(n_past);
  712. const int n_head = ((int32_t *) src1->data)[1];
  713. const float max_bias = ((float *) src1->data)[2];
  714. if (__builtin_popcount(n_head) != 1) {
  715. GGML_ASSERT(false && "only power-of-two n_head implemented");
  716. }
  717. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  718. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  719. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  720. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  721. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  722. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  723. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  724. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  725. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  726. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  727. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  728. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  729. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  730. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  731. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  732. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  733. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  734. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  735. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  736. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  737. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  738. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  739. const int nth = 32;
  740. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  741. } break;
  742. case GGML_OP_ROPE:
  743. {
  744. if (encoder == nil) {
  745. encoder = [command_buffer computeCommandEncoder];
  746. }
  747. const int n_dims = ((int32_t *) src1->data)[1];
  748. const int mode = ((int32_t *) src1->data)[2];
  749. const int n_past = ((int32_t *)(src1->data))[0];
  750. [encoder setComputePipelineState:ctx->pipeline_rope];
  751. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  752. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  753. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  754. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  755. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  756. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  757. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  758. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  759. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  760. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  761. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  762. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  763. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  764. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  765. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  766. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  767. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  768. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  769. [encoder setBytes:&n_past length:sizeof( int) atIndex:18];
  770. [encoder setBytes:&n_dims length:sizeof( int) atIndex:19];
  771. [encoder setBytes:&mode length:sizeof( int) atIndex:20];
  772. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  773. } break;
  774. case GGML_OP_CPY:
  775. {
  776. if (encoder == nil) {
  777. encoder = [command_buffer computeCommandEncoder];
  778. }
  779. const int nth = 32;
  780. switch (src0t) {
  781. case GGML_TYPE_F32:
  782. {
  783. switch (dstt) {
  784. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  785. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  786. default: GGML_ASSERT(false && "not implemented");
  787. };
  788. } break;
  789. case GGML_TYPE_F16:
  790. {
  791. switch (dstt) {
  792. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  793. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  794. default: GGML_ASSERT(false && "not implemented");
  795. };
  796. } break;
  797. default: GGML_ASSERT(false && "not implemented");
  798. }
  799. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  800. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  801. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  802. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  803. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  804. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  805. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  806. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  807. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  808. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  809. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  810. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  811. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  812. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  813. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  814. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  815. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  816. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  817. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  818. } break;
  819. default:
  820. fprintf(stderr, "%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  821. GGML_ASSERT(false);
  822. }
  823. }
  824. if (encoder != nil) {
  825. [encoder endEncoding];
  826. encoder = nil;
  827. }
  828. [command_buffer commit];
  829. });
  830. }
  831. // wait for all threads to finish
  832. dispatch_barrier_sync(queue, ^{});
  833. [command_buffers[n_cb - 1] waitUntilCompleted];
  834. // check status of command buffers
  835. // needed to detect if the device ran out-of-memory for example (#1881)
  836. for (int i = 0; i < n_cb; i++) {
  837. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [command_buffers[i] status];
  838. if (status != MTLCommandBufferStatusCompleted) {
  839. fprintf(stderr, "%s: command buffer %d failed with status %lu\n", __func__, i, status);
  840. GGML_ASSERT(false);
  841. }
  842. }
  843. }