ggml-metal.m 84 KB

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