ggml-metal.m 57 KB

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