ggml-metal.m 59 KB

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