ggml-metal.m 58 KB

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