ggml-metal.m 84 KB

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