ggml-metal.m 50 KB

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