ggml-metal.m 74 KB

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