ggml-metal.m 79 KB

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