ggml-metal.m 82 KB

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