ggml-metal.m 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  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 GGML_METAL_LOG_INFO(...)
  11. #define GGML_METAL_LOG_WARN(...)
  12. #define GGML_METAL_LOG_ERROR(...)
  13. #else
  14. #define GGML_METAL_LOG_INFO(...) ggml_metal_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  15. #define GGML_METAL_LOG_WARN(...) ggml_metal_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  16. #define GGML_METAL_LOG_ERROR(...) ggml_metal_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  17. #endif
  18. #define UNUSED(x) (void)(x)
  19. #define GGML_MAX_CONCUR (2*GGML_MAX_NODES)
  20. struct ggml_metal_buffer {
  21. const char * name;
  22. void * data;
  23. size_t size;
  24. id<MTLBuffer> metal;
  25. };
  26. struct ggml_metal_context {
  27. int n_cb;
  28. id<MTLDevice> device;
  29. id<MTLCommandQueue> queue;
  30. id<MTLLibrary> library;
  31. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  32. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  33. dispatch_queue_t d_queue;
  34. int n_buffers;
  35. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  36. int concur_list[GGML_MAX_CONCUR];
  37. int concur_list_len;
  38. // custom kernels
  39. #define GGML_METAL_DECL_KERNEL(name) \
  40. id<MTLFunction> function_##name; \
  41. id<MTLComputePipelineState> pipeline_##name
  42. GGML_METAL_DECL_KERNEL(add);
  43. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  44. GGML_METAL_DECL_KERNEL(mul);
  45. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  46. GGML_METAL_DECL_KERNEL(scale);
  47. GGML_METAL_DECL_KERNEL(scale_4);
  48. GGML_METAL_DECL_KERNEL(silu);
  49. GGML_METAL_DECL_KERNEL(relu);
  50. GGML_METAL_DECL_KERNEL(gelu);
  51. GGML_METAL_DECL_KERNEL(soft_max);
  52. GGML_METAL_DECL_KERNEL(soft_max_4);
  53. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  54. GGML_METAL_DECL_KERNEL(diag_mask_inf_8);
  55. GGML_METAL_DECL_KERNEL(get_rows_f32);
  56. GGML_METAL_DECL_KERNEL(get_rows_f16);
  57. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  58. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  59. GGML_METAL_DECL_KERNEL(get_rows_q5_0);
  60. GGML_METAL_DECL_KERNEL(get_rows_q5_1);
  61. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  62. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  63. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  64. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  65. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  66. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  67. GGML_METAL_DECL_KERNEL(rms_norm);
  68. GGML_METAL_DECL_KERNEL(norm);
  69. GGML_METAL_DECL_KERNEL(mul_mv_f32_f32);
  70. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32);
  71. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_1row);
  72. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_l4);
  73. GGML_METAL_DECL_KERNEL(mul_mv_q4_0_f32);
  74. GGML_METAL_DECL_KERNEL(mul_mv_q4_1_f32);
  75. GGML_METAL_DECL_KERNEL(mul_mv_q5_0_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mv_q5_1_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mv_q8_0_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mv_q2_K_f32);
  79. GGML_METAL_DECL_KERNEL(mul_mv_q3_K_f32);
  80. GGML_METAL_DECL_KERNEL(mul_mv_q4_K_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mv_q5_K_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mv_q6_K_f32);
  83. GGML_METAL_DECL_KERNEL(mul_mm_f32_f32);
  84. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  85. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  86. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  87. GGML_METAL_DECL_KERNEL(mul_mm_q5_0_f32);
  88. GGML_METAL_DECL_KERNEL(mul_mm_q5_1_f32);
  89. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  90. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  91. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  92. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  93. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  94. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  95. GGML_METAL_DECL_KERNEL(rope_f32);
  96. GGML_METAL_DECL_KERNEL(rope_f16);
  97. GGML_METAL_DECL_KERNEL(alibi_f32);
  98. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  99. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  100. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  101. GGML_METAL_DECL_KERNEL(concat);
  102. GGML_METAL_DECL_KERNEL(sqr);
  103. #undef GGML_METAL_DECL_KERNEL
  104. };
  105. // MSL code
  106. // TODO: move the contents here when ready
  107. // for now it is easier to work in a separate file
  108. static NSString * const msl_library_source = @"see metal.metal";
  109. // Here to assist with NSBundle Path Hack
  110. @interface GGMLMetalClass : NSObject
  111. @end
  112. @implementation GGMLMetalClass
  113. @end
  114. ggml_log_callback ggml_metal_log_callback = NULL;
  115. void * ggml_metal_log_user_data = NULL;
  116. void ggml_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  117. ggml_metal_log_callback = log_callback;
  118. ggml_metal_log_user_data = user_data;
  119. }
  120. static void ggml_metal_log(enum ggml_log_level level, const char* format, ...){
  121. if (ggml_metal_log_callback != NULL) {
  122. va_list args;
  123. va_start(args, format);
  124. char buffer[128];
  125. int len = vsnprintf(buffer, 128, format, args);
  126. if (len < 128) {
  127. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  128. } else {
  129. char* buffer2 = malloc(len+1);
  130. vsnprintf(buffer2, len+1, format, args);
  131. buffer2[len] = 0;
  132. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  133. free(buffer2);
  134. }
  135. va_end(args);
  136. }
  137. }
  138. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  139. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  140. id <MTLDevice> device;
  141. NSString * s;
  142. #if TARGET_OS_OSX
  143. // Show all the Metal device instances in the system
  144. NSArray * devices = MTLCopyAllDevices();
  145. for (device in devices) {
  146. s = [device name];
  147. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [s UTF8String]);
  148. }
  149. #endif
  150. // Pick and show default Metal device
  151. device = MTLCreateSystemDefaultDevice();
  152. s = [device name];
  153. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [s UTF8String]);
  154. // Configure context
  155. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  156. ctx->device = device;
  157. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  158. ctx->queue = [ctx->device newCommandQueue];
  159. ctx->n_buffers = 0;
  160. ctx->concur_list_len = 0;
  161. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  162. // load library
  163. {
  164. NSBundle * bundle = nil;
  165. #ifdef SWIFT_PACKAGE
  166. bundle = SWIFTPM_MODULE_BUNDLE;
  167. #else
  168. bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  169. #endif
  170. NSError * error = nil;
  171. NSString * libPath = [bundle pathForResource:@"default" ofType:@"metallib"];
  172. if (libPath != nil) {
  173. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  174. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [libPath UTF8String]);
  175. ctx->library = [ctx->device newLibraryWithURL:libURL error:&error];
  176. } else {
  177. GGML_METAL_LOG_INFO("%s: default.metallib not found, loading from source\n", __func__);
  178. NSString * sourcePath = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  179. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [sourcePath UTF8String]);
  180. NSString * src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:&error];
  181. if (error) {
  182. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  183. return NULL;
  184. }
  185. MTLCompileOptions* options = nil;
  186. #ifdef GGML_QKK_64
  187. options = [MTLCompileOptions new];
  188. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  189. #endif
  190. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  191. }
  192. if (error) {
  193. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  194. return NULL;
  195. }
  196. }
  197. // load kernels
  198. {
  199. NSError * error = nil;
  200. #define GGML_METAL_ADD_KERNEL(name) \
  201. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  202. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  203. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  204. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  205. (int) ctx->pipeline_##name.threadExecutionWidth); \
  206. if (error) { \
  207. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  208. return NULL; \
  209. }
  210. GGML_METAL_ADD_KERNEL(add);
  211. GGML_METAL_ADD_KERNEL(add_row);
  212. GGML_METAL_ADD_KERNEL(mul);
  213. GGML_METAL_ADD_KERNEL(mul_row);
  214. GGML_METAL_ADD_KERNEL(scale);
  215. GGML_METAL_ADD_KERNEL(scale_4);
  216. GGML_METAL_ADD_KERNEL(silu);
  217. GGML_METAL_ADD_KERNEL(relu);
  218. GGML_METAL_ADD_KERNEL(gelu);
  219. GGML_METAL_ADD_KERNEL(soft_max);
  220. GGML_METAL_ADD_KERNEL(soft_max_4);
  221. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  222. GGML_METAL_ADD_KERNEL(diag_mask_inf_8);
  223. GGML_METAL_ADD_KERNEL(get_rows_f32);
  224. GGML_METAL_ADD_KERNEL(get_rows_f16);
  225. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  226. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  227. GGML_METAL_ADD_KERNEL(get_rows_q5_0);
  228. GGML_METAL_ADD_KERNEL(get_rows_q5_1);
  229. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  230. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  231. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  232. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  233. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  234. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  235. GGML_METAL_ADD_KERNEL(rms_norm);
  236. GGML_METAL_ADD_KERNEL(norm);
  237. GGML_METAL_ADD_KERNEL(mul_mv_f32_f32);
  238. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32);
  239. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_1row);
  240. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_l4);
  241. GGML_METAL_ADD_KERNEL(mul_mv_q4_0_f32);
  242. GGML_METAL_ADD_KERNEL(mul_mv_q4_1_f32);
  243. GGML_METAL_ADD_KERNEL(mul_mv_q5_0_f32);
  244. GGML_METAL_ADD_KERNEL(mul_mv_q5_1_f32);
  245. GGML_METAL_ADD_KERNEL(mul_mv_q8_0_f32);
  246. GGML_METAL_ADD_KERNEL(mul_mv_q2_K_f32);
  247. GGML_METAL_ADD_KERNEL(mul_mv_q3_K_f32);
  248. GGML_METAL_ADD_KERNEL(mul_mv_q4_K_f32);
  249. GGML_METAL_ADD_KERNEL(mul_mv_q5_K_f32);
  250. GGML_METAL_ADD_KERNEL(mul_mv_q6_K_f32);
  251. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  252. GGML_METAL_ADD_KERNEL(mul_mm_f32_f32);
  253. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  254. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  255. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  256. GGML_METAL_ADD_KERNEL(mul_mm_q5_0_f32);
  257. GGML_METAL_ADD_KERNEL(mul_mm_q5_1_f32);
  258. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  259. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  260. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  261. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  262. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  263. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  264. }
  265. GGML_METAL_ADD_KERNEL(rope_f32);
  266. GGML_METAL_ADD_KERNEL(rope_f16);
  267. GGML_METAL_ADD_KERNEL(alibi_f32);
  268. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  269. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  270. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  271. GGML_METAL_ADD_KERNEL(concat);
  272. GGML_METAL_ADD_KERNEL(sqr);
  273. #undef GGML_METAL_ADD_KERNEL
  274. }
  275. #if TARGET_OS_OSX
  276. // print MTL GPU family:
  277. GGML_METAL_LOG_INFO("%s: GPU name: %s\n", __func__, [[ctx->device name] UTF8String]);
  278. // determine max supported GPU family
  279. // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
  280. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  281. for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) {
  282. if ([ctx->device supportsFamily:i]) {
  283. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, i - MTLGPUFamilyApple1 + 1, i);
  284. break;
  285. }
  286. }
  287. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  288. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  289. if (ctx->device.maxTransferRate != 0) {
  290. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  291. } else {
  292. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  293. }
  294. #endif
  295. return ctx;
  296. }
  297. void ggml_metal_free(struct ggml_metal_context * ctx) {
  298. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  299. #define GGML_METAL_DEL_KERNEL(name) \
  300. [ctx->function_##name release]; \
  301. [ctx->pipeline_##name release];
  302. GGML_METAL_DEL_KERNEL(add);
  303. GGML_METAL_DEL_KERNEL(add_row);
  304. GGML_METAL_DEL_KERNEL(mul);
  305. GGML_METAL_DEL_KERNEL(mul_row);
  306. GGML_METAL_DEL_KERNEL(scale);
  307. GGML_METAL_DEL_KERNEL(scale_4);
  308. GGML_METAL_DEL_KERNEL(silu);
  309. GGML_METAL_DEL_KERNEL(relu);
  310. GGML_METAL_DEL_KERNEL(gelu);
  311. GGML_METAL_DEL_KERNEL(soft_max);
  312. GGML_METAL_DEL_KERNEL(soft_max_4);
  313. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  314. GGML_METAL_DEL_KERNEL(diag_mask_inf_8);
  315. GGML_METAL_DEL_KERNEL(get_rows_f32);
  316. GGML_METAL_DEL_KERNEL(get_rows_f16);
  317. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  318. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  319. GGML_METAL_DEL_KERNEL(get_rows_q5_0);
  320. GGML_METAL_DEL_KERNEL(get_rows_q5_1);
  321. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  322. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  323. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  324. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  325. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  326. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  327. GGML_METAL_DEL_KERNEL(rms_norm);
  328. GGML_METAL_DEL_KERNEL(norm);
  329. GGML_METAL_DEL_KERNEL(mul_mv_f32_f32);
  330. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32);
  331. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_1row);
  332. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_l4);
  333. GGML_METAL_DEL_KERNEL(mul_mv_q4_0_f32);
  334. GGML_METAL_DEL_KERNEL(mul_mv_q4_1_f32);
  335. GGML_METAL_DEL_KERNEL(mul_mv_q5_0_f32);
  336. GGML_METAL_DEL_KERNEL(mul_mv_q5_1_f32);
  337. GGML_METAL_DEL_KERNEL(mul_mv_q8_0_f32);
  338. GGML_METAL_DEL_KERNEL(mul_mv_q2_K_f32);
  339. GGML_METAL_DEL_KERNEL(mul_mv_q3_K_f32);
  340. GGML_METAL_DEL_KERNEL(mul_mv_q4_K_f32);
  341. GGML_METAL_DEL_KERNEL(mul_mv_q5_K_f32);
  342. GGML_METAL_DEL_KERNEL(mul_mv_q6_K_f32);
  343. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  344. GGML_METAL_DEL_KERNEL(mul_mm_f32_f32);
  345. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  346. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  347. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  348. GGML_METAL_DEL_KERNEL(mul_mm_q5_0_f32);
  349. GGML_METAL_DEL_KERNEL(mul_mm_q5_1_f32);
  350. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  351. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  352. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  353. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  354. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  355. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  356. }
  357. GGML_METAL_DEL_KERNEL(rope_f32);
  358. GGML_METAL_DEL_KERNEL(rope_f16);
  359. GGML_METAL_DEL_KERNEL(alibi_f32);
  360. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  361. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  362. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  363. GGML_METAL_DEL_KERNEL(concat);
  364. GGML_METAL_DEL_KERNEL(sqr);
  365. #undef GGML_METAL_DEL_KERNEL
  366. for (int i = 0; i < ctx->n_buffers; ++i) {
  367. [ctx->buffers[i].metal release];
  368. }
  369. [ctx->library release];
  370. [ctx->queue release];
  371. [ctx->device release];
  372. dispatch_release(ctx->d_queue);
  373. free(ctx);
  374. }
  375. void * ggml_metal_host_malloc(size_t n) {
  376. void * data = NULL;
  377. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  378. if (result != 0) {
  379. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  380. return NULL;
  381. }
  382. return data;
  383. }
  384. void ggml_metal_host_free(void * data) {
  385. free(data);
  386. }
  387. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  388. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  389. }
  390. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  391. return ctx->concur_list_len;
  392. }
  393. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  394. return ctx->concur_list;
  395. }
  396. // finds the Metal buffer that contains the tensor data on the GPU device
  397. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  398. // Metal buffer based on the host memory pointer
  399. //
  400. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  401. //GGML_METAL_LOG_INFO("%s: data tensor '%16s', offs_data = %8ld, offs_eval = %8ld, offs_cach = %8ld\n", __func__, t->name, offs_data, offs_eval, offs_cach);
  402. const int64_t tsize = ggml_nbytes(t);
  403. // find the view that contains the tensor fully
  404. for (int i = 0; i < ctx->n_buffers; ++i) {
  405. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  406. //GGML_METAL_LOG_INFO("ioffs = %10ld, tsize = %10ld, sum = %10ld, ctx->buffers[%d].size = %10ld, name = %s\n", ioffs, tsize, ioffs + tsize, i, ctx->buffers[i].size, ctx->buffers[i].name);
  407. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  408. *offs = (size_t) ioffs;
  409. //GGML_METAL_LOG_INFO("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  410. return ctx->buffers[i].metal;
  411. }
  412. }
  413. GGML_METAL_LOG_ERROR("%s: error: buffer is nil\n", __func__);
  414. return nil;
  415. }
  416. bool ggml_metal_add_buffer(
  417. struct ggml_metal_context * ctx,
  418. const char * name,
  419. void * data,
  420. size_t size,
  421. size_t max_size) {
  422. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  423. GGML_METAL_LOG_ERROR("%s: error: too many buffers\n", __func__);
  424. return false;
  425. }
  426. if (data) {
  427. // verify that the buffer does not overlap with any of the existing buffers
  428. for (int i = 0; i < ctx->n_buffers; ++i) {
  429. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  430. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  431. GGML_METAL_LOG_ERROR("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  432. return false;
  433. }
  434. }
  435. const size_t size_page = sysconf(_SC_PAGESIZE);
  436. size_t size_aligned = size;
  437. if ((size_aligned % size_page) != 0) {
  438. size_aligned += (size_page - (size_aligned % size_page));
  439. }
  440. // the buffer fits into the max buffer size allowed by the device
  441. if (size_aligned <= ctx->device.maxBufferLength) {
  442. ctx->buffers[ctx->n_buffers].name = name;
  443. ctx->buffers[ctx->n_buffers].data = data;
  444. ctx->buffers[ctx->n_buffers].size = size;
  445. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  446. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  447. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  448. return false;
  449. }
  450. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB", __func__, name, size_aligned / 1024.0 / 1024.0);
  451. ++ctx->n_buffers;
  452. } else {
  453. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  454. // one of the views
  455. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  456. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  457. const size_t size_view = ctx->device.maxBufferLength;
  458. for (size_t i = 0; i < size; i += size_step) {
  459. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  460. ctx->buffers[ctx->n_buffers].name = name;
  461. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  462. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  463. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  464. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  465. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  466. return false;
  467. }
  468. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  469. if (i + size_step < size) {
  470. GGML_METAL_LOG_INFO("\n");
  471. }
  472. ++ctx->n_buffers;
  473. }
  474. }
  475. #if TARGET_OS_OSX
  476. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  477. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  478. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  479. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  480. GGML_METAL_LOG_WARN(", warning: current allocated size is greater than the recommended max working set size\n", __func__);
  481. } else {
  482. GGML_METAL_LOG_INFO("\n");
  483. }
  484. #else
  485. GGML_METAL_LOG_INFO(", (%8.2f)\n", ctx->device.currentAllocatedSize / 1024.0 / 1024.0);
  486. #endif
  487. }
  488. return true;
  489. }
  490. void ggml_metal_set_tensor(
  491. struct ggml_metal_context * ctx,
  492. struct ggml_tensor * t) {
  493. size_t offs;
  494. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  495. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  496. }
  497. void ggml_metal_get_tensor(
  498. struct ggml_metal_context * ctx,
  499. struct ggml_tensor * t) {
  500. size_t offs;
  501. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  502. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  503. }
  504. void ggml_metal_graph_find_concurrency(
  505. struct ggml_metal_context * ctx,
  506. struct ggml_cgraph * gf, bool check_mem) {
  507. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  508. int nodes_unused[GGML_MAX_CONCUR];
  509. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  510. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  511. ctx->concur_list_len = 0;
  512. int n_left = gf->n_nodes;
  513. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  514. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  515. while (n_left > 0) {
  516. // number of nodes at a layer (that can be issued concurrently)
  517. int concurrency = 0;
  518. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  519. if (nodes_unused[i]) {
  520. // if the requirements for gf->nodes[i] are satisfied
  521. int exe_flag = 1;
  522. // scan all srcs
  523. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  524. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  525. if (src_cur) {
  526. // if is leaf nodes it's satisfied.
  527. // TODO: ggml_is_leaf()
  528. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  529. continue;
  530. }
  531. // otherwise this src should be the output from previous nodes.
  532. int is_found = 0;
  533. // scan 2*search_depth back because we inserted barrier.
  534. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  535. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  536. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  537. is_found = 1;
  538. break;
  539. }
  540. }
  541. if (is_found == 0) {
  542. exe_flag = 0;
  543. break;
  544. }
  545. }
  546. }
  547. if (exe_flag && check_mem) {
  548. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  549. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  550. int64_t data_start = (int64_t) gf->nodes[i]->data;
  551. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  552. for (int j = n_start; j < i; j++) {
  553. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  554. && gf->nodes[j]->op != GGML_OP_VIEW \
  555. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  556. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  557. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  558. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  559. continue;
  560. }
  561. exe_flag = 0;
  562. }
  563. }
  564. }
  565. if (exe_flag) {
  566. ctx->concur_list[level_pos + concurrency] = i;
  567. nodes_unused[i] = 0;
  568. concurrency++;
  569. ctx->concur_list_len++;
  570. }
  571. }
  572. }
  573. n_left -= concurrency;
  574. // adding a barrier different layer
  575. ctx->concur_list[level_pos + concurrency] = -1;
  576. ctx->concur_list_len++;
  577. // jump all sorted nodes at nodes_bak
  578. while (!nodes_unused[n_start]) {
  579. n_start++;
  580. }
  581. level_pos += concurrency + 1;
  582. }
  583. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  584. GGML_METAL_LOG_WARN("%s: too many elements for metal ctx->concur_list!\n", __func__);
  585. }
  586. }
  587. void ggml_metal_graph_compute(
  588. struct ggml_metal_context * ctx,
  589. struct ggml_cgraph * gf) {
  590. @autoreleasepool {
  591. // if there is ctx->concur_list, dispatch concurrently
  592. // else fallback to serial dispatch
  593. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  594. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  595. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  596. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  597. // create multiple command buffers and enqueue them
  598. // then, we encode the graph into the command buffers in parallel
  599. const int n_cb = ctx->n_cb;
  600. for (int i = 0; i < n_cb; ++i) {
  601. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  602. // enqueue the command buffers in order to specify their execution order
  603. [ctx->command_buffers[i] enqueue];
  604. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  605. }
  606. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  607. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  608. dispatch_async(ctx->d_queue, ^{
  609. size_t offs_src0 = 0;
  610. size_t offs_src1 = 0;
  611. size_t offs_dst = 0;
  612. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  613. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  614. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  615. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  616. for (int ind = node_start; ind < node_end; ++ind) {
  617. const int i = has_concur ? ctx->concur_list[ind] : ind;
  618. if (i == -1) {
  619. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  620. continue;
  621. }
  622. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  623. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  624. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  625. struct ggml_tensor * dst = gf->nodes[i];
  626. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  627. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  628. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  629. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  630. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  631. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  632. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  633. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  634. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  635. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  636. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  637. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  638. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  639. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  640. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  641. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  642. const int64_t ne0 = dst ? dst->ne[0] : 0;
  643. const int64_t ne1 = dst ? dst->ne[1] : 0;
  644. const int64_t ne2 = dst ? dst->ne[2] : 0;
  645. const int64_t ne3 = dst ? dst->ne[3] : 0;
  646. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  647. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  648. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  649. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  650. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  651. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  652. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  653. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  654. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  655. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  656. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  657. //if (src0) {
  658. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  659. // ggml_is_contiguous(src0), src0->name);
  660. //}
  661. //if (src1) {
  662. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  663. // ggml_is_contiguous(src1), src1->name);
  664. //}
  665. //if (dst) {
  666. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  667. // dst->name);
  668. //}
  669. switch (dst->op) {
  670. case GGML_OP_NONE:
  671. case GGML_OP_RESHAPE:
  672. case GGML_OP_VIEW:
  673. case GGML_OP_TRANSPOSE:
  674. case GGML_OP_PERMUTE:
  675. {
  676. // noop
  677. } break;
  678. case GGML_OP_CONCAT:
  679. {
  680. const int64_t nb = ne00;
  681. [encoder setComputePipelineState:ctx->pipeline_concat];
  682. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  683. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  684. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  685. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  686. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  687. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  688. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  689. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  690. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  691. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  692. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  693. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  694. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  695. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  696. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  697. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  698. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  699. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  700. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  701. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  702. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  703. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  704. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  705. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  706. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  707. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  708. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  709. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  710. const int nth = MIN(1024, ne0);
  711. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  712. } break;
  713. case GGML_OP_ADD:
  714. {
  715. GGML_ASSERT(ggml_is_contiguous(src0));
  716. GGML_ASSERT(ggml_is_contiguous(src1));
  717. bool bcast_row = false;
  718. int64_t nb = ne00;
  719. if (ggml_nelements(src1) == ne10 && ne00 % 4 == 0) {
  720. // src1 is a row
  721. GGML_ASSERT(ne11 == 1);
  722. nb = ne00 / 4;
  723. [encoder setComputePipelineState:ctx->pipeline_add_row];
  724. bcast_row = true;
  725. } else {
  726. [encoder setComputePipelineState:ctx->pipeline_add];
  727. }
  728. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  729. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  730. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  731. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  732. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  733. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  734. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  735. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  736. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  737. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  738. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  739. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  740. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  741. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  742. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  743. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  744. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  745. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  746. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  747. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  748. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  749. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  750. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  751. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  752. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  753. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  754. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  755. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  756. if (bcast_row) {
  757. const int64_t n = ggml_nelements(dst)/4;
  758. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  759. } else {
  760. const int nth = MIN(1024, ne0);
  761. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  762. }
  763. } break;
  764. case GGML_OP_MUL:
  765. {
  766. GGML_ASSERT(ggml_is_contiguous(src0));
  767. GGML_ASSERT(ggml_is_contiguous(src1));
  768. // utilize float4
  769. GGML_ASSERT(ne00 % 4 == 0);
  770. const int64_t nb = ne00/4;
  771. if (ggml_nelements(src1) == ne10) {
  772. // src1 is a row
  773. GGML_ASSERT(ne11 == 1);
  774. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  775. } else {
  776. [encoder setComputePipelineState:ctx->pipeline_mul];
  777. }
  778. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  779. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  780. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  781. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  782. const int64_t n = ggml_nelements(dst)/4;
  783. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  784. } break;
  785. case GGML_OP_SCALE:
  786. {
  787. GGML_ASSERT(ggml_is_contiguous(src0));
  788. const float scale = *(const float *) src1->data;
  789. int64_t n = ggml_nelements(dst);
  790. if (n % 4 == 0) {
  791. n /= 4;
  792. [encoder setComputePipelineState:ctx->pipeline_scale_4];
  793. } else {
  794. [encoder setComputePipelineState:ctx->pipeline_scale];
  795. }
  796. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  797. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  798. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  799. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  800. } break;
  801. case GGML_OP_UNARY:
  802. switch (ggml_get_unary_op(gf->nodes[i])) {
  803. case GGML_UNARY_OP_SILU:
  804. {
  805. [encoder setComputePipelineState:ctx->pipeline_silu];
  806. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  807. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  808. const int64_t n = ggml_nelements(dst);
  809. GGML_ASSERT(n % 4 == 0);
  810. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  811. } break;
  812. case GGML_UNARY_OP_RELU:
  813. {
  814. [encoder setComputePipelineState:ctx->pipeline_relu];
  815. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  816. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  817. const int64_t n = ggml_nelements(dst);
  818. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  819. } break;
  820. case GGML_UNARY_OP_GELU:
  821. {
  822. [encoder setComputePipelineState:ctx->pipeline_gelu];
  823. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  824. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  825. const int64_t n = ggml_nelements(dst);
  826. GGML_ASSERT(n % 4 == 0);
  827. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  828. } break;
  829. default:
  830. {
  831. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  832. GGML_ASSERT(false);
  833. }
  834. } break;
  835. case GGML_OP_SQR:
  836. {
  837. GGML_ASSERT(ggml_is_contiguous(src0));
  838. [encoder setComputePipelineState:ctx->pipeline_sqr];
  839. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  840. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  841. const int64_t n = ggml_nelements(dst);
  842. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  843. } break;
  844. case GGML_OP_SOFT_MAX:
  845. {
  846. const int nth = MIN(32, ne00);
  847. if (ne00%4 == 0) {
  848. [encoder setComputePipelineState:ctx->pipeline_soft_max_4];
  849. } else {
  850. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  851. }
  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(ne00) atIndex:2];
  855. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  856. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  857. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  858. } break;
  859. case GGML_OP_DIAG_MASK_INF:
  860. {
  861. const int n_past = ((int32_t *)(dst->op_params))[0];
  862. if (ne00%8 == 0) {
  863. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf_8];
  864. } else {
  865. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  866. }
  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(ne00) atIndex:2];
  870. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  871. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  872. if (ne00%8 == 0) {
  873. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  874. }
  875. else {
  876. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  877. }
  878. } break;
  879. case GGML_OP_MUL_MAT:
  880. {
  881. GGML_ASSERT(ne00 == ne10);
  882. GGML_ASSERT(ne03 == ne13);
  883. const uint gqa = ne12/ne02;
  884. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  885. // to the matrix-vector kernel
  886. int ne11_mm_min = 1;
  887. #if 0
  888. // the numbers below are measured on M2 Ultra for 7B and 13B models
  889. // these numbers do not translate to other devices or model sizes
  890. // TODO: need to find a better approach
  891. if ([ctx->device.name isEqualToString:@"Apple M2 Ultra"]) {
  892. switch (src0t) {
  893. case GGML_TYPE_F16: ne11_mm_min = 2; break;
  894. case GGML_TYPE_Q8_0: ne11_mm_min = 7; break;
  895. case GGML_TYPE_Q2_K: ne11_mm_min = 15; break;
  896. case GGML_TYPE_Q3_K: ne11_mm_min = 7; break;
  897. case GGML_TYPE_Q4_0:
  898. case GGML_TYPE_Q4_1: ne11_mm_min = 15; break;
  899. case GGML_TYPE_Q4_K: ne11_mm_min = 11; break;
  900. case GGML_TYPE_Q5_0: // not tested yet
  901. case GGML_TYPE_Q5_1: ne11_mm_min = 13; break; // not tested yet
  902. case GGML_TYPE_Q5_K: ne11_mm_min = 7; break;
  903. case GGML_TYPE_Q6_K: ne11_mm_min = 7; break;
  904. default: ne11_mm_min = 1; break;
  905. }
  906. }
  907. #endif
  908. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  909. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  910. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  911. !ggml_is_transposed(src0) &&
  912. !ggml_is_transposed(src1) &&
  913. src1t == GGML_TYPE_F32 &&
  914. ne00 % 32 == 0 && ne00 >= 64 &&
  915. ne11 > ne11_mm_min) {
  916. //printf("matrix: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  917. switch (src0->type) {
  918. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f32_f32]; break;
  919. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  920. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  921. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  922. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_0_f32]; break;
  923. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_1_f32]; break;
  924. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  925. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  926. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  927. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  928. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  929. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  930. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  931. }
  932. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  933. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  934. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  935. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  936. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  937. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  938. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  939. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  940. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  941. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  942. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  943. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  944. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  945. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:13];
  946. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  947. [encoder dispatchThreadgroups:MTLSizeMake( (ne11 + 31)/32, (ne01 + 63)/64, ne12) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  948. } else {
  949. int nth0 = 32;
  950. int nth1 = 1;
  951. int nrows = 1;
  952. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  953. // use custom matrix x vector kernel
  954. switch (src0t) {
  955. case GGML_TYPE_F32:
  956. {
  957. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f32_f32];
  958. nrows = 4;
  959. } break;
  960. case GGML_TYPE_F16:
  961. {
  962. nth0 = 32;
  963. nth1 = 1;
  964. if (ne11 * ne12 < 4) {
  965. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_1row];
  966. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  967. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_l4];
  968. nrows = ne11;
  969. } else {
  970. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32];
  971. nrows = 4;
  972. }
  973. } break;
  974. case GGML_TYPE_Q4_0:
  975. {
  976. GGML_ASSERT(ne02 == 1);
  977. GGML_ASSERT(ne12 == 1);
  978. nth0 = 8;
  979. nth1 = 8;
  980. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_0_f32];
  981. } break;
  982. case GGML_TYPE_Q4_1:
  983. {
  984. GGML_ASSERT(ne02 == 1);
  985. GGML_ASSERT(ne12 == 1);
  986. nth0 = 8;
  987. nth1 = 8;
  988. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_1_f32];
  989. } break;
  990. case GGML_TYPE_Q5_0:
  991. {
  992. GGML_ASSERT(ne02 == 1);
  993. GGML_ASSERT(ne12 == 1);
  994. nth0 = 8;
  995. nth1 = 8;
  996. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_0_f32];
  997. } break;
  998. case GGML_TYPE_Q5_1:
  999. {
  1000. GGML_ASSERT(ne02 == 1);
  1001. GGML_ASSERT(ne12 == 1);
  1002. nth0 = 8;
  1003. nth1 = 8;
  1004. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_1_f32];
  1005. } break;
  1006. case GGML_TYPE_Q8_0:
  1007. {
  1008. GGML_ASSERT(ne02 == 1);
  1009. GGML_ASSERT(ne12 == 1);
  1010. nth0 = 8;
  1011. nth1 = 8;
  1012. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q8_0_f32];
  1013. } break;
  1014. case GGML_TYPE_Q2_K:
  1015. {
  1016. GGML_ASSERT(ne02 == 1);
  1017. GGML_ASSERT(ne12 == 1);
  1018. nth0 = 2;
  1019. nth1 = 32;
  1020. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q2_K_f32];
  1021. } break;
  1022. case GGML_TYPE_Q3_K:
  1023. {
  1024. GGML_ASSERT(ne02 == 1);
  1025. GGML_ASSERT(ne12 == 1);
  1026. nth0 = 2;
  1027. nth1 = 32;
  1028. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q3_K_f32];
  1029. } break;
  1030. case GGML_TYPE_Q4_K:
  1031. {
  1032. GGML_ASSERT(ne02 == 1);
  1033. GGML_ASSERT(ne12 == 1);
  1034. nth0 = 4; //1;
  1035. nth1 = 8; //32;
  1036. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_K_f32];
  1037. } break;
  1038. case GGML_TYPE_Q5_K:
  1039. {
  1040. GGML_ASSERT(ne02 == 1);
  1041. GGML_ASSERT(ne12 == 1);
  1042. nth0 = 2;
  1043. nth1 = 32;
  1044. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_K_f32];
  1045. } break;
  1046. case GGML_TYPE_Q6_K:
  1047. {
  1048. GGML_ASSERT(ne02 == 1);
  1049. GGML_ASSERT(ne12 == 1);
  1050. nth0 = 2;
  1051. nth1 = 32;
  1052. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q6_K_f32];
  1053. } break;
  1054. default:
  1055. {
  1056. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  1057. GGML_ASSERT(false && "not implemented");
  1058. }
  1059. };
  1060. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1061. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1062. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1063. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1064. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1065. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1066. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1067. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1068. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1069. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  1070. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  1071. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  1072. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  1073. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  1074. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  1075. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  1076. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  1077. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:17];
  1078. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 ||
  1079. src0t == GGML_TYPE_Q5_0 || src0t == GGML_TYPE_Q5_1 || src0t == GGML_TYPE_Q8_0 ||
  1080. src0t == GGML_TYPE_Q2_K) { // || src0t == GGML_TYPE_Q4_K) {
  1081. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1082. }
  1083. else if (src0t == GGML_TYPE_Q4_K) {
  1084. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1085. }
  1086. else if (src0t == GGML_TYPE_Q3_K) {
  1087. #ifdef GGML_QKK_64
  1088. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1089. #else
  1090. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1091. #endif
  1092. }
  1093. else if (src0t == GGML_TYPE_Q5_K) {
  1094. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1095. }
  1096. else if (src0t == GGML_TYPE_Q6_K) {
  1097. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1098. } else {
  1099. int64_t ny = (ne11 + nrows - 1)/nrows;
  1100. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1101. }
  1102. }
  1103. } break;
  1104. case GGML_OP_GET_ROWS:
  1105. {
  1106. switch (src0->type) {
  1107. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_get_rows_f32]; break;
  1108. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  1109. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  1110. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  1111. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_0]; break;
  1112. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_1]; break;
  1113. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  1114. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  1115. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  1116. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  1117. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  1118. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  1119. default: GGML_ASSERT(false && "not implemented");
  1120. }
  1121. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1122. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1123. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1124. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1125. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  1126. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:5];
  1127. const int64_t n = ggml_nelements(src1);
  1128. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1129. } break;
  1130. case GGML_OP_RMS_NORM:
  1131. {
  1132. GGML_ASSERT(ne00 % 4 == 0);
  1133. float eps;
  1134. memcpy(&eps, dst->op_params, sizeof(float));
  1135. const int nth = MIN(512, ne00);
  1136. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  1137. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1138. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1139. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1140. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1141. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1142. [encoder setThreadgroupMemoryLength:nth/32*sizeof(float) atIndex:0];
  1143. const int64_t nrows = ggml_nrows(src0);
  1144. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1145. } break;
  1146. case GGML_OP_NORM:
  1147. {
  1148. float eps;
  1149. memcpy(&eps, dst->op_params, sizeof(float));
  1150. const int nth = MIN(256, ne00);
  1151. [encoder setComputePipelineState:ctx->pipeline_norm];
  1152. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1153. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1154. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1155. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1156. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1157. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  1158. const int64_t nrows = ggml_nrows(src0);
  1159. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1160. } break;
  1161. case GGML_OP_ALIBI:
  1162. {
  1163. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1164. const int nth = MIN(1024, ne00);
  1165. //const int n_past = ((int32_t *) dst->op_params)[0];
  1166. const int n_head = ((int32_t *) dst->op_params)[1];
  1167. float max_bias;
  1168. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1169. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1170. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1171. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  1172. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  1173. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1174. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1175. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1176. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1177. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1178. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1179. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1180. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1181. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1182. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1183. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1184. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1185. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1186. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1187. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1188. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1189. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1190. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1191. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1192. [encoder setBytes:&m1 length:sizeof( float) atIndex:19];
  1193. [encoder setBytes:&n_heads_log2_floor length:sizeof(int) atIndex:20];
  1194. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1195. } break;
  1196. case GGML_OP_ROPE:
  1197. {
  1198. GGML_ASSERT(ne10 == ne02);
  1199. const int nth = MIN(1024, ne00);
  1200. const int n_past = ((int32_t *) dst->op_params)[0];
  1201. const int n_dims = ((int32_t *) dst->op_params)[1];
  1202. const int mode = ((int32_t *) dst->op_params)[2];
  1203. float freq_base;
  1204. float freq_scale;
  1205. memcpy(&freq_base, (int32_t *) dst->op_params + 4, sizeof(float));
  1206. memcpy(&freq_scale, (int32_t *) dst->op_params + 5, sizeof(float));
  1207. switch (src0->type) {
  1208. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_rope_f32]; break;
  1209. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_rope_f16]; break;
  1210. default: GGML_ASSERT(false);
  1211. };
  1212. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1213. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1214. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1215. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1216. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:4];
  1217. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:5];
  1218. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:6];
  1219. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:7];
  1220. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:8];
  1221. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:9];
  1222. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:10];
  1223. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:11];
  1224. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:12];
  1225. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:13];
  1226. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:14];
  1227. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:15];
  1228. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:16];
  1229. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:17];
  1230. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:18];
  1231. [encoder setBytes:&n_past length:sizeof( int) atIndex:19];
  1232. [encoder setBytes:&n_dims length:sizeof( int) atIndex:20];
  1233. [encoder setBytes:&mode length:sizeof( int) atIndex:21];
  1234. [encoder setBytes:&freq_base length:sizeof(float) atIndex:22];
  1235. [encoder setBytes:&freq_scale length:sizeof(float) atIndex:23];
  1236. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1237. } break;
  1238. case GGML_OP_DUP:
  1239. case GGML_OP_CPY:
  1240. case GGML_OP_CONT:
  1241. {
  1242. const int nth = MIN(1024, ne00);
  1243. switch (src0t) {
  1244. case GGML_TYPE_F32:
  1245. {
  1246. switch (dstt) {
  1247. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  1248. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  1249. default: GGML_ASSERT(false && "not implemented");
  1250. };
  1251. } break;
  1252. case GGML_TYPE_F16:
  1253. {
  1254. switch (dstt) {
  1255. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  1256. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  1257. default: GGML_ASSERT(false && "not implemented");
  1258. };
  1259. } break;
  1260. default: GGML_ASSERT(false && "not implemented");
  1261. }
  1262. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1263. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1264. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1265. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1266. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1267. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1268. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1269. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1270. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1271. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1272. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1273. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1274. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1275. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1276. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1277. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1278. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1279. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1280. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1281. } break;
  1282. default:
  1283. {
  1284. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1285. GGML_ASSERT(false);
  1286. }
  1287. }
  1288. }
  1289. if (encoder != nil) {
  1290. [encoder endEncoding];
  1291. encoder = nil;
  1292. }
  1293. [command_buffer commit];
  1294. });
  1295. }
  1296. // wait for all threads to finish
  1297. dispatch_barrier_sync(ctx->d_queue, ^{});
  1298. // check status of command buffers
  1299. // needed to detect if the device ran out-of-memory for example (#1881)
  1300. for (int i = 0; i < n_cb; i++) {
  1301. [ctx->command_buffers[i] waitUntilCompleted];
  1302. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  1303. if (status != MTLCommandBufferStatusCompleted) {
  1304. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  1305. GGML_ASSERT(false);
  1306. }
  1307. }
  1308. }
  1309. }
  1310. ////////////////////////////////////////////////////////////////////////////////
  1311. // backend interface
  1312. static const char * ggml_backend_metal_name(ggml_backend_t backend) {
  1313. return "Metal";
  1314. UNUSED(backend);
  1315. }
  1316. static void ggml_backend_metal_free(ggml_backend_t backend) {
  1317. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1318. ggml_metal_free(ctx);
  1319. free(backend);
  1320. }
  1321. static void * ggml_backend_metal_buffer_get_base(ggml_backend_buffer_t buffer) {
  1322. return (void *)buffer->context;
  1323. }
  1324. static void ggml_backend_metal_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  1325. free(buffer->context);
  1326. UNUSED(buffer);
  1327. }
  1328. static struct ggml_backend_buffer_i metal_backend_buffer_i = {
  1329. /* .free_buffer = */ ggml_backend_metal_buffer_free_buffer,
  1330. /* .get_base = */ ggml_backend_metal_buffer_get_base,
  1331. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  1332. /* .init_tensor = */ NULL, // no initialization required
  1333. /* .free_tensor = */ NULL, // no cleanup required
  1334. };
  1335. static ggml_backend_buffer_t ggml_backend_metal_alloc_buffer(ggml_backend_t backend, size_t size) {
  1336. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1337. void * data = ggml_metal_host_malloc(size);
  1338. // TODO: set proper name of the buffers
  1339. ggml_metal_add_buffer(ctx, "backend", data, size, 0);
  1340. return ggml_backend_buffer_init(backend, metal_backend_buffer_i, data, size);
  1341. }
  1342. static size_t ggml_backend_metal_get_alignment(ggml_backend_t backend) {
  1343. return 32;
  1344. UNUSED(backend);
  1345. }
  1346. static void ggml_backend_metal_set_tensor_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  1347. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
  1348. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  1349. memcpy((char *)tensor->data + offset, data, size);
  1350. UNUSED(backend);
  1351. }
  1352. static void ggml_backend_metal_get_tensor_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  1353. GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
  1354. GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
  1355. memcpy(data, (const char *)tensor->data + offset, size);
  1356. UNUSED(backend);
  1357. }
  1358. static void ggml_backend_metal_synchronize(ggml_backend_t backend) {
  1359. UNUSED(backend);
  1360. }
  1361. static void ggml_backend_metal_cpy_tensor_from(ggml_backend_t backend, struct ggml_tensor * src, struct ggml_tensor * dst) {
  1362. ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
  1363. UNUSED(backend);
  1364. }
  1365. static void ggml_backend_metal_cpy_tensor_to(ggml_backend_t backend, struct ggml_tensor * src, struct ggml_tensor * dst) {
  1366. ggml_backend_tensor_set_async(dst, src->data, 0, ggml_nbytes(src));
  1367. UNUSED(backend);
  1368. }
  1369. static void ggml_backend_metal_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  1370. struct ggml_metal_context * metal_ctx = (struct ggml_metal_context *)backend->context;
  1371. ggml_metal_graph_compute(metal_ctx, cgraph);
  1372. }
  1373. static bool ggml_backend_metal_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  1374. return true;
  1375. UNUSED(backend);
  1376. UNUSED(op);
  1377. }
  1378. static struct ggml_backend_i metal_backend_i = {
  1379. /* .get_name = */ ggml_backend_metal_name,
  1380. /* .free = */ ggml_backend_metal_free,
  1381. /* .alloc_buffer = */ ggml_backend_metal_alloc_buffer,
  1382. /* .get_alignment = */ ggml_backend_metal_get_alignment,
  1383. /* .set_tensor_async = */ ggml_backend_metal_set_tensor_async,
  1384. /* .get_tensor_async = */ ggml_backend_metal_get_tensor_async,
  1385. /* .synchronize = */ ggml_backend_metal_synchronize,
  1386. /* .cpy_tensor_from = */ ggml_backend_metal_cpy_tensor_from,
  1387. /* .cpy_tensor_to = */ ggml_backend_metal_cpy_tensor_to,
  1388. /* .graph_plan_create = */ NULL, // the metal implementation does not require creating graph plans atm
  1389. /* .graph_plan_free = */ NULL,
  1390. /* .graph_plan_compute = */ NULL,
  1391. /* .graph_compute = */ ggml_backend_metal_graph_compute,
  1392. /* .supports_op = */ ggml_backend_metal_supports_op,
  1393. };
  1394. ggml_backend_t ggml_backend_metal_init(void) {
  1395. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  1396. ctx = ggml_metal_init(GGML_DEFAULT_N_THREADS);
  1397. ggml_backend_t metal_backend = malloc(sizeof(struct ggml_backend));
  1398. *metal_backend = (struct ggml_backend) {
  1399. /* .interface = */ metal_backend_i,
  1400. /* .context = */ ctx,
  1401. };
  1402. return metal_backend;
  1403. }
  1404. bool ggml_backend_is_metal(ggml_backend_t backend) {
  1405. return backend->iface.get_name == ggml_backend_metal_name;
  1406. }
  1407. void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
  1408. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  1409. ggml_metal_set_n_cb(ctx, n_cb);
  1410. }