ggml-metal.m 55 KB

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