ggml-metal.m 60 KB

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