ggml-metal.m 58 KB

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