ggml-metal.m 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. // TODO: temporary - reuse llama.cpp logging
  10. #ifdef GGML_METAL_NDEBUG
  11. #define metal_printf(...)
  12. #else
  13. #define metal_printf(...) fprintf(stderr, __VA_ARGS__)
  14. #endif
  15. #define UNUSED(x) (void)(x)
  16. #define GGML_MAX_CONCUR (2*GGML_MAX_NODES)
  17. struct ggml_metal_buffer {
  18. const char * name;
  19. void * data;
  20. size_t size;
  21. id<MTLBuffer> metal;
  22. };
  23. struct ggml_metal_context {
  24. int n_cb;
  25. id<MTLDevice> device;
  26. id<MTLCommandQueue> queue;
  27. id<MTLLibrary> library;
  28. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  29. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  30. dispatch_queue_t d_queue;
  31. int n_buffers;
  32. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  33. int concur_list[GGML_MAX_CONCUR];
  34. int concur_list_len;
  35. // custom kernels
  36. #define GGML_METAL_DECL_KERNEL(name) \
  37. id<MTLFunction> function_##name; \
  38. id<MTLComputePipelineState> pipeline_##name
  39. GGML_METAL_DECL_KERNEL(add);
  40. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  41. GGML_METAL_DECL_KERNEL(mul);
  42. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  43. GGML_METAL_DECL_KERNEL(scale);
  44. GGML_METAL_DECL_KERNEL(silu);
  45. GGML_METAL_DECL_KERNEL(relu);
  46. GGML_METAL_DECL_KERNEL(gelu);
  47. GGML_METAL_DECL_KERNEL(soft_max);
  48. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  49. GGML_METAL_DECL_KERNEL(get_rows_f16);
  50. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  51. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  52. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  53. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  54. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  55. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  56. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  57. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  58. GGML_METAL_DECL_KERNEL(rms_norm);
  59. GGML_METAL_DECL_KERNEL(norm);
  60. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32);
  61. GGML_METAL_DECL_KERNEL(mul_mat_f16_f32_1row);
  62. GGML_METAL_DECL_KERNEL(mul_mat_q4_0_f32);
  63. GGML_METAL_DECL_KERNEL(mul_mat_q4_1_f32);
  64. GGML_METAL_DECL_KERNEL(mul_mat_q8_0_f32);
  65. GGML_METAL_DECL_KERNEL(mul_mat_q2_K_f32);
  66. GGML_METAL_DECL_KERNEL(mul_mat_q3_K_f32);
  67. GGML_METAL_DECL_KERNEL(mul_mat_q4_K_f32);
  68. GGML_METAL_DECL_KERNEL(mul_mat_q5_K_f32);
  69. GGML_METAL_DECL_KERNEL(mul_mat_q6_K_f32);
  70. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  71. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  72. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  73. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  74. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  75. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  77. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  79. GGML_METAL_DECL_KERNEL(rope);
  80. GGML_METAL_DECL_KERNEL(alibi_f32);
  81. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  82. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  83. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  84. #undef GGML_METAL_DECL_KERNEL
  85. };
  86. // MSL code
  87. // TODO: move the contents here when ready
  88. // for now it is easier to work in a separate file
  89. static NSString * const msl_library_source = @"see metal.metal";
  90. // Here to assist with NSBundle Path Hack
  91. @interface GGMLMetalClass : NSObject
  92. @end
  93. @implementation GGMLMetalClass
  94. @end
  95. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  96. metal_printf("%s: allocating\n", __func__);
  97. // Show all the Metal device instances in the system
  98. NSArray * devices = MTLCopyAllDevices();
  99. id <MTLDevice> device;
  100. NSString * s;
  101. for (device in devices) {
  102. s = [device name];
  103. metal_printf("%s: found device: %s\n", __func__, [s UTF8String]);
  104. }
  105. // Pick and show default Metal device
  106. device = MTLCreateSystemDefaultDevice();
  107. s = [device name];
  108. metal_printf("%s: picking default device: %s\n", __func__, [s UTF8String]);
  109. // Configure context
  110. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  111. ctx->device = device;
  112. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  113. ctx->queue = [ctx->device newCommandQueue];
  114. ctx->n_buffers = 0;
  115. ctx->concur_list_len = 0;
  116. ctx->d_queue = dispatch_queue_create("llama.cpp", DISPATCH_QUEUE_CONCURRENT);
  117. #if 0
  118. // compile from source string and show compile log
  119. {
  120. NSError * error = nil;
  121. ctx->library = [ctx->device newLibraryWithSource:msl_library_source options:nil error:&error];
  122. if (error) {
  123. metal_printf("%s: error: %s\n", __func__, [[error description] UTF8String]);
  124. return NULL;
  125. }
  126. }
  127. #else
  128. UNUSED(msl_library_source);
  129. // read the source from "ggml-metal.metal" into a string and use newLibraryWithSource
  130. {
  131. NSError * error = nil;
  132. //NSString * path = [[NSBundle mainBundle] pathForResource:@"../../examples/metal/metal" ofType:@"metal"];
  133. NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  134. NSString * path = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  135. metal_printf("%s: loading '%s'\n", __func__, [path UTF8String]);
  136. NSString * src = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
  137. if (error) {
  138. metal_printf("%s: error: %s\n", __func__, [[error description] UTF8String]);
  139. return NULL;
  140. }
  141. #ifdef GGML_QKK_64
  142. MTLCompileOptions* options = [MTLCompileOptions new];
  143. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  144. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  145. #else
  146. ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];
  147. #endif
  148. if (error) {
  149. metal_printf("%s: error: %s\n", __func__, [[error description] UTF8String]);
  150. return NULL;
  151. }
  152. }
  153. #endif
  154. // load kernels
  155. {
  156. NSError * error = nil;
  157. #define GGML_METAL_ADD_KERNEL(name) \
  158. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  159. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  160. metal_printf("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  161. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  162. (int) ctx->pipeline_##name.threadExecutionWidth); \
  163. if (error) { \
  164. metal_printf("%s: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  165. return NULL; \
  166. }
  167. GGML_METAL_ADD_KERNEL(add);
  168. GGML_METAL_ADD_KERNEL(add_row);
  169. GGML_METAL_ADD_KERNEL(mul);
  170. GGML_METAL_ADD_KERNEL(mul_row);
  171. GGML_METAL_ADD_KERNEL(scale);
  172. GGML_METAL_ADD_KERNEL(silu);
  173. GGML_METAL_ADD_KERNEL(relu);
  174. GGML_METAL_ADD_KERNEL(gelu);
  175. GGML_METAL_ADD_KERNEL(soft_max);
  176. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  177. GGML_METAL_ADD_KERNEL(get_rows_f16);
  178. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  179. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  180. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  181. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  182. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  183. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  184. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  185. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  186. GGML_METAL_ADD_KERNEL(rms_norm);
  187. GGML_METAL_ADD_KERNEL(norm);
  188. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32);
  189. GGML_METAL_ADD_KERNEL(mul_mat_f16_f32_1row);
  190. GGML_METAL_ADD_KERNEL(mul_mat_q4_0_f32);
  191. GGML_METAL_ADD_KERNEL(mul_mat_q4_1_f32);
  192. GGML_METAL_ADD_KERNEL(mul_mat_q8_0_f32);
  193. GGML_METAL_ADD_KERNEL(mul_mat_q2_K_f32);
  194. GGML_METAL_ADD_KERNEL(mul_mat_q3_K_f32);
  195. GGML_METAL_ADD_KERNEL(mul_mat_q4_K_f32);
  196. GGML_METAL_ADD_KERNEL(mul_mat_q5_K_f32);
  197. GGML_METAL_ADD_KERNEL(mul_mat_q6_K_f32);
  198. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  199. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  200. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  201. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  202. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  203. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  204. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  205. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  206. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  207. GGML_METAL_ADD_KERNEL(rope);
  208. GGML_METAL_ADD_KERNEL(alibi_f32);
  209. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  210. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  211. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  212. #undef GGML_METAL_ADD_KERNEL
  213. }
  214. metal_printf("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  215. metal_printf("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  216. if (ctx->device.maxTransferRate != 0) {
  217. metal_printf("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1024.0 / 1024.0);
  218. } else {
  219. metal_printf("%s: maxTransferRate = built-in GPU\n", __func__);
  220. }
  221. return ctx;
  222. }
  223. void ggml_metal_free(struct ggml_metal_context * ctx) {
  224. metal_printf("%s: deallocating\n", __func__);
  225. #define GGML_METAL_DEL_KERNEL(name) \
  226. [ctx->function_##name release]; \
  227. [ctx->pipeline_##name release];
  228. GGML_METAL_DEL_KERNEL(add);
  229. GGML_METAL_DEL_KERNEL(add_row);
  230. GGML_METAL_DEL_KERNEL(mul);
  231. GGML_METAL_DEL_KERNEL(mul_row);
  232. GGML_METAL_DEL_KERNEL(scale);
  233. GGML_METAL_DEL_KERNEL(silu);
  234. GGML_METAL_DEL_KERNEL(relu);
  235. GGML_METAL_DEL_KERNEL(gelu);
  236. GGML_METAL_DEL_KERNEL(soft_max);
  237. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  238. GGML_METAL_DEL_KERNEL(get_rows_f16);
  239. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  240. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  241. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  242. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  243. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  244. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  245. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  246. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  247. GGML_METAL_DEL_KERNEL(rms_norm);
  248. GGML_METAL_DEL_KERNEL(norm);
  249. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32);
  250. GGML_METAL_DEL_KERNEL(mul_mat_f16_f32_1row);
  251. GGML_METAL_DEL_KERNEL(mul_mat_q4_0_f32);
  252. GGML_METAL_DEL_KERNEL(mul_mat_q4_1_f32);
  253. GGML_METAL_DEL_KERNEL(mul_mat_q8_0_f32);
  254. GGML_METAL_DEL_KERNEL(mul_mat_q2_K_f32);
  255. GGML_METAL_DEL_KERNEL(mul_mat_q3_K_f32);
  256. GGML_METAL_DEL_KERNEL(mul_mat_q4_K_f32);
  257. GGML_METAL_DEL_KERNEL(mul_mat_q5_K_f32);
  258. GGML_METAL_DEL_KERNEL(mul_mat_q6_K_f32);
  259. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  260. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  261. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  262. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  263. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  264. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  265. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  266. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  267. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  268. GGML_METAL_DEL_KERNEL(rope);
  269. GGML_METAL_DEL_KERNEL(alibi_f32);
  270. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  271. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  272. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  273. #undef GGML_METAL_DEL_KERNEL
  274. for (int i = 0; i < ctx->n_buffers; ++i) {
  275. [ctx->buffers[i].metal release];
  276. }
  277. [ctx->library release];
  278. [ctx->queue release];
  279. [ctx->device release];
  280. dispatch_release(ctx->d_queue);
  281. free(ctx);
  282. }
  283. void * ggml_metal_host_malloc(size_t n) {
  284. void * data = NULL;
  285. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  286. if (result != 0) {
  287. metal_printf("%s: error: posix_memalign failed\n", __func__);
  288. return NULL;
  289. }
  290. return data;
  291. }
  292. void ggml_metal_host_free(void * data) {
  293. free(data);
  294. }
  295. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  296. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  297. }
  298. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  299. return ctx->concur_list_len;
  300. }
  301. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  302. return ctx->concur_list;
  303. }
  304. // finds the Metal buffer that contains the tensor data on the GPU device
  305. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  306. // Metal buffer based on the host memory pointer
  307. //
  308. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  309. //metal_printf("%s: data tensor '%16s', offs_data = %8ld, offs_eval = %8ld, offs_cach = %8ld\n", __func__, t->name, offs_data, offs_eval, offs_cach);
  310. const int64_t tsize = ggml_nbytes(t);
  311. // find the view that contains the tensor fully
  312. for (int i = 0; i < ctx->n_buffers; ++i) {
  313. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  314. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  315. *offs = (size_t) ioffs;
  316. //metal_printf("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  317. return ctx->buffers[i].metal;
  318. }
  319. }
  320. metal_printf("%s: error: buffer is nil\n", __func__);
  321. return nil;
  322. }
  323. bool ggml_metal_add_buffer(
  324. struct ggml_metal_context * ctx,
  325. const char * name,
  326. void * data,
  327. size_t size,
  328. size_t max_size) {
  329. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  330. metal_printf("%s: too many buffers\n", __func__);
  331. return false;
  332. }
  333. if (data) {
  334. // verify that the buffer does not overlap with any of the existing buffers
  335. for (int i = 0; i < ctx->n_buffers; ++i) {
  336. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  337. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  338. metal_printf("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  339. return false;
  340. }
  341. }
  342. const size_t size_page = sysconf(_SC_PAGESIZE);
  343. size_t size_aligned = size;
  344. if ((size_aligned % size_page) != 0) {
  345. size_aligned += (size_page - (size_aligned % size_page));
  346. }
  347. // the buffer fits into the max buffer size allowed by the device
  348. if (size_aligned <= ctx->device.maxBufferLength) {
  349. ctx->buffers[ctx->n_buffers].name = name;
  350. ctx->buffers[ctx->n_buffers].data = data;
  351. ctx->buffers[ctx->n_buffers].size = size;
  352. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  353. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  354. metal_printf("%s: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  355. return false;
  356. }
  357. metal_printf("%s: allocated '%-16s' buffer, size = %8.2f MB", __func__, name, size_aligned / 1024.0 / 1024.0);
  358. ++ctx->n_buffers;
  359. } else {
  360. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  361. // one of the views
  362. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  363. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  364. const size_t size_view = ctx->device.maxBufferLength;
  365. for (size_t i = 0; i < size; i += size_step) {
  366. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  367. ctx->buffers[ctx->n_buffers].name = name;
  368. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  369. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  370. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  371. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  372. metal_printf("%s: failed to allocate '%-16s' buffer, size = %8.2f MB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  373. return false;
  374. }
  375. metal_printf("%s: allocated '%-16s' buffer, size = %8.2f MB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  376. if (i + size_step < size) {
  377. metal_printf("\n");
  378. }
  379. ++ctx->n_buffers;
  380. }
  381. }
  382. metal_printf(", (%8.2f / %8.2f)",
  383. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  384. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  385. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  386. metal_printf(", warning: current allocated size is greater than the recommended max working set size\n");
  387. } else {
  388. metal_printf("\n");
  389. }
  390. }
  391. return true;
  392. }
  393. void ggml_metal_set_tensor(
  394. struct ggml_metal_context * ctx,
  395. struct ggml_tensor * t) {
  396. size_t offs;
  397. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  398. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  399. }
  400. void ggml_metal_get_tensor(
  401. struct ggml_metal_context * ctx,
  402. struct ggml_tensor * t) {
  403. size_t offs;
  404. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  405. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  406. }
  407. void ggml_metal_graph_find_concurrency(
  408. struct ggml_metal_context * ctx,
  409. struct ggml_cgraph * gf, bool check_mem) {
  410. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  411. int nodes_unused[GGML_MAX_CONCUR];
  412. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  413. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  414. ctx->concur_list_len = 0;
  415. int n_left = gf->n_nodes;
  416. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  417. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  418. while (n_left > 0) {
  419. // number of nodes at a layer (that can be issued concurrently)
  420. int concurrency = 0;
  421. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  422. if (nodes_unused[i]) {
  423. // if the requirements for gf->nodes[i] are satisfied
  424. int exe_flag = 1;
  425. // scan all srcs
  426. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  427. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  428. if (src_cur) {
  429. // if is leaf nodes it's satisfied.
  430. // TODO: ggml_is_leaf()
  431. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  432. continue;
  433. }
  434. // otherwise this src should be the output from previous nodes.
  435. int is_found = 0;
  436. // scan 2*search_depth back because we inserted barrier.
  437. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  438. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  439. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  440. is_found = 1;
  441. break;
  442. }
  443. }
  444. if (is_found == 0) {
  445. exe_flag = 0;
  446. break;
  447. }
  448. }
  449. }
  450. if (exe_flag && check_mem) {
  451. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  452. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  453. int64_t data_start = (int64_t) gf->nodes[i]->data;
  454. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  455. for (int j = n_start; j < i; j++) {
  456. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  457. && gf->nodes[j]->op != GGML_OP_VIEW \
  458. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  459. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  460. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  461. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  462. continue;
  463. }
  464. exe_flag = 0;
  465. }
  466. }
  467. }
  468. if (exe_flag) {
  469. ctx->concur_list[level_pos + concurrency] = i;
  470. nodes_unused[i] = 0;
  471. concurrency++;
  472. ctx->concur_list_len++;
  473. }
  474. }
  475. }
  476. n_left -= concurrency;
  477. // adding a barrier different layer
  478. ctx->concur_list[level_pos + concurrency] = -1;
  479. ctx->concur_list_len++;
  480. // jump all sorted nodes at nodes_bak
  481. while (!nodes_unused[n_start]) {
  482. n_start++;
  483. }
  484. level_pos += concurrency + 1;
  485. }
  486. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  487. metal_printf("%s: too many elements for metal ctx->concur_list!\n", __func__);
  488. }
  489. }
  490. void ggml_metal_graph_compute(
  491. struct ggml_metal_context * ctx,
  492. struct ggml_cgraph * gf) {
  493. @autoreleasepool {
  494. // if there is ctx->concur_list, dispatch concurrently
  495. // else fallback to serial dispatch
  496. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  497. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  498. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  499. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  500. // create multiple command buffers and enqueue them
  501. // then, we encode the graph into the command buffers in parallel
  502. const int n_cb = ctx->n_cb;
  503. for (int i = 0; i < n_cb; ++i) {
  504. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  505. // enqueue the command buffers in order to specify their execution order
  506. [ctx->command_buffers[i] enqueue];
  507. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  508. }
  509. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  510. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  511. dispatch_async(ctx->d_queue, ^{
  512. size_t offs_src0 = 0;
  513. size_t offs_src1 = 0;
  514. size_t offs_dst = 0;
  515. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  516. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  517. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  518. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  519. for (int ind = node_start; ind < node_end; ++ind) {
  520. const int i = has_concur ? ctx->concur_list[ind] : ind;
  521. if (i == -1) {
  522. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  523. continue;
  524. }
  525. //metal_printf("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  526. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  527. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  528. struct ggml_tensor * dst = gf->nodes[i];
  529. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  530. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  531. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  532. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  533. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  534. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  535. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  536. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  537. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  538. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  539. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  540. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  541. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  542. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  543. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  544. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  545. const int64_t ne0 = dst ? dst->ne[0] : 0;
  546. const int64_t ne1 = dst ? dst->ne[1] : 0;
  547. const int64_t ne2 = dst ? dst->ne[2] : 0;
  548. const int64_t ne3 = dst ? dst->ne[3] : 0;
  549. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  550. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  551. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  552. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  553. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  554. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  555. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  556. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  557. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  558. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  559. //metal_printf("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  560. //if (src0) {
  561. // metal_printf("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  562. // ggml_is_contiguous(src0), src0->name);
  563. //}
  564. //if (src1) {
  565. // metal_printf("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  566. // ggml_is_contiguous(src1), src1->name);
  567. //}
  568. //if (dst) {
  569. // metal_printf("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  570. // dst->name);
  571. //}
  572. switch (dst->op) {
  573. case GGML_OP_NONE:
  574. case GGML_OP_RESHAPE:
  575. case GGML_OP_VIEW:
  576. case GGML_OP_TRANSPOSE:
  577. case GGML_OP_PERMUTE:
  578. {
  579. // noop
  580. } break;
  581. case GGML_OP_ADD:
  582. {
  583. GGML_ASSERT(ggml_is_contiguous(src0));
  584. // utilize float4
  585. GGML_ASSERT(ne00 % 4 == 0);
  586. const int64_t nb = ne00/4;
  587. if (ggml_nelements(src1) == ne10) {
  588. // src1 is a row
  589. [encoder setComputePipelineState:ctx->pipeline_add_row];
  590. } else {
  591. [encoder setComputePipelineState:ctx->pipeline_add];
  592. }
  593. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  594. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  595. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  596. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  597. const int64_t n = ggml_nelements(dst)/4;
  598. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  599. } break;
  600. case GGML_OP_MUL:
  601. {
  602. GGML_ASSERT(ggml_is_contiguous(src0));
  603. // utilize float4
  604. GGML_ASSERT(ne00 % 4 == 0);
  605. const int64_t nb = ne00/4;
  606. if (ggml_nelements(src1) == ne10) {
  607. // src1 is a row
  608. [encoder setComputePipelineState:ctx->pipeline_mul_row];
  609. } else {
  610. [encoder setComputePipelineState:ctx->pipeline_mul];
  611. }
  612. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  613. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  614. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  615. [encoder setBytes:&nb length:sizeof(nb) atIndex:3];
  616. const int64_t n = ggml_nelements(dst)/4;
  617. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  618. } break;
  619. case GGML_OP_SCALE:
  620. {
  621. const float scale = *(const float *) src1->data;
  622. [encoder setComputePipelineState:ctx->pipeline_scale];
  623. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  624. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  625. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  626. const int64_t n = ggml_nelements(dst);
  627. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  628. } break;
  629. case GGML_OP_UNARY:
  630. switch (ggml_get_unary_op(gf->nodes[i])) {
  631. case GGML_UNARY_OP_SILU:
  632. {
  633. [encoder setComputePipelineState:ctx->pipeline_silu];
  634. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  635. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  636. const int64_t n = ggml_nelements(dst);
  637. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  638. } break;
  639. case GGML_UNARY_OP_RELU:
  640. {
  641. [encoder setComputePipelineState:ctx->pipeline_relu];
  642. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  643. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  644. const int64_t n = ggml_nelements(dst);
  645. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  646. } break;
  647. case GGML_UNARY_OP_GELU:
  648. {
  649. [encoder setComputePipelineState:ctx->pipeline_gelu];
  650. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  651. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  652. const int64_t n = ggml_nelements(dst);
  653. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  654. } break;
  655. default:
  656. {
  657. metal_printf("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  658. GGML_ASSERT(false);
  659. }
  660. } break;
  661. case GGML_OP_SOFT_MAX:
  662. {
  663. const int nth = 32;
  664. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  665. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  666. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  667. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  668. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  669. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  670. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  671. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  672. } break;
  673. case GGML_OP_DIAG_MASK_INF:
  674. {
  675. const int n_past = ((int32_t *)(dst->op_params))[0];
  676. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  677. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  678. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  679. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  680. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  681. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  682. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  683. } break;
  684. case GGML_OP_MUL_MAT:
  685. {
  686. // TODO: needs to be updated after PR: https://github.com/ggerganov/ggml/pull/224
  687. GGML_ASSERT(ne00 == ne10);
  688. // GGML_ASSERT(ne02 == ne12); // Should be checked on individual data types until broadcast is implemented everywhere
  689. uint gqa = ne12/ne02;
  690. GGML_ASSERT(ne03 == ne13);
  691. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  692. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  693. if (ggml_is_contiguous(src0) &&
  694. ggml_is_contiguous(src1) &&
  695. src1t == GGML_TYPE_F32 &&
  696. [ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  697. ne00%32 == 0 &&
  698. ne11 > 1) {
  699. switch (src0->type) {
  700. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  701. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  702. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  703. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  704. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  705. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  706. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  707. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  708. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  709. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  710. }
  711. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  712. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  713. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  714. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  715. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  716. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  717. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  718. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  719. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:8];
  720. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:9];
  721. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:10];
  722. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  723. [encoder dispatchThreadgroups:MTLSizeMake( (ne11+31)/32, (ne01+63) / 64, ne12) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  724. } else {
  725. int nth0 = 32;
  726. int nth1 = 1;
  727. // use custom matrix x vector kernel
  728. switch (src0t) {
  729. case GGML_TYPE_F16:
  730. {
  731. nth0 = 32;
  732. nth1 = 1;
  733. if (ne11 * ne12 < 4) {
  734. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32_1row];
  735. } else {
  736. [encoder setComputePipelineState:ctx->pipeline_mul_mat_f16_f32];
  737. }
  738. } break;
  739. case GGML_TYPE_Q4_0:
  740. {
  741. GGML_ASSERT(ne02 == 1);
  742. GGML_ASSERT(ne12 == 1);
  743. nth0 = 8;
  744. nth1 = 8;
  745. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_0_f32];
  746. } break;
  747. case GGML_TYPE_Q4_1:
  748. {
  749. GGML_ASSERT(ne02 == 1);
  750. GGML_ASSERT(ne12 == 1);
  751. nth0 = 8;
  752. nth1 = 8;
  753. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_1_f32];
  754. } break;
  755. case GGML_TYPE_Q8_0:
  756. {
  757. GGML_ASSERT(ne02 == 1);
  758. GGML_ASSERT(ne12 == 1);
  759. nth0 = 8;
  760. nth1 = 8;
  761. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q8_0_f32];
  762. } break;
  763. case GGML_TYPE_Q2_K:
  764. {
  765. GGML_ASSERT(ne02 == 1);
  766. GGML_ASSERT(ne12 == 1);
  767. nth0 = 2;
  768. nth1 = 32;
  769. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q2_K_f32];
  770. } break;
  771. case GGML_TYPE_Q3_K:
  772. {
  773. GGML_ASSERT(ne02 == 1);
  774. GGML_ASSERT(ne12 == 1);
  775. nth0 = 2;
  776. nth1 = 32;
  777. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q3_K_f32];
  778. } break;
  779. case GGML_TYPE_Q4_K:
  780. {
  781. GGML_ASSERT(ne02 == 1);
  782. GGML_ASSERT(ne12 == 1);
  783. nth0 = 4; //1;
  784. nth1 = 8; //32;
  785. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q4_K_f32];
  786. } break;
  787. case GGML_TYPE_Q5_K:
  788. {
  789. GGML_ASSERT(ne02 == 1);
  790. GGML_ASSERT(ne12 == 1);
  791. nth0 = 2;
  792. nth1 = 32;
  793. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q5_K_f32];
  794. } break;
  795. case GGML_TYPE_Q6_K:
  796. {
  797. GGML_ASSERT(ne02 == 1);
  798. GGML_ASSERT(ne12 == 1);
  799. nth0 = 2;
  800. nth1 = 32;
  801. [encoder setComputePipelineState:ctx->pipeline_mul_mat_q6_K_f32];
  802. } break;
  803. default:
  804. {
  805. metal_printf("Asserting on type %d\n",(int)src0t);
  806. GGML_ASSERT(false && "not implemented");
  807. }
  808. };
  809. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  810. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  811. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  812. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  813. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  814. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  815. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  816. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  817. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  818. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  819. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  820. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  821. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  822. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  823. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  824. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  825. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  826. [encoder setBytes:&gqa length:sizeof(gqa) atIndex:17];
  827. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 || src0t == GGML_TYPE_Q8_0 ||
  828. src0t == GGML_TYPE_Q2_K) {// || src0t == GGML_TYPE_Q4_K) {
  829. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  830. }
  831. else if (src0t == GGML_TYPE_Q4_K) {
  832. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  833. }
  834. else if (src0t == GGML_TYPE_Q3_K) {
  835. #ifdef GGML_QKK_64
  836. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  837. #else
  838. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  839. #endif
  840. }
  841. else if (src0t == GGML_TYPE_Q5_K) {
  842. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  843. }
  844. else if (src0t == GGML_TYPE_Q6_K) {
  845. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  846. } else {
  847. int64_t ny = (ne11 + 3)/4;
  848. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  849. }
  850. }
  851. } break;
  852. case GGML_OP_GET_ROWS:
  853. {
  854. switch (src0->type) {
  855. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  856. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  857. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  858. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  859. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  860. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  861. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  862. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  863. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  864. default: GGML_ASSERT(false && "not implemented");
  865. }
  866. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  867. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  868. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  869. [encoder setBytes:&(src0->ne[0]) length:sizeof( int64_t) atIndex:3];
  870. [encoder setBytes:&(src0->nb[1]) length:sizeof(uint64_t) atIndex:4];
  871. [encoder setBytes:&(dst->nb[1]) length:sizeof(uint64_t) atIndex:5];
  872. const int64_t n = ggml_nelements(src1);
  873. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  874. } break;
  875. case GGML_OP_RMS_NORM:
  876. {
  877. float eps;
  878. memcpy(&eps, dst->op_params, sizeof(float));
  879. const int nth = 512;
  880. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  881. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  882. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  883. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  884. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  885. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  886. [encoder setThreadgroupMemoryLength:nth/32*sizeof(float) atIndex:0];
  887. const int64_t nrows = ggml_nrows(src0);
  888. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  889. } break;
  890. case GGML_OP_NORM:
  891. {
  892. float eps;
  893. memcpy(&eps, dst->op_params, sizeof(float));
  894. const int nth = 256;
  895. [encoder setComputePipelineState:ctx->pipeline_norm];
  896. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  897. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  898. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  899. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  900. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  901. [encoder setThreadgroupMemoryLength:nth*sizeof(float) atIndex:0];
  902. const int64_t nrows = ggml_nrows(src0);
  903. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  904. } break;
  905. case GGML_OP_ALIBI:
  906. {
  907. GGML_ASSERT((src0t == GGML_TYPE_F32));
  908. const int n_past = ((int32_t *) dst->op_params)[0]; UNUSED(n_past);
  909. const int n_head = ((int32_t *) dst->op_params)[1];
  910. float max_bias;
  911. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  912. if (__builtin_popcount(n_head) != 1) {
  913. GGML_ASSERT(false && "only power-of-two n_head implemented");
  914. }
  915. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  916. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  917. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  918. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  919. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  920. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  921. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  922. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  923. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  924. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  925. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  926. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  927. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  928. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  929. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  930. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  931. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  932. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  933. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  934. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  935. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  936. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  937. const int nth = 32;
  938. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  939. } break;
  940. case GGML_OP_ROPE:
  941. {
  942. const int n_past = ((int32_t *) dst->op_params)[0];
  943. const int n_dims = ((int32_t *) dst->op_params)[1];
  944. const int mode = ((int32_t *) dst->op_params)[2];
  945. float freq_base;
  946. float freq_scale;
  947. memcpy(&freq_base, (int32_t *) dst->op_params + 4, sizeof(float));
  948. memcpy(&freq_scale, (int32_t *) dst->op_params + 5, sizeof(float));
  949. [encoder setComputePipelineState:ctx->pipeline_rope];
  950. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  951. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  952. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  953. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  954. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  955. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  956. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  957. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  958. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  959. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  960. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  961. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  962. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  963. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  964. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  965. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  966. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  967. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  968. [encoder setBytes:&n_past length:sizeof( int) atIndex:18];
  969. [encoder setBytes:&n_dims length:sizeof( int) atIndex:19];
  970. [encoder setBytes:&mode length:sizeof( int) atIndex:20];
  971. [encoder setBytes:&freq_base length:sizeof(float) atIndex:21];
  972. [encoder setBytes:&freq_scale length:sizeof(float) atIndex:22];
  973. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
  974. } break;
  975. case GGML_OP_DUP:
  976. case GGML_OP_CPY:
  977. case GGML_OP_CONT:
  978. {
  979. const int nth = 32;
  980. switch (src0t) {
  981. case GGML_TYPE_F32:
  982. {
  983. switch (dstt) {
  984. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  985. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  986. default: GGML_ASSERT(false && "not implemented");
  987. };
  988. } break;
  989. case GGML_TYPE_F16:
  990. {
  991. switch (dstt) {
  992. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  993. case GGML_TYPE_F32: GGML_ASSERT(false && "cpy_f16_f32 not implemented"); break;
  994. default: GGML_ASSERT(false && "not implemented");
  995. };
  996. } break;
  997. default: GGML_ASSERT(false && "not implemented");
  998. }
  999. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1000. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1001. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1002. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1003. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1004. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1005. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1006. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1007. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1008. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1009. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1010. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1011. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1012. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1013. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1014. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1015. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1016. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1017. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1018. } break;
  1019. default:
  1020. {
  1021. metal_printf("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1022. GGML_ASSERT(false);
  1023. }
  1024. }
  1025. }
  1026. if (encoder != nil) {
  1027. [encoder endEncoding];
  1028. encoder = nil;
  1029. }
  1030. [command_buffer commit];
  1031. });
  1032. }
  1033. // wait for all threads to finish
  1034. dispatch_barrier_sync(ctx->d_queue, ^{});
  1035. // check status of command buffers
  1036. // needed to detect if the device ran out-of-memory for example (#1881)
  1037. for (int i = 0; i < n_cb; i++) {
  1038. [ctx->command_buffers[i] waitUntilCompleted];
  1039. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  1040. if (status != MTLCommandBufferStatusCompleted) {
  1041. metal_printf("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  1042. GGML_ASSERT(false);
  1043. }
  1044. }
  1045. }
  1046. }