ggml-metal.m 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740
  1. #import "ggml-metal.h"
  2. #import "ggml-backend-impl.h"
  3. #import "ggml.h"
  4. #import <Foundation/Foundation.h>
  5. #import <Metal/Metal.h>
  6. #undef MIN
  7. #undef MAX
  8. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  9. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  10. #ifdef GGML_METAL_NDEBUG
  11. #define GGML_METAL_LOG_INFO(...)
  12. #define GGML_METAL_LOG_WARN(...)
  13. #define GGML_METAL_LOG_ERROR(...)
  14. #else
  15. #define GGML_METAL_LOG_INFO(...) ggml_metal_log(GGML_LOG_LEVEL_INFO, __VA_ARGS__)
  16. #define GGML_METAL_LOG_WARN(...) ggml_metal_log(GGML_LOG_LEVEL_WARN, __VA_ARGS__)
  17. #define GGML_METAL_LOG_ERROR(...) ggml_metal_log(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  18. #endif
  19. #define UNUSED(x) (void)(x)
  20. #define GGML_MAX_CONCUR (2*GGML_DEFAULT_GRAPH_SIZE)
  21. struct ggml_metal_buffer {
  22. const char * name;
  23. void * data;
  24. size_t size;
  25. id<MTLBuffer> metal;
  26. };
  27. struct ggml_metal_context {
  28. int n_cb;
  29. id<MTLDevice> device;
  30. id<MTLCommandQueue> queue;
  31. id<MTLLibrary> library;
  32. id<MTLCommandBuffer> command_buffers [GGML_METAL_MAX_COMMAND_BUFFERS];
  33. id<MTLComputeCommandEncoder> command_encoders[GGML_METAL_MAX_COMMAND_BUFFERS];
  34. dispatch_queue_t d_queue;
  35. int n_buffers;
  36. struct ggml_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  37. int concur_list[GGML_MAX_CONCUR];
  38. int concur_list_len;
  39. // custom kernels
  40. #define GGML_METAL_DECL_KERNEL(name) \
  41. id<MTLFunction> function_##name; \
  42. id<MTLComputePipelineState> pipeline_##name
  43. GGML_METAL_DECL_KERNEL(add);
  44. GGML_METAL_DECL_KERNEL(add_row); // TODO: avoid this extra kernel, instead extend the "add" kernel to support broadcast
  45. GGML_METAL_DECL_KERNEL(mul);
  46. GGML_METAL_DECL_KERNEL(mul_row); // TODO: avoid this extra kernel, instead extend the "mul" kernel to support broadcast
  47. GGML_METAL_DECL_KERNEL(div);
  48. GGML_METAL_DECL_KERNEL(div_row);
  49. GGML_METAL_DECL_KERNEL(scale);
  50. GGML_METAL_DECL_KERNEL(scale_4);
  51. GGML_METAL_DECL_KERNEL(tanh);
  52. GGML_METAL_DECL_KERNEL(relu);
  53. GGML_METAL_DECL_KERNEL(gelu);
  54. GGML_METAL_DECL_KERNEL(gelu_quick);
  55. GGML_METAL_DECL_KERNEL(silu);
  56. GGML_METAL_DECL_KERNEL(soft_max);
  57. GGML_METAL_DECL_KERNEL(soft_max_4);
  58. GGML_METAL_DECL_KERNEL(diag_mask_inf);
  59. GGML_METAL_DECL_KERNEL(diag_mask_inf_8);
  60. GGML_METAL_DECL_KERNEL(get_rows_f32);
  61. GGML_METAL_DECL_KERNEL(get_rows_f16);
  62. GGML_METAL_DECL_KERNEL(get_rows_q4_0);
  63. GGML_METAL_DECL_KERNEL(get_rows_q4_1);
  64. GGML_METAL_DECL_KERNEL(get_rows_q5_0);
  65. GGML_METAL_DECL_KERNEL(get_rows_q5_1);
  66. GGML_METAL_DECL_KERNEL(get_rows_q8_0);
  67. GGML_METAL_DECL_KERNEL(get_rows_q2_K);
  68. GGML_METAL_DECL_KERNEL(get_rows_q3_K);
  69. GGML_METAL_DECL_KERNEL(get_rows_q4_K);
  70. GGML_METAL_DECL_KERNEL(get_rows_q5_K);
  71. GGML_METAL_DECL_KERNEL(get_rows_q6_K);
  72. GGML_METAL_DECL_KERNEL(rms_norm);
  73. GGML_METAL_DECL_KERNEL(group_norm);
  74. GGML_METAL_DECL_KERNEL(norm);
  75. GGML_METAL_DECL_KERNEL(mul_mv_f32_f32);
  76. GGML_METAL_DECL_KERNEL(mul_mv_f16_f16);
  77. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32);
  78. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_1row);
  79. GGML_METAL_DECL_KERNEL(mul_mv_f16_f32_l4);
  80. GGML_METAL_DECL_KERNEL(mul_mv_q4_0_f32);
  81. GGML_METAL_DECL_KERNEL(mul_mv_q4_1_f32);
  82. GGML_METAL_DECL_KERNEL(mul_mv_q5_0_f32);
  83. GGML_METAL_DECL_KERNEL(mul_mv_q5_1_f32);
  84. GGML_METAL_DECL_KERNEL(mul_mv_q8_0_f32);
  85. GGML_METAL_DECL_KERNEL(mul_mv_q2_K_f32);
  86. GGML_METAL_DECL_KERNEL(mul_mv_q3_K_f32);
  87. GGML_METAL_DECL_KERNEL(mul_mv_q4_K_f32);
  88. GGML_METAL_DECL_KERNEL(mul_mv_q5_K_f32);
  89. GGML_METAL_DECL_KERNEL(mul_mv_q6_K_f32);
  90. GGML_METAL_DECL_KERNEL(mul_mv_id_f32_f32);
  91. //GGML_METAL_DECL_KERNEL(mul_mv_id_f16_f16);
  92. GGML_METAL_DECL_KERNEL(mul_mv_id_f16_f32);
  93. //GGML_METAL_DECL_KERNEL(mul_mv_id_f16_f32_1row);
  94. //GGML_METAL_DECL_KERNEL(mul_mv_id_f16_f32_l4);
  95. GGML_METAL_DECL_KERNEL(mul_mv_id_q4_0_f32);
  96. GGML_METAL_DECL_KERNEL(mul_mv_id_q4_1_f32);
  97. GGML_METAL_DECL_KERNEL(mul_mv_id_q5_0_f32);
  98. GGML_METAL_DECL_KERNEL(mul_mv_id_q5_1_f32);
  99. GGML_METAL_DECL_KERNEL(mul_mv_id_q8_0_f32);
  100. GGML_METAL_DECL_KERNEL(mul_mv_id_q2_K_f32);
  101. GGML_METAL_DECL_KERNEL(mul_mv_id_q3_K_f32);
  102. GGML_METAL_DECL_KERNEL(mul_mv_id_q4_K_f32);
  103. GGML_METAL_DECL_KERNEL(mul_mv_id_q5_K_f32);
  104. GGML_METAL_DECL_KERNEL(mul_mv_id_q6_K_f32);
  105. GGML_METAL_DECL_KERNEL(mul_mm_f32_f32);
  106. GGML_METAL_DECL_KERNEL(mul_mm_f16_f32);
  107. GGML_METAL_DECL_KERNEL(mul_mm_q4_0_f32);
  108. GGML_METAL_DECL_KERNEL(mul_mm_q4_1_f32);
  109. GGML_METAL_DECL_KERNEL(mul_mm_q5_0_f32);
  110. GGML_METAL_DECL_KERNEL(mul_mm_q5_1_f32);
  111. GGML_METAL_DECL_KERNEL(mul_mm_q8_0_f32);
  112. GGML_METAL_DECL_KERNEL(mul_mm_q2_K_f32);
  113. GGML_METAL_DECL_KERNEL(mul_mm_q3_K_f32);
  114. GGML_METAL_DECL_KERNEL(mul_mm_q4_K_f32);
  115. GGML_METAL_DECL_KERNEL(mul_mm_q5_K_f32);
  116. GGML_METAL_DECL_KERNEL(mul_mm_q6_K_f32);
  117. GGML_METAL_DECL_KERNEL(mul_mm_id_f32_f32);
  118. GGML_METAL_DECL_KERNEL(mul_mm_id_f16_f32);
  119. GGML_METAL_DECL_KERNEL(mul_mm_id_q4_0_f32);
  120. GGML_METAL_DECL_KERNEL(mul_mm_id_q4_1_f32);
  121. GGML_METAL_DECL_KERNEL(mul_mm_id_q5_0_f32);
  122. GGML_METAL_DECL_KERNEL(mul_mm_id_q5_1_f32);
  123. GGML_METAL_DECL_KERNEL(mul_mm_id_q8_0_f32);
  124. GGML_METAL_DECL_KERNEL(mul_mm_id_q2_K_f32);
  125. GGML_METAL_DECL_KERNEL(mul_mm_id_q3_K_f32);
  126. GGML_METAL_DECL_KERNEL(mul_mm_id_q4_K_f32);
  127. GGML_METAL_DECL_KERNEL(mul_mm_id_q5_K_f32);
  128. GGML_METAL_DECL_KERNEL(mul_mm_id_q6_K_f32);
  129. GGML_METAL_DECL_KERNEL(rope_f32);
  130. GGML_METAL_DECL_KERNEL(rope_f16);
  131. GGML_METAL_DECL_KERNEL(alibi_f32);
  132. GGML_METAL_DECL_KERNEL(im2col_f16);
  133. GGML_METAL_DECL_KERNEL(upscale_f32);
  134. GGML_METAL_DECL_KERNEL(pad_f32);
  135. GGML_METAL_DECL_KERNEL(argsort_f32_i32_asc);
  136. GGML_METAL_DECL_KERNEL(argsort_f32_i32_desc);
  137. GGML_METAL_DECL_KERNEL(leaky_relu_f32);
  138. GGML_METAL_DECL_KERNEL(cpy_f32_f16);
  139. GGML_METAL_DECL_KERNEL(cpy_f32_f32);
  140. GGML_METAL_DECL_KERNEL(cpy_f32_q8_0);
  141. GGML_METAL_DECL_KERNEL(cpy_f32_q4_0);
  142. GGML_METAL_DECL_KERNEL(cpy_f32_q4_1);
  143. //GGML_METAL_DECL_KERNEL(cpy_f32_q5_0);
  144. //GGML_METAL_DECL_KERNEL(cpy_f32_q5_1);
  145. GGML_METAL_DECL_KERNEL(cpy_f16_f16);
  146. GGML_METAL_DECL_KERNEL(cpy_f16_f32);
  147. GGML_METAL_DECL_KERNEL(concat);
  148. GGML_METAL_DECL_KERNEL(sqr);
  149. GGML_METAL_DECL_KERNEL(sum_rows);
  150. #undef GGML_METAL_DECL_KERNEL
  151. };
  152. // MSL code
  153. // TODO: move the contents here when ready
  154. // for now it is easier to work in a separate file
  155. //static NSString * const msl_library_source = @"see metal.metal";
  156. // Here to assist with NSBundle Path Hack
  157. @interface GGMLMetalClass : NSObject
  158. @end
  159. @implementation GGMLMetalClass
  160. @end
  161. static void ggml_metal_default_log_callback(enum ggml_log_level level, const char * msg, void * user_data) {
  162. fprintf(stderr, "%s", msg);
  163. UNUSED(level);
  164. UNUSED(user_data);
  165. }
  166. ggml_log_callback ggml_metal_log_callback = ggml_metal_default_log_callback;
  167. void * ggml_metal_log_user_data = NULL;
  168. void ggml_metal_log_set_callback(ggml_log_callback log_callback, void * user_data) {
  169. ggml_metal_log_callback = log_callback;
  170. ggml_metal_log_user_data = user_data;
  171. }
  172. GGML_ATTRIBUTE_FORMAT(2, 3)
  173. static void ggml_metal_log(enum ggml_log_level level, const char * format, ...){
  174. if (ggml_metal_log_callback != NULL) {
  175. va_list args;
  176. va_start(args, format);
  177. char buffer[128];
  178. int len = vsnprintf(buffer, 128, format, args);
  179. if (len < 128) {
  180. ggml_metal_log_callback(level, buffer, ggml_metal_log_user_data);
  181. } else {
  182. char* buffer2 = malloc(len+1);
  183. va_end(args);
  184. va_start(args, format);
  185. vsnprintf(buffer2, len+1, format, args);
  186. buffer2[len] = 0;
  187. ggml_metal_log_callback(level, buffer2, ggml_metal_log_user_data);
  188. free(buffer2);
  189. }
  190. va_end(args);
  191. }
  192. }
  193. struct ggml_metal_context * ggml_metal_init(int n_cb) {
  194. GGML_METAL_LOG_INFO("%s: allocating\n", __func__);
  195. id<MTLDevice> device;
  196. NSString * s;
  197. #if TARGET_OS_OSX
  198. // Show all the Metal device instances in the system
  199. NSArray * devices = MTLCopyAllDevices();
  200. for (device in devices) {
  201. s = [device name];
  202. GGML_METAL_LOG_INFO("%s: found device: %s\n", __func__, [s UTF8String]);
  203. }
  204. #endif
  205. // Pick and show default Metal device
  206. device = MTLCreateSystemDefaultDevice();
  207. s = [device name];
  208. GGML_METAL_LOG_INFO("%s: picking default device: %s\n", __func__, [s UTF8String]);
  209. // Configure context
  210. struct ggml_metal_context * ctx = malloc(sizeof(struct ggml_metal_context));
  211. ctx->device = device;
  212. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  213. ctx->queue = [ctx->device newCommandQueue];
  214. ctx->n_buffers = 0;
  215. ctx->concur_list_len = 0;
  216. ctx->d_queue = dispatch_queue_create("ggml-metal", DISPATCH_QUEUE_CONCURRENT);
  217. // load library
  218. {
  219. NSBundle * bundle = nil;
  220. #ifdef SWIFT_PACKAGE
  221. bundle = SWIFTPM_MODULE_BUNDLE;
  222. #else
  223. bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
  224. #endif
  225. NSError * error = nil;
  226. NSString * libPath = [bundle pathForResource:@"default" ofType:@"metallib"];
  227. if (libPath != nil) {
  228. NSURL * libURL = [NSURL fileURLWithPath:libPath];
  229. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [libPath UTF8String]);
  230. ctx->library = [ctx->device newLibraryWithURL:libURL error:&error];
  231. } else {
  232. GGML_METAL_LOG_INFO("%s: default.metallib not found, loading from source\n", __func__);
  233. NSString * sourcePath;
  234. NSString * ggmlMetalPathResources = [[NSProcessInfo processInfo].environment objectForKey:@"GGML_METAL_PATH_RESOURCES"];
  235. GGML_METAL_LOG_INFO("%s: GGML_METAL_PATH_RESOURCES = %s\n", __func__, ggmlMetalPathResources ? [ggmlMetalPathResources UTF8String] : "nil");
  236. if (ggmlMetalPathResources) {
  237. sourcePath = [ggmlMetalPathResources stringByAppendingPathComponent:@"ggml-metal.metal"];
  238. } else {
  239. sourcePath = [bundle pathForResource:@"ggml-metal" ofType:@"metal"];
  240. }
  241. if (sourcePath == nil) {
  242. GGML_METAL_LOG_WARN("%s: error: could not use bundle path to find ggml-metal.metal, falling back to trying cwd\n", __func__);
  243. sourcePath = @"ggml-metal.metal";
  244. }
  245. GGML_METAL_LOG_INFO("%s: loading '%s'\n", __func__, [sourcePath UTF8String]);
  246. NSString * src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:&error];
  247. if (error) {
  248. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  249. return NULL;
  250. }
  251. MTLCompileOptions* options = nil;
  252. #ifdef GGML_QKK_64
  253. options = [MTLCompileOptions new];
  254. options.preprocessorMacros = @{ @"QK_K" : @(64) };
  255. #endif
  256. ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
  257. }
  258. if (error) {
  259. GGML_METAL_LOG_ERROR("%s: error: %s\n", __func__, [[error description] UTF8String]);
  260. return NULL;
  261. }
  262. }
  263. #if TARGET_OS_OSX
  264. // print MTL GPU family:
  265. GGML_METAL_LOG_INFO("%s: GPU name: %s\n", __func__, [[ctx->device name] UTF8String]);
  266. // determine max supported GPU family
  267. // https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf
  268. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  269. for (int i = MTLGPUFamilyApple1 + 20; i >= MTLGPUFamilyApple1; --i) {
  270. if ([ctx->device supportsFamily:i]) {
  271. GGML_METAL_LOG_INFO("%s: GPU family: MTLGPUFamilyApple%d (%d)\n", __func__, i - (int) MTLGPUFamilyApple1 + 1, i);
  272. break;
  273. }
  274. }
  275. GGML_METAL_LOG_INFO("%s: hasUnifiedMemory = %s\n", __func__, ctx->device.hasUnifiedMemory ? "true" : "false");
  276. GGML_METAL_LOG_INFO("%s: recommendedMaxWorkingSetSize = %8.2f MB\n", __func__, ctx->device.recommendedMaxWorkingSetSize / 1e6);
  277. if (ctx->device.maxTransferRate != 0) {
  278. GGML_METAL_LOG_INFO("%s: maxTransferRate = %8.2f MB/s\n", __func__, ctx->device.maxTransferRate / 1e6);
  279. } else {
  280. GGML_METAL_LOG_INFO("%s: maxTransferRate = built-in GPU\n", __func__);
  281. }
  282. #endif
  283. // load kernels
  284. {
  285. NSError * error = nil;
  286. /*
  287. GGML_METAL_LOG_INFO("%s: loaded %-32s %16p | th_max = %4d | th_width = %4d\n", __func__, "kernel_"#name, (void *) ctx->pipeline_##name, \
  288. (int) ctx->pipeline_##name.maxTotalThreadsPerThreadgroup, \
  289. (int) ctx->pipeline_##name.threadExecutionWidth); \
  290. */
  291. #define GGML_METAL_ADD_KERNEL(name) \
  292. ctx->function_##name = [ctx->library newFunctionWithName:@"kernel_"#name]; \
  293. ctx->pipeline_##name = [ctx->device newComputePipelineStateWithFunction:ctx->function_##name error:&error]; \
  294. if (error) { \
  295. GGML_METAL_LOG_ERROR("%s: error: load pipeline error: %s\n", __func__, [[error description] UTF8String]); \
  296. return NULL; \
  297. }
  298. GGML_METAL_ADD_KERNEL(add);
  299. GGML_METAL_ADD_KERNEL(add_row);
  300. GGML_METAL_ADD_KERNEL(mul);
  301. GGML_METAL_ADD_KERNEL(mul_row);
  302. GGML_METAL_ADD_KERNEL(div);
  303. GGML_METAL_ADD_KERNEL(div_row);
  304. GGML_METAL_ADD_KERNEL(scale);
  305. GGML_METAL_ADD_KERNEL(scale_4);
  306. GGML_METAL_ADD_KERNEL(tanh);
  307. GGML_METAL_ADD_KERNEL(relu);
  308. GGML_METAL_ADD_KERNEL(gelu);
  309. GGML_METAL_ADD_KERNEL(gelu_quick);
  310. GGML_METAL_ADD_KERNEL(silu);
  311. GGML_METAL_ADD_KERNEL(soft_max);
  312. GGML_METAL_ADD_KERNEL(soft_max_4);
  313. GGML_METAL_ADD_KERNEL(diag_mask_inf);
  314. GGML_METAL_ADD_KERNEL(diag_mask_inf_8);
  315. GGML_METAL_ADD_KERNEL(get_rows_f32);
  316. GGML_METAL_ADD_KERNEL(get_rows_f16);
  317. GGML_METAL_ADD_KERNEL(get_rows_q4_0);
  318. GGML_METAL_ADD_KERNEL(get_rows_q4_1);
  319. GGML_METAL_ADD_KERNEL(get_rows_q5_0);
  320. GGML_METAL_ADD_KERNEL(get_rows_q5_1);
  321. GGML_METAL_ADD_KERNEL(get_rows_q8_0);
  322. GGML_METAL_ADD_KERNEL(get_rows_q2_K);
  323. GGML_METAL_ADD_KERNEL(get_rows_q3_K);
  324. GGML_METAL_ADD_KERNEL(get_rows_q4_K);
  325. GGML_METAL_ADD_KERNEL(get_rows_q5_K);
  326. GGML_METAL_ADD_KERNEL(get_rows_q6_K);
  327. GGML_METAL_ADD_KERNEL(rms_norm);
  328. GGML_METAL_ADD_KERNEL(group_norm);
  329. GGML_METAL_ADD_KERNEL(norm);
  330. GGML_METAL_ADD_KERNEL(mul_mv_f32_f32);
  331. GGML_METAL_ADD_KERNEL(mul_mv_f16_f16);
  332. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32);
  333. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_1row);
  334. GGML_METAL_ADD_KERNEL(mul_mv_f16_f32_l4);
  335. GGML_METAL_ADD_KERNEL(mul_mv_q4_0_f32);
  336. GGML_METAL_ADD_KERNEL(mul_mv_q4_1_f32);
  337. GGML_METAL_ADD_KERNEL(mul_mv_q5_0_f32);
  338. GGML_METAL_ADD_KERNEL(mul_mv_q5_1_f32);
  339. GGML_METAL_ADD_KERNEL(mul_mv_q8_0_f32);
  340. GGML_METAL_ADD_KERNEL(mul_mv_q2_K_f32);
  341. GGML_METAL_ADD_KERNEL(mul_mv_q3_K_f32);
  342. GGML_METAL_ADD_KERNEL(mul_mv_q4_K_f32);
  343. GGML_METAL_ADD_KERNEL(mul_mv_q5_K_f32);
  344. GGML_METAL_ADD_KERNEL(mul_mv_q6_K_f32);
  345. GGML_METAL_ADD_KERNEL(mul_mv_id_f32_f32);
  346. //GGML_METAL_ADD_KERNEL(mul_mv_id_f16_f16);
  347. GGML_METAL_ADD_KERNEL(mul_mv_id_f16_f32);
  348. //GGML_METAL_ADD_KERNEL(mul_mv_id_f16_f32_1row);
  349. //GGML_METAL_ADD_KERNEL(mul_mv_id_f16_f32_l4);
  350. GGML_METAL_ADD_KERNEL(mul_mv_id_q4_0_f32);
  351. GGML_METAL_ADD_KERNEL(mul_mv_id_q4_1_f32);
  352. GGML_METAL_ADD_KERNEL(mul_mv_id_q5_0_f32);
  353. GGML_METAL_ADD_KERNEL(mul_mv_id_q5_1_f32);
  354. GGML_METAL_ADD_KERNEL(mul_mv_id_q8_0_f32);
  355. GGML_METAL_ADD_KERNEL(mul_mv_id_q2_K_f32);
  356. GGML_METAL_ADD_KERNEL(mul_mv_id_q3_K_f32);
  357. GGML_METAL_ADD_KERNEL(mul_mv_id_q4_K_f32);
  358. GGML_METAL_ADD_KERNEL(mul_mv_id_q5_K_f32);
  359. GGML_METAL_ADD_KERNEL(mul_mv_id_q6_K_f32);
  360. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  361. GGML_METAL_ADD_KERNEL(mul_mm_f32_f32);
  362. GGML_METAL_ADD_KERNEL(mul_mm_f16_f32);
  363. GGML_METAL_ADD_KERNEL(mul_mm_q4_0_f32);
  364. GGML_METAL_ADD_KERNEL(mul_mm_q4_1_f32);
  365. GGML_METAL_ADD_KERNEL(mul_mm_q5_0_f32);
  366. GGML_METAL_ADD_KERNEL(mul_mm_q5_1_f32);
  367. GGML_METAL_ADD_KERNEL(mul_mm_q8_0_f32);
  368. GGML_METAL_ADD_KERNEL(mul_mm_q2_K_f32);
  369. GGML_METAL_ADD_KERNEL(mul_mm_q3_K_f32);
  370. GGML_METAL_ADD_KERNEL(mul_mm_q4_K_f32);
  371. GGML_METAL_ADD_KERNEL(mul_mm_q5_K_f32);
  372. GGML_METAL_ADD_KERNEL(mul_mm_q6_K_f32);
  373. GGML_METAL_ADD_KERNEL(mul_mm_id_f32_f32);
  374. GGML_METAL_ADD_KERNEL(mul_mm_id_f16_f32);
  375. GGML_METAL_ADD_KERNEL(mul_mm_id_q4_0_f32);
  376. GGML_METAL_ADD_KERNEL(mul_mm_id_q4_1_f32);
  377. GGML_METAL_ADD_KERNEL(mul_mm_id_q5_0_f32);
  378. GGML_METAL_ADD_KERNEL(mul_mm_id_q5_1_f32);
  379. GGML_METAL_ADD_KERNEL(mul_mm_id_q8_0_f32);
  380. GGML_METAL_ADD_KERNEL(mul_mm_id_q2_K_f32);
  381. GGML_METAL_ADD_KERNEL(mul_mm_id_q3_K_f32);
  382. GGML_METAL_ADD_KERNEL(mul_mm_id_q4_K_f32);
  383. GGML_METAL_ADD_KERNEL(mul_mm_id_q5_K_f32);
  384. GGML_METAL_ADD_KERNEL(mul_mm_id_q6_K_f32);
  385. }
  386. GGML_METAL_ADD_KERNEL(rope_f32);
  387. GGML_METAL_ADD_KERNEL(rope_f16);
  388. GGML_METAL_ADD_KERNEL(alibi_f32);
  389. GGML_METAL_ADD_KERNEL(im2col_f16);
  390. GGML_METAL_ADD_KERNEL(upscale_f32);
  391. GGML_METAL_ADD_KERNEL(pad_f32);
  392. GGML_METAL_ADD_KERNEL(argsort_f32_i32_asc);
  393. GGML_METAL_ADD_KERNEL(argsort_f32_i32_desc);
  394. GGML_METAL_ADD_KERNEL(leaky_relu_f32);
  395. GGML_METAL_ADD_KERNEL(cpy_f32_f16);
  396. GGML_METAL_ADD_KERNEL(cpy_f32_f32);
  397. GGML_METAL_ADD_KERNEL(cpy_f32_q8_0);
  398. GGML_METAL_ADD_KERNEL(cpy_f32_q4_0);
  399. GGML_METAL_ADD_KERNEL(cpy_f32_q4_1);
  400. //GGML_METAL_ADD_KERNEL(cpy_f32_q5_0);
  401. //GGML_METAL_ADD_KERNEL(cpy_f32_q5_1);
  402. GGML_METAL_ADD_KERNEL(cpy_f16_f16);
  403. GGML_METAL_ADD_KERNEL(cpy_f16_f32);
  404. GGML_METAL_ADD_KERNEL(concat);
  405. GGML_METAL_ADD_KERNEL(sqr);
  406. GGML_METAL_ADD_KERNEL(sum_rows);
  407. #undef GGML_METAL_ADD_KERNEL
  408. }
  409. return ctx;
  410. }
  411. void ggml_metal_free(struct ggml_metal_context * ctx) {
  412. GGML_METAL_LOG_INFO("%s: deallocating\n", __func__);
  413. #define GGML_METAL_DEL_KERNEL(name) \
  414. [ctx->function_##name release]; \
  415. [ctx->pipeline_##name release];
  416. GGML_METAL_DEL_KERNEL(add);
  417. GGML_METAL_DEL_KERNEL(add_row);
  418. GGML_METAL_DEL_KERNEL(mul);
  419. GGML_METAL_DEL_KERNEL(mul_row);
  420. GGML_METAL_DEL_KERNEL(div);
  421. GGML_METAL_DEL_KERNEL(div_row);
  422. GGML_METAL_DEL_KERNEL(scale);
  423. GGML_METAL_DEL_KERNEL(scale_4);
  424. GGML_METAL_DEL_KERNEL(tanh);
  425. GGML_METAL_DEL_KERNEL(relu);
  426. GGML_METAL_DEL_KERNEL(gelu);
  427. GGML_METAL_DEL_KERNEL(gelu_quick);
  428. GGML_METAL_DEL_KERNEL(silu);
  429. GGML_METAL_DEL_KERNEL(soft_max);
  430. GGML_METAL_DEL_KERNEL(soft_max_4);
  431. GGML_METAL_DEL_KERNEL(diag_mask_inf);
  432. GGML_METAL_DEL_KERNEL(diag_mask_inf_8);
  433. GGML_METAL_DEL_KERNEL(get_rows_f32);
  434. GGML_METAL_DEL_KERNEL(get_rows_f16);
  435. GGML_METAL_DEL_KERNEL(get_rows_q4_0);
  436. GGML_METAL_DEL_KERNEL(get_rows_q4_1);
  437. GGML_METAL_DEL_KERNEL(get_rows_q5_0);
  438. GGML_METAL_DEL_KERNEL(get_rows_q5_1);
  439. GGML_METAL_DEL_KERNEL(get_rows_q8_0);
  440. GGML_METAL_DEL_KERNEL(get_rows_q2_K);
  441. GGML_METAL_DEL_KERNEL(get_rows_q3_K);
  442. GGML_METAL_DEL_KERNEL(get_rows_q4_K);
  443. GGML_METAL_DEL_KERNEL(get_rows_q5_K);
  444. GGML_METAL_DEL_KERNEL(get_rows_q6_K);
  445. GGML_METAL_DEL_KERNEL(rms_norm);
  446. GGML_METAL_DEL_KERNEL(group_norm);
  447. GGML_METAL_DEL_KERNEL(norm);
  448. GGML_METAL_DEL_KERNEL(mul_mv_f32_f32);
  449. GGML_METAL_DEL_KERNEL(mul_mv_f16_f16);
  450. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32);
  451. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_1row);
  452. GGML_METAL_DEL_KERNEL(mul_mv_f16_f32_l4);
  453. GGML_METAL_DEL_KERNEL(mul_mv_q4_0_f32);
  454. GGML_METAL_DEL_KERNEL(mul_mv_q4_1_f32);
  455. GGML_METAL_DEL_KERNEL(mul_mv_q5_0_f32);
  456. GGML_METAL_DEL_KERNEL(mul_mv_q5_1_f32);
  457. GGML_METAL_DEL_KERNEL(mul_mv_q8_0_f32);
  458. GGML_METAL_DEL_KERNEL(mul_mv_q2_K_f32);
  459. GGML_METAL_DEL_KERNEL(mul_mv_q3_K_f32);
  460. GGML_METAL_DEL_KERNEL(mul_mv_q4_K_f32);
  461. GGML_METAL_DEL_KERNEL(mul_mv_q5_K_f32);
  462. GGML_METAL_DEL_KERNEL(mul_mv_q6_K_f32);
  463. GGML_METAL_DEL_KERNEL(mul_mv_id_f32_f32);
  464. //GGML_METAL_DEL_KERNEL(mul_mv_id_f16_f16);
  465. GGML_METAL_DEL_KERNEL(mul_mv_id_f16_f32);
  466. //GGML_METAL_DEL_KERNEL(mul_mv_id_f16_f32_1row);
  467. //GGML_METAL_DEL_KERNEL(mul_mv_id_f16_f32_l4);
  468. GGML_METAL_DEL_KERNEL(mul_mv_id_q4_0_f32);
  469. GGML_METAL_DEL_KERNEL(mul_mv_id_q4_1_f32);
  470. GGML_METAL_DEL_KERNEL(mul_mv_id_q5_0_f32);
  471. GGML_METAL_DEL_KERNEL(mul_mv_id_q5_1_f32);
  472. GGML_METAL_DEL_KERNEL(mul_mv_id_q8_0_f32);
  473. GGML_METAL_DEL_KERNEL(mul_mv_id_q2_K_f32);
  474. GGML_METAL_DEL_KERNEL(mul_mv_id_q3_K_f32);
  475. GGML_METAL_DEL_KERNEL(mul_mv_id_q4_K_f32);
  476. GGML_METAL_DEL_KERNEL(mul_mv_id_q5_K_f32);
  477. GGML_METAL_DEL_KERNEL(mul_mv_id_q6_K_f32);
  478. if ([ctx->device supportsFamily:MTLGPUFamilyApple7]) {
  479. GGML_METAL_DEL_KERNEL(mul_mm_f32_f32);
  480. GGML_METAL_DEL_KERNEL(mul_mm_f16_f32);
  481. GGML_METAL_DEL_KERNEL(mul_mm_q4_0_f32);
  482. GGML_METAL_DEL_KERNEL(mul_mm_q4_1_f32);
  483. GGML_METAL_DEL_KERNEL(mul_mm_q5_0_f32);
  484. GGML_METAL_DEL_KERNEL(mul_mm_q5_1_f32);
  485. GGML_METAL_DEL_KERNEL(mul_mm_q8_0_f32);
  486. GGML_METAL_DEL_KERNEL(mul_mm_q2_K_f32);
  487. GGML_METAL_DEL_KERNEL(mul_mm_q3_K_f32);
  488. GGML_METAL_DEL_KERNEL(mul_mm_q4_K_f32);
  489. GGML_METAL_DEL_KERNEL(mul_mm_q5_K_f32);
  490. GGML_METAL_DEL_KERNEL(mul_mm_q6_K_f32);
  491. GGML_METAL_DEL_KERNEL(mul_mm_id_f32_f32);
  492. GGML_METAL_DEL_KERNEL(mul_mm_id_f16_f32);
  493. GGML_METAL_DEL_KERNEL(mul_mm_id_q4_0_f32);
  494. GGML_METAL_DEL_KERNEL(mul_mm_id_q4_1_f32);
  495. GGML_METAL_DEL_KERNEL(mul_mm_id_q5_0_f32);
  496. GGML_METAL_DEL_KERNEL(mul_mm_id_q5_1_f32);
  497. GGML_METAL_DEL_KERNEL(mul_mm_id_q8_0_f32);
  498. GGML_METAL_DEL_KERNEL(mul_mm_id_q2_K_f32);
  499. GGML_METAL_DEL_KERNEL(mul_mm_id_q3_K_f32);
  500. GGML_METAL_DEL_KERNEL(mul_mm_id_q4_K_f32);
  501. GGML_METAL_DEL_KERNEL(mul_mm_id_q5_K_f32);
  502. GGML_METAL_DEL_KERNEL(mul_mm_id_q6_K_f32);
  503. }
  504. GGML_METAL_DEL_KERNEL(rope_f32);
  505. GGML_METAL_DEL_KERNEL(rope_f16);
  506. GGML_METAL_DEL_KERNEL(alibi_f32);
  507. GGML_METAL_DEL_KERNEL(im2col_f16);
  508. GGML_METAL_DEL_KERNEL(upscale_f32);
  509. GGML_METAL_DEL_KERNEL(pad_f32);
  510. GGML_METAL_DEL_KERNEL(argsort_f32_i32_asc);
  511. GGML_METAL_DEL_KERNEL(argsort_f32_i32_desc);
  512. GGML_METAL_DEL_KERNEL(leaky_relu_f32);
  513. GGML_METAL_DEL_KERNEL(cpy_f32_f16);
  514. GGML_METAL_DEL_KERNEL(cpy_f32_f32);
  515. GGML_METAL_DEL_KERNEL(cpy_f32_q8_0);
  516. GGML_METAL_DEL_KERNEL(cpy_f32_q4_0);
  517. GGML_METAL_DEL_KERNEL(cpy_f32_q4_1);
  518. //GGML_METAL_DEL_KERNEL(cpy_f32_q5_0);
  519. //GGML_METAL_DEL_KERNEL(cpy_f32_q5_1);
  520. GGML_METAL_DEL_KERNEL(cpy_f16_f16);
  521. GGML_METAL_DEL_KERNEL(cpy_f16_f32);
  522. GGML_METAL_DEL_KERNEL(concat);
  523. GGML_METAL_DEL_KERNEL(sqr);
  524. GGML_METAL_DEL_KERNEL(sum_rows);
  525. #undef GGML_METAL_DEL_KERNEL
  526. for (int i = 0; i < ctx->n_buffers; ++i) {
  527. [ctx->buffers[i].metal release];
  528. }
  529. [ctx->library release];
  530. [ctx->queue release];
  531. [ctx->device release];
  532. dispatch_release(ctx->d_queue);
  533. free(ctx);
  534. }
  535. void * ggml_metal_host_malloc(size_t n) {
  536. void * data = NULL;
  537. const int result = posix_memalign((void **) &data, sysconf(_SC_PAGESIZE), n);
  538. if (result != 0) {
  539. GGML_METAL_LOG_ERROR("%s: error: posix_memalign failed\n", __func__);
  540. return NULL;
  541. }
  542. return data;
  543. }
  544. void ggml_metal_host_free(void * data) {
  545. free(data);
  546. }
  547. void ggml_metal_set_n_cb(struct ggml_metal_context * ctx, int n_cb) {
  548. ctx->n_cb = MIN(n_cb, GGML_METAL_MAX_BUFFERS);
  549. }
  550. int ggml_metal_if_optimized(struct ggml_metal_context * ctx) {
  551. return ctx->concur_list_len;
  552. }
  553. int * ggml_metal_get_concur_list(struct ggml_metal_context * ctx) {
  554. return ctx->concur_list;
  555. }
  556. // temporarily defined here for compatibility between ggml-backend and the old API
  557. struct ggml_backend_metal_buffer {
  558. void * data;
  559. size_t size;
  560. id<MTLBuffer> metal;
  561. };
  562. struct ggml_backend_metal_buffer_context {
  563. void * all_data;
  564. size_t all_size;
  565. bool owned;
  566. // multiple buffers are used only to avoid the maximum buffer size limitation when using mmap
  567. int n_buffers;
  568. struct ggml_backend_metal_buffer buffers[GGML_METAL_MAX_BUFFERS];
  569. };
  570. // finds the Metal buffer that contains the tensor data on the GPU device
  571. // the assumption is that there is 1-to-1 mapping between the host and device memory buffers, so we can find the
  572. // Metal buffer based on the host memory pointer
  573. //
  574. static id<MTLBuffer> ggml_metal_get_buffer(struct ggml_metal_context * ctx, struct ggml_tensor * t, size_t * offs) {
  575. //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);
  576. const int64_t tsize = ggml_nbytes(t);
  577. ggml_backend_buffer_t buffer = t->view_src ? t->view_src->buffer : t->buffer;
  578. // compatibility with ggml-backend
  579. if (buffer && buffer->buft == ggml_backend_metal_buffer_type()) {
  580. struct ggml_backend_metal_buffer_context * buf_ctx = (struct ggml_backend_metal_buffer_context *) buffer->context;
  581. // find the view that contains the tensor fully
  582. for (int i = 0; i < buf_ctx->n_buffers; ++i) {
  583. const int64_t ioffs = (int64_t) t->data - (int64_t) buf_ctx->buffers[i].data;
  584. //GGML_METAL_LOG_INFO("ioffs = %10ld, tsize = %10ld, sum = %10ld, buf_ctx->buffers[%d].size = %10ld\n", ioffs, tsize, ioffs + tsize, i, buf_ctx->buffers[i].size);
  585. if (ioffs >= 0 && ioffs + tsize <= (int64_t) buf_ctx->buffers[i].size) {
  586. *offs = (size_t) ioffs;
  587. //GGML_METAL_LOG_INFO("%s: tensor '%16s', offs = %8ld\n", __func__, t->name, *offs);
  588. return buf_ctx->buffers[i].metal;
  589. }
  590. }
  591. GGML_METAL_LOG_ERROR("%s: error: tensor '%s' buffer is nil\n", __func__, t->name);
  592. return nil;
  593. }
  594. // find the view that contains the tensor fully
  595. for (int i = 0; i < ctx->n_buffers; ++i) {
  596. const int64_t ioffs = (int64_t) t->data - (int64_t) ctx->buffers[i].data;
  597. //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);
  598. if (ioffs >= 0 && ioffs + tsize <= (int64_t) ctx->buffers[i].size) {
  599. *offs = (size_t) ioffs;
  600. //GGML_METAL_LOG_INFO("%s: '%s' tensor '%16s', offs = %8ld\n", __func__, ctx->buffers[i].name, t->name, *offs);
  601. return ctx->buffers[i].metal;
  602. }
  603. }
  604. GGML_METAL_LOG_ERROR("%s: error: buffer is nil\n", __func__);
  605. return nil;
  606. }
  607. bool ggml_metal_add_buffer(
  608. struct ggml_metal_context * ctx,
  609. const char * name,
  610. void * data,
  611. size_t size,
  612. size_t max_size) {
  613. if (ctx->n_buffers >= GGML_METAL_MAX_BUFFERS) {
  614. GGML_METAL_LOG_ERROR("%s: error: too many buffers\n", __func__);
  615. return false;
  616. }
  617. if (data) {
  618. // verify that the buffer does not overlap with any of the existing buffers
  619. for (int i = 0; i < ctx->n_buffers; ++i) {
  620. const int64_t ioffs = (int64_t) data - (int64_t) ctx->buffers[i].data;
  621. if (ioffs >= 0 && ioffs < (int64_t) ctx->buffers[i].size) {
  622. GGML_METAL_LOG_ERROR("%s: error: buffer '%s' overlaps with '%s'\n", __func__, name, ctx->buffers[i].name);
  623. return false;
  624. }
  625. }
  626. const size_t size_page = sysconf(_SC_PAGESIZE);
  627. size_t size_aligned = size;
  628. if ((size_aligned % size_page) != 0) {
  629. size_aligned += (size_page - (size_aligned % size_page));
  630. }
  631. // the buffer fits into the max buffer size allowed by the device
  632. if (size_aligned <= ctx->device.maxBufferLength) {
  633. ctx->buffers[ctx->n_buffers].name = name;
  634. ctx->buffers[ctx->n_buffers].data = data;
  635. ctx->buffers[ctx->n_buffers].size = size;
  636. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  637. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  638. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MiB\n", __func__, name, size_aligned / 1024.0 / 1024.0);
  639. return false;
  640. }
  641. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MiB", __func__, name, size_aligned / 1024.0 / 1024.0);
  642. ++ctx->n_buffers;
  643. } else {
  644. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  645. // one of the views
  646. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  647. const size_t size_step = ctx->device.maxBufferLength - size_ovlp;
  648. const size_t size_view = ctx->device.maxBufferLength;
  649. for (size_t i = 0; i < size; i += size_step) {
  650. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  651. ctx->buffers[ctx->n_buffers].name = name;
  652. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  653. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  654. ctx->buffers[ctx->n_buffers].metal = [ctx->device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  655. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  656. GGML_METAL_LOG_ERROR("%s: error: failed to allocate '%-16s' buffer, size = %8.2f MiB\n", __func__, name, size_step_aligned / 1024.0 / 1024.0);
  657. return false;
  658. }
  659. GGML_METAL_LOG_INFO("%s: allocated '%-16s' buffer, size = %8.2f MiB, offs = %12ld", __func__, name, size_step_aligned / 1024.0 / 1024.0, i);
  660. if (i + size_step < size) {
  661. GGML_METAL_LOG_INFO("\n");
  662. }
  663. ++ctx->n_buffers;
  664. }
  665. }
  666. #if TARGET_OS_OSX
  667. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  668. ctx->device.currentAllocatedSize / 1024.0 / 1024.0,
  669. ctx->device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  670. if (ctx->device.currentAllocatedSize > ctx->device.recommendedMaxWorkingSetSize) {
  671. GGML_METAL_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
  672. } else {
  673. GGML_METAL_LOG_INFO("\n");
  674. }
  675. #else
  676. GGML_METAL_LOG_INFO(", (%8.2f)\n", ctx->device.currentAllocatedSize / 1024.0 / 1024.0);
  677. #endif
  678. }
  679. return true;
  680. }
  681. void ggml_metal_set_tensor(
  682. struct ggml_metal_context * ctx,
  683. struct ggml_tensor * t) {
  684. size_t offs;
  685. id<MTLBuffer> id_dst = ggml_metal_get_buffer(ctx, t, &offs);
  686. memcpy((void *) ((uint8_t *) id_dst.contents + offs), t->data, ggml_nbytes(t));
  687. }
  688. void ggml_metal_get_tensor(
  689. struct ggml_metal_context * ctx,
  690. struct ggml_tensor * t) {
  691. size_t offs;
  692. id<MTLBuffer> id_src = ggml_metal_get_buffer(ctx, t, &offs);
  693. memcpy(t->data, (void *) ((uint8_t *) id_src.contents + offs), ggml_nbytes(t));
  694. }
  695. void ggml_metal_graph_find_concurrency(
  696. struct ggml_metal_context * ctx,
  697. struct ggml_cgraph * gf, bool check_mem) {
  698. int search_depth = gf->n_nodes; //we only find concurrency in this range to avoid wasting too much time
  699. int nodes_unused[GGML_MAX_CONCUR];
  700. for (int i = 0; i < GGML_MAX_CONCUR; i++) { ctx->concur_list[i] = 0; }
  701. for (int i = 0; i < gf->n_nodes; i++) { nodes_unused[i] = 1; }
  702. ctx->concur_list_len = 0;
  703. int n_left = gf->n_nodes;
  704. int n_start = 0; // all nodes before n_start at nodes_unused array have been sorted and store back to ctx->concur_list
  705. int level_pos = 0; // at ctx->concur_list, the last layer (level) ends at level_pos
  706. while (n_left > 0) {
  707. // number of nodes at a layer (that can be issued concurrently)
  708. int concurrency = 0;
  709. for (int i = n_start; i < ((n_start + search_depth > gf->n_nodes) ? gf->n_nodes : n_start + search_depth); i++) {
  710. if (nodes_unused[i]) {
  711. // if the requirements for gf->nodes[i] are satisfied
  712. int exe_flag = 1;
  713. // scan all srcs
  714. for (int src_ind = 0; src_ind < GGML_MAX_SRC; src_ind++) {
  715. struct ggml_tensor * src_cur = gf->nodes[i]->src[src_ind];
  716. if (src_cur) {
  717. // if is leaf nodes it's satisfied.
  718. // TODO: ggml_is_leaf()
  719. if (src_cur->op == GGML_OP_NONE && src_cur->grad == NULL) {
  720. continue;
  721. }
  722. // otherwise this src should be the output from previous nodes.
  723. int is_found = 0;
  724. // scan 2*search_depth back because we inserted barrier.
  725. //for (int j = ((level_pos - 2*search_depth) < 0 ? 0 : (level_pos - 2*search_depth)); j < level_pos; j++) {
  726. for (int j = MAX(0, level_pos - 2*search_depth); j < level_pos; j++) {
  727. if (ctx->concur_list[j] >= 0 && gf->nodes[ctx->concur_list[j]] == src_cur) {
  728. is_found = 1;
  729. break;
  730. }
  731. }
  732. if (is_found == 0) {
  733. exe_flag = 0;
  734. break;
  735. }
  736. }
  737. }
  738. if (exe_flag && check_mem) {
  739. // check if nodes[i]'s data will be overwritten by a node before nodes[i].
  740. // if node[5] and node[3] write to the same memory region, then we can't issue node[5] before node[3]
  741. int64_t data_start = (int64_t) gf->nodes[i]->data;
  742. int64_t length = (int64_t) ggml_nbytes(gf->nodes[i]);
  743. for (int j = n_start; j < i; j++) {
  744. if (nodes_unused[j] && gf->nodes[j]->op != GGML_OP_RESHAPE \
  745. && gf->nodes[j]->op != GGML_OP_VIEW \
  746. && gf->nodes[j]->op != GGML_OP_TRANSPOSE \
  747. && gf->nodes[j]->op != GGML_OP_PERMUTE) {
  748. if (((int64_t)gf->nodes[j]->data) >= data_start + length || \
  749. ((int64_t)gf->nodes[j]->data) + (int64_t) ggml_nbytes(gf->nodes[j]) <= data_start) {
  750. continue;
  751. }
  752. exe_flag = 0;
  753. }
  754. }
  755. }
  756. if (exe_flag) {
  757. ctx->concur_list[level_pos + concurrency] = i;
  758. nodes_unused[i] = 0;
  759. concurrency++;
  760. ctx->concur_list_len++;
  761. }
  762. }
  763. }
  764. n_left -= concurrency;
  765. // adding a barrier different layer
  766. ctx->concur_list[level_pos + concurrency] = -1;
  767. ctx->concur_list_len++;
  768. // jump all sorted nodes at nodes_bak
  769. while (!nodes_unused[n_start]) {
  770. n_start++;
  771. }
  772. level_pos += concurrency + 1;
  773. }
  774. if (ctx->concur_list_len > GGML_MAX_CONCUR) {
  775. GGML_METAL_LOG_WARN("%s: too many elements for metal ctx->concur_list!\n", __func__);
  776. }
  777. }
  778. static bool ggml_metal_supports_op(const struct ggml_tensor * op) {
  779. switch (op->op) {
  780. case GGML_OP_UNARY:
  781. switch (ggml_get_unary_op(op)) {
  782. case GGML_UNARY_OP_TANH:
  783. case GGML_UNARY_OP_RELU:
  784. case GGML_UNARY_OP_GELU:
  785. case GGML_UNARY_OP_GELU_QUICK:
  786. case GGML_UNARY_OP_SILU:
  787. return true;
  788. default:
  789. return false;
  790. }
  791. case GGML_OP_NONE:
  792. case GGML_OP_RESHAPE:
  793. case GGML_OP_VIEW:
  794. case GGML_OP_TRANSPOSE:
  795. case GGML_OP_PERMUTE:
  796. case GGML_OP_CONCAT:
  797. case GGML_OP_ADD:
  798. case GGML_OP_ACC:
  799. case GGML_OP_MUL:
  800. case GGML_OP_DIV:
  801. case GGML_OP_SCALE:
  802. case GGML_OP_SQR:
  803. case GGML_OP_SUM_ROWS:
  804. case GGML_OP_SOFT_MAX:
  805. case GGML_OP_RMS_NORM:
  806. case GGML_OP_GROUP_NORM:
  807. case GGML_OP_NORM:
  808. case GGML_OP_ALIBI:
  809. case GGML_OP_ROPE:
  810. case GGML_OP_IM2COL:
  811. case GGML_OP_UPSCALE:
  812. case GGML_OP_PAD:
  813. case GGML_OP_ARGSORT:
  814. case GGML_OP_LEAKY_RELU:
  815. case GGML_OP_MUL_MAT:
  816. case GGML_OP_MUL_MAT_ID:
  817. return true;
  818. case GGML_OP_CPY:
  819. case GGML_OP_DUP:
  820. case GGML_OP_CONT:
  821. {
  822. switch (op->src[0]->type) {
  823. case GGML_TYPE_F32:
  824. switch (op->type) {
  825. case GGML_TYPE_F16:
  826. case GGML_TYPE_F32:
  827. case GGML_TYPE_Q8_0:
  828. case GGML_TYPE_Q4_0:
  829. case GGML_TYPE_Q4_1:
  830. return true;
  831. default:
  832. return false;
  833. }
  834. case GGML_TYPE_F16:
  835. switch (op->type) {
  836. case GGML_TYPE_F16:
  837. case GGML_TYPE_F32:
  838. return true;
  839. default:
  840. return false;
  841. }
  842. default:
  843. return false;
  844. };
  845. }
  846. case GGML_OP_DIAG_MASK_INF:
  847. case GGML_OP_GET_ROWS:
  848. {
  849. return op->ne[3] == 1;
  850. }
  851. default:
  852. return false;
  853. }
  854. }
  855. void ggml_metal_graph_compute(
  856. struct ggml_metal_context * ctx,
  857. struct ggml_cgraph * gf) {
  858. @autoreleasepool {
  859. // if there is ctx->concur_list, dispatch concurrently
  860. // else fallback to serial dispatch
  861. MTLComputePassDescriptor * edesc = MTLComputePassDescriptor.computePassDescriptor;
  862. const bool has_concur = ctx->concur_list_len && ctx->concur_list_len <= GGML_MAX_CONCUR;
  863. const int n_nodes = has_concur ? ctx->concur_list_len : gf->n_nodes;
  864. edesc.dispatchType = has_concur ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial;
  865. // create multiple command buffers and enqueue them
  866. // then, we encode the graph into the command buffers in parallel
  867. const int n_cb = ctx->n_cb;
  868. for (int i = 0; i < n_cb; ++i) {
  869. ctx->command_buffers[i] = [ctx->queue commandBuffer];
  870. // enqueue the command buffers in order to specify their execution order
  871. [ctx->command_buffers[i] enqueue];
  872. ctx->command_encoders[i] = [ctx->command_buffers[i] computeCommandEncoderWithDescriptor: edesc];
  873. }
  874. for (int cb_idx = 0; cb_idx < n_cb; ++cb_idx) {
  875. const int n_nodes_per_cb = (n_nodes + n_cb - 1) / n_cb;
  876. dispatch_async(ctx->d_queue, ^{
  877. size_t offs_src0 = 0;
  878. size_t offs_src1 = 0;
  879. size_t offs_dst = 0;
  880. id<MTLCommandBuffer> command_buffer = ctx->command_buffers[cb_idx];
  881. id<MTLComputeCommandEncoder> encoder = ctx->command_encoders[cb_idx];
  882. const int node_start = (cb_idx + 0) * n_nodes_per_cb;
  883. const int node_end = MIN((cb_idx == n_cb - 1) ? n_nodes : (cb_idx + 1) * n_nodes_per_cb, n_nodes);
  884. for (int ind = node_start; ind < node_end; ++ind) {
  885. const int i = has_concur ? ctx->concur_list[ind] : ind;
  886. if (i == -1) {
  887. [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers];
  888. continue;
  889. }
  890. //GGML_METAL_LOG_INFO("%s: encoding node %3d, op = %8s\n", __func__, i, ggml_op_name(gf->nodes[i]->op));
  891. struct ggml_tensor * src0 = gf->nodes[i]->src[0];
  892. struct ggml_tensor * src1 = gf->nodes[i]->src[1];
  893. struct ggml_tensor * dst = gf->nodes[i];
  894. switch (dst->op) {
  895. case GGML_OP_NONE:
  896. case GGML_OP_RESHAPE:
  897. case GGML_OP_VIEW:
  898. case GGML_OP_TRANSPOSE:
  899. case GGML_OP_PERMUTE:
  900. {
  901. // noop -> next node
  902. } continue;
  903. default:
  904. {
  905. } break;
  906. }
  907. if (!ggml_metal_supports_op(dst)) {
  908. GGML_METAL_LOG_ERROR("%s: error: unsupported op '%s'\n", __func__, ggml_op_desc(dst));
  909. GGML_ASSERT(!"unsupported op");
  910. }
  911. const int64_t ne00 = src0 ? src0->ne[0] : 0;
  912. const int64_t ne01 = src0 ? src0->ne[1] : 0;
  913. const int64_t ne02 = src0 ? src0->ne[2] : 0;
  914. const int64_t ne03 = src0 ? src0->ne[3] : 0;
  915. const uint64_t nb00 = src0 ? src0->nb[0] : 0;
  916. const uint64_t nb01 = src0 ? src0->nb[1] : 0;
  917. const uint64_t nb02 = src0 ? src0->nb[2] : 0;
  918. const uint64_t nb03 = src0 ? src0->nb[3] : 0;
  919. const int64_t ne10 = src1 ? src1->ne[0] : 0;
  920. const int64_t ne11 = src1 ? src1->ne[1] : 0;
  921. const int64_t ne12 = src1 ? src1->ne[2] : 0;
  922. const int64_t ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13);
  923. const uint64_t nb10 = src1 ? src1->nb[0] : 0;
  924. const uint64_t nb11 = src1 ? src1->nb[1] : 0;
  925. const uint64_t nb12 = src1 ? src1->nb[2] : 0;
  926. const uint64_t nb13 = src1 ? src1->nb[3] : 0; UNUSED(nb13);
  927. const int64_t ne0 = dst ? dst->ne[0] : 0;
  928. const int64_t ne1 = dst ? dst->ne[1] : 0;
  929. const int64_t ne2 = dst ? dst->ne[2] : 0;
  930. const int64_t ne3 = dst ? dst->ne[3] : 0;
  931. const uint64_t nb0 = dst ? dst->nb[0] : 0;
  932. const uint64_t nb1 = dst ? dst->nb[1] : 0;
  933. const uint64_t nb2 = dst ? dst->nb[2] : 0;
  934. const uint64_t nb3 = dst ? dst->nb[3] : 0;
  935. const enum ggml_type src0t = src0 ? src0->type : GGML_TYPE_COUNT;
  936. const enum ggml_type src1t = src1 ? src1->type : GGML_TYPE_COUNT;
  937. const enum ggml_type dstt = dst ? dst->type : GGML_TYPE_COUNT;
  938. id<MTLBuffer> id_src0 = src0 ? ggml_metal_get_buffer(ctx, src0, &offs_src0) : nil;
  939. id<MTLBuffer> id_src1 = src1 ? ggml_metal_get_buffer(ctx, src1, &offs_src1) : nil;
  940. id<MTLBuffer> id_dst = dst ? ggml_metal_get_buffer(ctx, dst, &offs_dst) : nil;
  941. //GGML_METAL_LOG_INFO("%s: op - %s\n", __func__, ggml_op_name(dst->op));
  942. //if (src0) {
  943. // GGML_METAL_LOG_INFO("%s: src0 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src0t), ne00, ne01, ne02,
  944. // ggml_is_contiguous(src0), src0->name);
  945. //}
  946. //if (src1) {
  947. // GGML_METAL_LOG_INFO("%s: src1 - %4s [%5lld, %5lld, %5lld], %d, %s\n", __func__, ggml_type_name(src1t), ne10, ne11, ne12,
  948. // ggml_is_contiguous(src1), src1->name);
  949. //}
  950. //if (dst) {
  951. // GGML_METAL_LOG_INFO("%s: dst - %4s [%5lld, %5lld, %5lld], 1, %s\n", __func__, ggml_type_name(dstt), ne0, ne1, ne2,
  952. // dst->name);
  953. //}
  954. switch (dst->op) {
  955. case GGML_OP_CONCAT:
  956. {
  957. const int64_t nb = ne00;
  958. [encoder setComputePipelineState:ctx->pipeline_concat];
  959. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  960. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  961. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  962. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  963. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  964. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  965. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  966. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  967. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  968. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  969. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  970. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  971. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  972. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  973. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  974. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  975. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  976. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  977. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  978. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  979. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  980. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  981. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  982. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  983. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  984. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  985. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  986. [encoder setBytes:&nb length:sizeof(nb) atIndex:27];
  987. const int nth = MIN(1024, ne0);
  988. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  989. } break;
  990. case GGML_OP_ADD:
  991. case GGML_OP_MUL:
  992. case GGML_OP_DIV:
  993. {
  994. const size_t offs = 0;
  995. bool bcast_row = false;
  996. int64_t nb = ne00;
  997. id<MTLComputePipelineState> pipeline = nil;
  998. if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) {
  999. GGML_ASSERT(ggml_is_contiguous(src0));
  1000. // src1 is a row
  1001. GGML_ASSERT(ne11 == 1);
  1002. nb = ne00 / 4;
  1003. switch (dst->op) {
  1004. case GGML_OP_ADD: pipeline = ctx->pipeline_add_row; break;
  1005. case GGML_OP_MUL: pipeline = ctx->pipeline_mul_row; break;
  1006. case GGML_OP_DIV: pipeline = ctx->pipeline_div_row; break;
  1007. default: GGML_ASSERT(false);
  1008. }
  1009. bcast_row = true;
  1010. } else {
  1011. switch (dst->op) {
  1012. case GGML_OP_ADD: pipeline = ctx->pipeline_add; break;
  1013. case GGML_OP_MUL: pipeline = ctx->pipeline_mul; break;
  1014. case GGML_OP_DIV: pipeline = ctx->pipeline_div; break;
  1015. default: GGML_ASSERT(false);
  1016. }
  1017. }
  1018. [encoder setComputePipelineState:pipeline];
  1019. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1020. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1021. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1022. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1023. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1024. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1025. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  1026. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  1027. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:8];
  1028. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:9];
  1029. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:10];
  1030. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  1031. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  1032. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  1033. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  1034. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  1035. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  1036. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  1037. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  1038. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  1039. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  1040. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  1041. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  1042. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  1043. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:24];
  1044. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:25];
  1045. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:26];
  1046. [encoder setBytes:&offs length:sizeof(offs) atIndex:27];
  1047. [encoder setBytes:&nb length:sizeof(nb) atIndex:28];
  1048. if (bcast_row) {
  1049. const int64_t n = ggml_nelements(dst)/4;
  1050. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1051. } else {
  1052. const int nth = MIN((int) pipeline.maxTotalThreadsPerThreadgroup, ne0);
  1053. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1054. }
  1055. } break;
  1056. case GGML_OP_ACC:
  1057. {
  1058. GGML_ASSERT(src0t == GGML_TYPE_F32);
  1059. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1060. GGML_ASSERT(dstt == GGML_TYPE_F32);
  1061. GGML_ASSERT(ggml_is_contiguous(src0));
  1062. GGML_ASSERT(ggml_is_contiguous(src1));
  1063. const size_t pnb1 = ((int32_t *) dst->op_params)[0];
  1064. const size_t pnb2 = ((int32_t *) dst->op_params)[1];
  1065. const size_t pnb3 = ((int32_t *) dst->op_params)[2];
  1066. const size_t offs = ((int32_t *) dst->op_params)[3];
  1067. const bool inplace = (bool) ((int32_t *) dst->op_params)[4];
  1068. if (!inplace) {
  1069. // run a separete kernel to cpy src->dst
  1070. // not sure how to avoid this
  1071. // TODO: make a simpler cpy_bytes kernel
  1072. const int nth = MIN(1024, ne00);
  1073. [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32];
  1074. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1075. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1076. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1077. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1078. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1079. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1080. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1081. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1082. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1083. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1084. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1085. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1086. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1087. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1088. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1089. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1090. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1091. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1092. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1093. }
  1094. [encoder setComputePipelineState:ctx->pipeline_add];
  1095. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1096. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1097. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1098. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1099. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1100. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1101. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:6];
  1102. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:7];
  1103. [encoder setBytes:&pnb1 length:sizeof(pnb1) atIndex:8];
  1104. [encoder setBytes:&pnb2 length:sizeof(pnb2) atIndex:9];
  1105. [encoder setBytes:&pnb3 length:sizeof(pnb3) atIndex:10];
  1106. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:11];
  1107. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:12];
  1108. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:13];
  1109. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:14];
  1110. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:15];
  1111. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:16];
  1112. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:17];
  1113. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:18];
  1114. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:19];
  1115. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:20];
  1116. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:21];
  1117. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:22];
  1118. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:23];
  1119. [encoder setBytes:&pnb1 length:sizeof(pnb1) atIndex:24];
  1120. [encoder setBytes:&pnb2 length:sizeof(pnb2) atIndex:25];
  1121. [encoder setBytes:&pnb3 length:sizeof(pnb3) atIndex:26];
  1122. [encoder setBytes:&offs length:sizeof(offs) atIndex:27];
  1123. const int nth = MIN(1024, ne0);
  1124. [encoder dispatchThreadgroups:MTLSizeMake(ne11, ne12, ne13) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1125. } break;
  1126. case GGML_OP_SCALE:
  1127. {
  1128. GGML_ASSERT(ggml_is_contiguous(src0));
  1129. const float scale = *(const float *) src1->data;
  1130. int64_t n = ggml_nelements(dst);
  1131. if (n % 4 == 0) {
  1132. n /= 4;
  1133. [encoder setComputePipelineState:ctx->pipeline_scale_4];
  1134. } else {
  1135. [encoder setComputePipelineState:ctx->pipeline_scale];
  1136. }
  1137. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1138. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1139. [encoder setBytes:&scale length:sizeof(scale) atIndex:2];
  1140. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1141. } break;
  1142. case GGML_OP_UNARY:
  1143. switch (ggml_get_unary_op(gf->nodes[i])) {
  1144. case GGML_UNARY_OP_TANH:
  1145. {
  1146. [encoder setComputePipelineState:ctx->pipeline_tanh];
  1147. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1148. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1149. const int64_t n = ggml_nelements(dst);
  1150. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1151. } break;
  1152. case GGML_UNARY_OP_RELU:
  1153. {
  1154. [encoder setComputePipelineState:ctx->pipeline_relu];
  1155. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1156. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1157. const int64_t n = ggml_nelements(dst);
  1158. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1159. } break;
  1160. case GGML_UNARY_OP_GELU:
  1161. {
  1162. [encoder setComputePipelineState:ctx->pipeline_gelu];
  1163. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1164. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1165. const int64_t n = ggml_nelements(dst);
  1166. GGML_ASSERT(n % 4 == 0);
  1167. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1168. } break;
  1169. case GGML_UNARY_OP_GELU_QUICK:
  1170. {
  1171. [encoder setComputePipelineState:ctx->pipeline_gelu_quick];
  1172. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1173. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1174. const int64_t n = ggml_nelements(dst);
  1175. GGML_ASSERT(n % 4 == 0);
  1176. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1177. } break;
  1178. case GGML_UNARY_OP_SILU:
  1179. {
  1180. [encoder setComputePipelineState:ctx->pipeline_silu];
  1181. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1182. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1183. const int64_t n = ggml_nelements(dst);
  1184. GGML_ASSERT(n % 4 == 0);
  1185. [encoder dispatchThreadgroups:MTLSizeMake(n/4, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1186. } break;
  1187. default:
  1188. {
  1189. GGML_METAL_LOG_WARN("%s: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  1190. GGML_ASSERT(false);
  1191. }
  1192. } break;
  1193. case GGML_OP_SQR:
  1194. {
  1195. GGML_ASSERT(ggml_is_contiguous(src0));
  1196. [encoder setComputePipelineState:ctx->pipeline_sqr];
  1197. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1198. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1199. const int64_t n = ggml_nelements(dst);
  1200. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1201. } break;
  1202. case GGML_OP_SUM_ROWS:
  1203. {
  1204. GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type));
  1205. [encoder setComputePipelineState:ctx->pipeline_sum_rows];
  1206. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1207. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1208. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1209. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1210. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1211. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1212. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1213. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1214. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1215. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1216. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:10];
  1217. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:11];
  1218. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:12];
  1219. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:13];
  1220. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:14];
  1221. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:15];
  1222. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:16];
  1223. [encoder setBytes:&nb13 length:sizeof(nb13) atIndex:17];
  1224. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:18];
  1225. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:19];
  1226. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:20];
  1227. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:21];
  1228. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:22];
  1229. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:23];
  1230. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:24];
  1231. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:25];
  1232. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1233. } break;
  1234. case GGML_OP_SOFT_MAX:
  1235. {
  1236. int nth = 32; // SIMD width
  1237. if (ne00%4 == 0) {
  1238. while (nth < ne00/4 && nth < 256) {
  1239. nth *= 2;
  1240. }
  1241. [encoder setComputePipelineState:ctx->pipeline_soft_max_4];
  1242. } else {
  1243. while (nth < ne00 && nth < 1024) {
  1244. nth *= 2;
  1245. }
  1246. [encoder setComputePipelineState:ctx->pipeline_soft_max];
  1247. }
  1248. const float scale = ((float *) dst->op_params)[0];
  1249. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1250. if (id_src1) {
  1251. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1252. } else {
  1253. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:1];
  1254. }
  1255. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1256. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1257. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1258. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1259. [encoder setBytes:&scale length:sizeof(scale) atIndex:6];
  1260. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1261. [encoder dispatchThreadgroups:MTLSizeMake(ne01*ne02*ne03, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1262. } break;
  1263. case GGML_OP_DIAG_MASK_INF:
  1264. {
  1265. const int n_past = ((int32_t *)(dst->op_params))[0];
  1266. if (ne00%8 == 0) {
  1267. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf_8];
  1268. } else {
  1269. [encoder setComputePipelineState:ctx->pipeline_diag_mask_inf];
  1270. }
  1271. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1272. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1273. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1274. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1275. [encoder setBytes:&n_past length:sizeof(int) atIndex:4];
  1276. if (ne00%8 == 0) {
  1277. [encoder dispatchThreadgroups:MTLSizeMake(ne00*ne01*ne02/8, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1278. }
  1279. else {
  1280. [encoder dispatchThreadgroups:MTLSizeMake(ne00, ne01, ne02) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  1281. }
  1282. } break;
  1283. case GGML_OP_MUL_MAT:
  1284. {
  1285. GGML_ASSERT(ne00 == ne10);
  1286. // TODO: assert that dim2 and dim3 are contiguous
  1287. GGML_ASSERT(ne12 % ne02 == 0);
  1288. GGML_ASSERT(ne13 % ne03 == 0);
  1289. const uint r2 = ne12/ne02;
  1290. const uint r3 = ne13/ne03;
  1291. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  1292. // to the matrix-vector kernel
  1293. int ne11_mm_min = 1;
  1294. #if 0
  1295. // the numbers below are measured on M2 Ultra for 7B and 13B models
  1296. // these numbers do not translate to other devices or model sizes
  1297. // TODO: need to find a better approach
  1298. if ([ctx->device.name isEqualToString:@"Apple M2 Ultra"]) {
  1299. switch (src0t) {
  1300. case GGML_TYPE_F16: ne11_mm_min = 2; break;
  1301. case GGML_TYPE_Q8_0: ne11_mm_min = 7; break;
  1302. case GGML_TYPE_Q2_K: ne11_mm_min = 15; break;
  1303. case GGML_TYPE_Q3_K: ne11_mm_min = 7; break;
  1304. case GGML_TYPE_Q4_0:
  1305. case GGML_TYPE_Q4_1: ne11_mm_min = 15; break;
  1306. case GGML_TYPE_Q4_K: ne11_mm_min = 11; break;
  1307. case GGML_TYPE_Q5_0: // not tested yet
  1308. case GGML_TYPE_Q5_1: ne11_mm_min = 13; break; // not tested yet
  1309. case GGML_TYPE_Q5_K: ne11_mm_min = 7; break;
  1310. case GGML_TYPE_Q6_K: ne11_mm_min = 7; break;
  1311. default: ne11_mm_min = 1; break;
  1312. }
  1313. }
  1314. #endif
  1315. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  1316. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  1317. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] &&
  1318. !ggml_is_transposed(src0) &&
  1319. !ggml_is_transposed(src1) &&
  1320. src1t == GGML_TYPE_F32 &&
  1321. ne00 % 32 == 0 && ne00 >= 64 &&
  1322. (ne11 > ne11_mm_min || (ggml_is_quantized(src0t) && ne12 > 1))) {
  1323. //printf("matrix: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1324. switch (src0->type) {
  1325. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f32_f32]; break;
  1326. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_f16_f32]; break;
  1327. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_0_f32]; break;
  1328. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_1_f32]; break;
  1329. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_0_f32]; break;
  1330. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_1_f32]; break;
  1331. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q8_0_f32]; break;
  1332. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q2_K_f32]; break;
  1333. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q3_K_f32]; break;
  1334. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q4_K_f32]; break;
  1335. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q5_K_f32]; break;
  1336. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_q6_K_f32]; break;
  1337. default: GGML_ASSERT(false && "MUL MAT-MAT not implemented");
  1338. }
  1339. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1340. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1341. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1342. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1343. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1344. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:5];
  1345. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:6];
  1346. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:7];
  1347. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:8];
  1348. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:9];
  1349. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:10];
  1350. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:11];
  1351. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:12];
  1352. [encoder setBytes:&r2 length:sizeof(r2) atIndex:13];
  1353. [encoder setBytes:&r3 length:sizeof(r3) atIndex:14];
  1354. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  1355. [encoder dispatchThreadgroups:MTLSizeMake( (ne11 + 31)/32, (ne01 + 63)/64, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  1356. } else {
  1357. int nth0 = 32;
  1358. int nth1 = 1;
  1359. int nrows = 1;
  1360. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1361. // use custom matrix x vector kernel
  1362. switch (src0t) {
  1363. case GGML_TYPE_F32:
  1364. {
  1365. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1366. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f32_f32];
  1367. nrows = 4;
  1368. } break;
  1369. case GGML_TYPE_F16:
  1370. {
  1371. nth0 = 32;
  1372. nth1 = 1;
  1373. if (src1t == GGML_TYPE_F32) {
  1374. if (ne11 * ne12 < 4) {
  1375. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_1row];
  1376. } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) {
  1377. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32_l4];
  1378. nrows = ne11;
  1379. } else {
  1380. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f32];
  1381. nrows = 4;
  1382. }
  1383. } else {
  1384. [encoder setComputePipelineState:ctx->pipeline_mul_mv_f16_f16];
  1385. nrows = 4;
  1386. }
  1387. } break;
  1388. case GGML_TYPE_Q4_0:
  1389. {
  1390. nth0 = 8;
  1391. nth1 = 8;
  1392. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_0_f32];
  1393. } break;
  1394. case GGML_TYPE_Q4_1:
  1395. {
  1396. nth0 = 8;
  1397. nth1 = 8;
  1398. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_1_f32];
  1399. } break;
  1400. case GGML_TYPE_Q5_0:
  1401. {
  1402. nth0 = 8;
  1403. nth1 = 8;
  1404. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_0_f32];
  1405. } break;
  1406. case GGML_TYPE_Q5_1:
  1407. {
  1408. nth0 = 8;
  1409. nth1 = 8;
  1410. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_1_f32];
  1411. } break;
  1412. case GGML_TYPE_Q8_0:
  1413. {
  1414. nth0 = 8;
  1415. nth1 = 8;
  1416. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q8_0_f32];
  1417. } break;
  1418. case GGML_TYPE_Q2_K:
  1419. {
  1420. nth0 = 2;
  1421. nth1 = 32;
  1422. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q2_K_f32];
  1423. } break;
  1424. case GGML_TYPE_Q3_K:
  1425. {
  1426. nth0 = 2;
  1427. nth1 = 32;
  1428. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q3_K_f32];
  1429. } break;
  1430. case GGML_TYPE_Q4_K:
  1431. {
  1432. nth0 = 4; //1;
  1433. nth1 = 8; //32;
  1434. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q4_K_f32];
  1435. } break;
  1436. case GGML_TYPE_Q5_K:
  1437. {
  1438. nth0 = 2;
  1439. nth1 = 32;
  1440. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q5_K_f32];
  1441. } break;
  1442. case GGML_TYPE_Q6_K:
  1443. {
  1444. nth0 = 2;
  1445. nth1 = 32;
  1446. [encoder setComputePipelineState:ctx->pipeline_mul_mv_q6_K_f32];
  1447. } break;
  1448. default:
  1449. {
  1450. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  1451. GGML_ASSERT(false && "not implemented");
  1452. }
  1453. };
  1454. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1455. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1456. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1457. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:3];
  1458. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:4];
  1459. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:5];
  1460. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1461. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1462. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1463. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:9];
  1464. [encoder setBytes:&ne11 length:sizeof(ne11) atIndex:10];
  1465. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:11];
  1466. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:12];
  1467. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:13];
  1468. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:14];
  1469. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:15];
  1470. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:16];
  1471. [encoder setBytes:&r2 length:sizeof(r2) atIndex:17];
  1472. [encoder setBytes:&r3 length:sizeof(r3) atIndex:18];
  1473. if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q4_1 ||
  1474. src0t == GGML_TYPE_Q5_0 || src0t == GGML_TYPE_Q5_1 || src0t == GGML_TYPE_Q8_0 ||
  1475. src0t == GGML_TYPE_Q2_K) { // || src0t == GGML_TYPE_Q4_K) {
  1476. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 7)/8, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1477. }
  1478. else if (src0t == GGML_TYPE_Q4_K) {
  1479. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1480. }
  1481. else if (src0t == GGML_TYPE_Q3_K) {
  1482. #ifdef GGML_QKK_64
  1483. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1484. #else
  1485. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1486. #endif
  1487. }
  1488. else if (src0t == GGML_TYPE_Q5_K) {
  1489. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 3)/4, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1490. }
  1491. else if (src0t == GGML_TYPE_Q6_K) {
  1492. [encoder dispatchThreadgroups:MTLSizeMake((ne01 + 1)/2, ne11, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1493. } else {
  1494. const int64_t ny = (ne11 + nrows - 1)/nrows;
  1495. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ny, ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1496. }
  1497. }
  1498. } break;
  1499. case GGML_OP_MUL_MAT_ID:
  1500. {
  1501. //GGML_ASSERT(ne00 == ne10);
  1502. //GGML_ASSERT(ne03 == ne13);
  1503. GGML_ASSERT(src0t == GGML_TYPE_I32);
  1504. const int n_as = ((int32_t *) dst->op_params)[1];
  1505. // TODO: make this more general
  1506. GGML_ASSERT(n_as <= 8);
  1507. struct ggml_tensor * src2 = gf->nodes[i]->src[2];
  1508. const int64_t ne20 = src2 ? src2->ne[0] : 0;
  1509. const int64_t ne21 = src2 ? src2->ne[1] : 0;
  1510. const int64_t ne22 = src2 ? src2->ne[2] : 0;
  1511. const int64_t ne23 = src2 ? src2->ne[3] : 0; GGML_UNUSED(ne23);
  1512. const uint64_t nb20 = src2 ? src2->nb[0] : 0; GGML_UNUSED(nb20);
  1513. const uint64_t nb21 = src2 ? src2->nb[1] : 0;
  1514. const uint64_t nb22 = src2 ? src2->nb[2] : 0;
  1515. const uint64_t nb23 = src2 ? src2->nb[3] : 0; GGML_UNUSED(nb23);
  1516. const enum ggml_type src2t = src2 ? src2->type : GGML_TYPE_COUNT; GGML_UNUSED(src2t);
  1517. GGML_ASSERT(!ggml_is_transposed(src2));
  1518. GGML_ASSERT(!ggml_is_transposed(src1));
  1519. GGML_ASSERT(ne20 % 32 == 0);
  1520. // !!!!!!!!! TODO: this assert is probably required but not sure!
  1521. //GGML_ASSERT(ne20 >= 64);
  1522. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1523. const uint r2 = ne12/ne22;
  1524. const uint r3 = ne13/ne23;
  1525. // find the break-even point where the matrix-matrix kernel becomes more efficient compared
  1526. // to the matrix-vector kernel
  1527. int ne11_mm_min = 1;
  1528. const int idx = ((int32_t *) dst->op_params)[0];
  1529. // batch size
  1530. GGML_ASSERT(ne01 == ne11);
  1531. const int64_t _ne1 = 1; // kernel_mul_mm_impl needs a reference in constant memory
  1532. // for now the matrix-matrix multiplication kernel only works on A14+/M1+ SoCs
  1533. // AMD GPU and older A-chips will reuse matrix-vector multiplication kernel
  1534. // !!!
  1535. // TODO: for now, always use mat-vec kernels until we figure out how to improve the
  1536. // indirect matrix multiplication
  1537. // !!!
  1538. if ([ctx->device supportsFamily:MTLGPUFamilyApple7] && _ne1 > ne11_mm_min) {
  1539. switch (src2->type) {
  1540. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_f32_f32]; break;
  1541. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_f16_f32]; break;
  1542. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q4_0_f32]; break;
  1543. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q4_1_f32]; break;
  1544. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q5_0_f32]; break;
  1545. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q5_1_f32]; break;
  1546. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q8_0_f32]; break;
  1547. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q2_K_f32]; break;
  1548. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q3_K_f32]; break;
  1549. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q4_K_f32]; break;
  1550. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q5_K_f32]; break;
  1551. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_mul_mm_id_q6_K_f32]; break;
  1552. default: GGML_ASSERT(false && "MUL_MAT_ID not implemented");
  1553. }
  1554. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1555. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1556. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1557. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:3];
  1558. [encoder setBytes:&ne20 length:sizeof(ne20) atIndex:4];
  1559. [encoder setBytes:&ne22 length:sizeof(ne22) atIndex:5];
  1560. [encoder setBytes:&nb21 length:sizeof(nb21) atIndex:6];
  1561. [encoder setBytes:&nb22 length:sizeof(nb22) atIndex:7];
  1562. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:8];
  1563. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:9];
  1564. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:10];
  1565. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:11];
  1566. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:12];
  1567. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:13];
  1568. [encoder setBytes:&_ne1 length:sizeof(_ne1) atIndex:14];
  1569. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1570. [encoder setBytes:&r2 length:sizeof(r2) atIndex:16];
  1571. [encoder setBytes:&r3 length:sizeof(r3) atIndex:17];
  1572. [encoder setBytes:&idx length:sizeof(idx) atIndex:18];
  1573. // TODO: how to make this an array? read Metal docs
  1574. for (int j = 0; j < n_as; ++j) {
  1575. struct ggml_tensor * src_cur = dst->src[2 + j];
  1576. size_t offs_src_cur = 0;
  1577. id<MTLBuffer> id_src_cur = ggml_metal_get_buffer(ctx, src_cur, &offs_src_cur);
  1578. [encoder setBuffer:id_src_cur offset:offs_src_cur atIndex:19 + j];
  1579. }
  1580. [encoder setThreadgroupMemoryLength:8192 atIndex:0];
  1581. // TODO: processing one row at a time (ne11 -> 1) is not efficient
  1582. [encoder dispatchThreadgroups:MTLSizeMake( (_ne1 + 31)/32, (ne21 + 63)/64, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(128, 1, 1)];
  1583. } else {
  1584. int nth0 = 32;
  1585. int nth1 = 1;
  1586. int nrows = 1;
  1587. //printf("vector: ne00 = %6d, ne01 = %6d, ne02 = %6d, ne11 = %6d, ne12 = %6d\n", ne00, ne01, ne02, ne11, ne12);
  1588. // use custom matrix x vector kernel
  1589. switch (src2t) {
  1590. case GGML_TYPE_F32:
  1591. {
  1592. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1593. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_f32_f32];
  1594. } break;
  1595. case GGML_TYPE_F16:
  1596. {
  1597. GGML_ASSERT(src1t == GGML_TYPE_F32);
  1598. nth0 = 32;
  1599. nth1 = 1;
  1600. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_f16_f32];
  1601. } break;
  1602. case GGML_TYPE_Q4_0:
  1603. {
  1604. nth0 = 8;
  1605. nth1 = 8;
  1606. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q4_0_f32];
  1607. } break;
  1608. case GGML_TYPE_Q4_1:
  1609. {
  1610. nth0 = 8;
  1611. nth1 = 8;
  1612. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q4_1_f32];
  1613. } break;
  1614. case GGML_TYPE_Q5_0:
  1615. {
  1616. nth0 = 8;
  1617. nth1 = 8;
  1618. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q5_0_f32];
  1619. } break;
  1620. case GGML_TYPE_Q5_1:
  1621. {
  1622. nth0 = 8;
  1623. nth1 = 8;
  1624. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q5_1_f32];
  1625. } break;
  1626. case GGML_TYPE_Q8_0:
  1627. {
  1628. nth0 = 8;
  1629. nth1 = 8;
  1630. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q8_0_f32];
  1631. } break;
  1632. case GGML_TYPE_Q2_K:
  1633. {
  1634. nth0 = 2;
  1635. nth1 = 32;
  1636. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q2_K_f32];
  1637. } break;
  1638. case GGML_TYPE_Q3_K:
  1639. {
  1640. nth0 = 2;
  1641. nth1 = 32;
  1642. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q3_K_f32];
  1643. } break;
  1644. case GGML_TYPE_Q4_K:
  1645. {
  1646. nth0 = 4; //1;
  1647. nth1 = 8; //32;
  1648. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q4_K_f32];
  1649. } break;
  1650. case GGML_TYPE_Q5_K:
  1651. {
  1652. nth0 = 2;
  1653. nth1 = 32;
  1654. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q5_K_f32];
  1655. } break;
  1656. case GGML_TYPE_Q6_K:
  1657. {
  1658. nth0 = 2;
  1659. nth1 = 32;
  1660. [encoder setComputePipelineState:ctx->pipeline_mul_mv_id_q6_K_f32];
  1661. } break;
  1662. default:
  1663. {
  1664. GGML_METAL_LOG_ERROR("Asserting on type %d\n", (int)src0t);
  1665. GGML_ASSERT(false && "not implemented");
  1666. }
  1667. };
  1668. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1669. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1670. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1671. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:3];
  1672. [encoder setBytes:&ne20 length:sizeof(ne20) atIndex:4];
  1673. [encoder setBytes:&ne21 length:sizeof(ne21) atIndex:5];
  1674. [encoder setBytes:&ne22 length:sizeof(ne22) atIndex:6];
  1675. [encoder setBytes:&nb20 length:sizeof(nb20) atIndex:7];
  1676. [encoder setBytes:&nb21 length:sizeof(nb21) atIndex:8];
  1677. [encoder setBytes:&nb22 length:sizeof(nb22) atIndex:9];
  1678. [encoder setBytes:&ne10 length:sizeof(ne10) atIndex:10];
  1679. [encoder setBytes:&_ne1 length:sizeof(_ne1) atIndex:11];
  1680. [encoder setBytes:&ne12 length:sizeof(ne12) atIndex:12];
  1681. [encoder setBytes:&ne13 length:sizeof(ne13) atIndex:13];
  1682. [encoder setBytes:&nb10 length:sizeof(nb10) atIndex:14];
  1683. [encoder setBytes:&nb11 length:sizeof(nb11) atIndex:15];
  1684. [encoder setBytes:&nb12 length:sizeof(nb12) atIndex:16];
  1685. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:17];
  1686. [encoder setBytes:&_ne1 length:sizeof(_ne1) atIndex:18];
  1687. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:19];
  1688. [encoder setBytes:&r2 length:sizeof(r2) atIndex:20];
  1689. [encoder setBytes:&r3 length:sizeof(r3) atIndex:21];
  1690. [encoder setBytes:&idx length:sizeof(idx) atIndex:22];
  1691. // TODO: how to make this an array? read Metal docs
  1692. for (int j = 0; j < n_as; ++j) {
  1693. struct ggml_tensor * src_cur = dst->src[2 + j];
  1694. size_t offs_src_cur = 0;
  1695. id<MTLBuffer> id_src_cur = ggml_metal_get_buffer(ctx, src_cur, &offs_src_cur);
  1696. [encoder setBuffer:id_src_cur offset:offs_src_cur atIndex:23 + j];
  1697. }
  1698. if (src2t == GGML_TYPE_Q4_0 || src2t == GGML_TYPE_Q4_1 ||
  1699. src2t == GGML_TYPE_Q5_0 || src2t == GGML_TYPE_Q5_1 || src2t == GGML_TYPE_Q8_0 ||
  1700. src2t == GGML_TYPE_Q2_K) { // || src2t == GGML_TYPE_Q4_K) {
  1701. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 7)/8, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1702. }
  1703. else if (src2t == GGML_TYPE_Q4_K) {
  1704. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1705. }
  1706. else if (src2t == GGML_TYPE_Q3_K) {
  1707. #ifdef GGML_QKK_64
  1708. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 1)/2, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1709. #else
  1710. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1711. #endif
  1712. }
  1713. else if (src2t == GGML_TYPE_Q5_K) {
  1714. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 3)/4, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1715. }
  1716. else if (src2t == GGML_TYPE_Q6_K) {
  1717. [encoder dispatchThreadgroups:MTLSizeMake((ne21 + 1)/2, _ne1, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1718. } else {
  1719. const int64_t ny = (_ne1 + nrows - 1)/nrows;
  1720. [encoder dispatchThreadgroups:MTLSizeMake(ne21, ny, ne01*ne12*ne13) threadsPerThreadgroup:MTLSizeMake(nth0, nth1, 1)];
  1721. }
  1722. }
  1723. } break;
  1724. case GGML_OP_GET_ROWS:
  1725. {
  1726. switch (src0->type) {
  1727. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_get_rows_f32]; break;
  1728. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_get_rows_f16]; break;
  1729. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_0]; break;
  1730. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_1]; break;
  1731. case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_0]; break;
  1732. case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_1]; break;
  1733. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_get_rows_q8_0]; break;
  1734. case GGML_TYPE_Q2_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q2_K]; break;
  1735. case GGML_TYPE_Q3_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q3_K]; break;
  1736. case GGML_TYPE_Q4_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q4_K]; break;
  1737. case GGML_TYPE_Q5_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q5_K]; break;
  1738. case GGML_TYPE_Q6_K: [encoder setComputePipelineState:ctx->pipeline_get_rows_q6_K]; break;
  1739. default: GGML_ASSERT(false && "not implemented");
  1740. }
  1741. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1742. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1743. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1744. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1745. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:4];
  1746. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:5];
  1747. [encoder setBytes:&ne10 length:sizeof( int64_t) atIndex:6];
  1748. [encoder setBytes:&nb10 length:sizeof( int64_t) atIndex:7];
  1749. [encoder setBytes:&nb11 length:sizeof( int64_t) atIndex:8];
  1750. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:9];
  1751. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:10];
  1752. [encoder dispatchThreadgroups:MTLSizeMake(ne10, ne11, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
  1753. } break;
  1754. case GGML_OP_RMS_NORM:
  1755. {
  1756. GGML_ASSERT(ne00 % 4 == 0);
  1757. float eps;
  1758. memcpy(&eps, dst->op_params, sizeof(float));
  1759. int nth = 32; // SIMD width
  1760. while (nth < ne00/4 && nth < 1024) {
  1761. nth *= 2;
  1762. }
  1763. [encoder setComputePipelineState:ctx->pipeline_rms_norm];
  1764. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1765. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1766. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1767. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1768. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1769. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1770. const int64_t nrows = ggml_nrows(src0);
  1771. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1772. } break;
  1773. case GGML_OP_GROUP_NORM:
  1774. {
  1775. GGML_ASSERT(ne00 % 4 == 0);
  1776. //float eps;
  1777. //memcpy(&eps, dst->op_params, sizeof(float));
  1778. const float eps = 1e-6f; // TODO: temporarily hardcoded
  1779. const int32_t n_groups = ((int32_t *) dst->op_params)[0];
  1780. int nth = 32; // SIMD width
  1781. //while (nth < ne00/4 && nth < 1024) {
  1782. // nth *= 2;
  1783. //}
  1784. [encoder setComputePipelineState:ctx->pipeline_group_norm];
  1785. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1786. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1787. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1788. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1789. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1790. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:5];
  1791. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:6];
  1792. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:7];
  1793. [encoder setBytes:&n_groups length:sizeof( int32_t) atIndex:8];
  1794. [encoder setBytes:&eps length:sizeof( float) atIndex:9];
  1795. [encoder setThreadgroupMemoryLength:32*sizeof(float) atIndex:0];
  1796. [encoder dispatchThreadgroups:MTLSizeMake(n_groups, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1797. } break;
  1798. case GGML_OP_NORM:
  1799. {
  1800. float eps;
  1801. memcpy(&eps, dst->op_params, sizeof(float));
  1802. const int nth = MIN(256, ne00);
  1803. [encoder setComputePipelineState:ctx->pipeline_norm];
  1804. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1805. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1806. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1807. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:3];
  1808. [encoder setBytes:&eps length:sizeof( float) atIndex:4];
  1809. [encoder setThreadgroupMemoryLength:GGML_PAD(nth*sizeof(float), 16) atIndex:0];
  1810. const int64_t nrows = ggml_nrows(src0);
  1811. [encoder dispatchThreadgroups:MTLSizeMake(nrows, 1, 1) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1812. } break;
  1813. case GGML_OP_ALIBI:
  1814. {
  1815. GGML_ASSERT((src0t == GGML_TYPE_F32));
  1816. const int nth = MIN(1024, ne00);
  1817. //const int n_past = ((int32_t *) dst->op_params)[0];
  1818. const int n_head = ((int32_t *) dst->op_params)[1];
  1819. float max_bias;
  1820. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  1821. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  1822. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  1823. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  1824. [encoder setComputePipelineState:ctx->pipeline_alibi_f32];
  1825. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1826. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1827. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  1828. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  1829. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  1830. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  1831. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  1832. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  1833. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  1834. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  1835. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  1836. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  1837. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  1838. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  1839. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  1840. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  1841. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  1842. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  1843. [encoder setBytes:&m0 length:sizeof( float) atIndex:18];
  1844. [encoder setBytes:&m1 length:sizeof( float) atIndex:19];
  1845. [encoder setBytes:&n_heads_log2_floor length:sizeof(int) atIndex:20];
  1846. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1847. } break;
  1848. case GGML_OP_ROPE:
  1849. {
  1850. GGML_ASSERT(ne10 == ne02);
  1851. const int nth = MIN(1024, ne00);
  1852. const int n_past = ((int32_t *) dst->op_params)[0];
  1853. const int n_dims = ((int32_t *) dst->op_params)[1];
  1854. const int mode = ((int32_t *) dst->op_params)[2];
  1855. // skip 3, n_ctx, used in GLM RoPE, unimplemented in metal
  1856. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  1857. float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
  1858. memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float));
  1859. memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float));
  1860. memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float));
  1861. memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float));
  1862. memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float));
  1863. memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float));
  1864. switch (src0->type) {
  1865. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_rope_f32]; break;
  1866. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_rope_f16]; break;
  1867. default: GGML_ASSERT(false);
  1868. };
  1869. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1870. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:1];
  1871. [encoder setBuffer:id_dst offset:offs_dst atIndex:2];
  1872. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:3];
  1873. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:4];
  1874. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:5];
  1875. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:6];
  1876. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:7];
  1877. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:8];
  1878. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:9];
  1879. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:10];
  1880. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:11];
  1881. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:12];
  1882. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:13];
  1883. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:14];
  1884. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:15];
  1885. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:16];
  1886. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:17];
  1887. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:18];
  1888. [encoder setBytes:&n_past length:sizeof( int) atIndex:19];
  1889. [encoder setBytes:&n_dims length:sizeof( int) atIndex:20];
  1890. [encoder setBytes:&mode length:sizeof( int) atIndex:21];
  1891. [encoder setBytes:&n_orig_ctx length:sizeof( int) atIndex:22];
  1892. [encoder setBytes:&freq_base length:sizeof( float) atIndex:23];
  1893. [encoder setBytes:&freq_scale length:sizeof( float) atIndex:24];
  1894. [encoder setBytes:&ext_factor length:sizeof( float) atIndex:25];
  1895. [encoder setBytes:&attn_factor length:sizeof( float) atIndex:26];
  1896. [encoder setBytes:&beta_fast length:sizeof( float) atIndex:27];
  1897. [encoder setBytes:&beta_slow length:sizeof( float) atIndex:28];
  1898. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1899. } break;
  1900. case GGML_OP_IM2COL:
  1901. {
  1902. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  1903. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  1904. GGML_ASSERT( dst->type == GGML_TYPE_F16);
  1905. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  1906. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  1907. const int32_t p0 = ((const int32_t *)(dst->op_params))[2];
  1908. const int32_t p1 = ((const int32_t *)(dst->op_params))[3];
  1909. const int32_t d0 = ((const int32_t *)(dst->op_params))[4];
  1910. const int32_t d1 = ((const int32_t *)(dst->op_params))[5];
  1911. const bool is_2D = ((const int32_t *)(dst->op_params))[6] == 1;
  1912. const int32_t N = src1->ne[is_2D ? 3 : 2];
  1913. const int32_t IC = src1->ne[is_2D ? 2 : 1];
  1914. const int32_t IH = is_2D ? src1->ne[1] : 1;
  1915. const int32_t IW = src1->ne[0];
  1916. const int32_t KH = is_2D ? src0->ne[1] : 1;
  1917. const int32_t KW = src0->ne[0];
  1918. const int32_t OH = is_2D ? dst->ne[2] : 1;
  1919. const int32_t OW = dst->ne[1];
  1920. const int32_t CHW = IC * KH * KW;
  1921. const int32_t ofs0 = src1->nb[is_2D ? 3 : 2] / 4;
  1922. const int32_t ofs1 = src1->nb[is_2D ? 2 : 1] / 4;
  1923. switch (src0->type) {
  1924. case GGML_TYPE_F32: GGML_ASSERT(false && "not implemented"); break;
  1925. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_im2col_f16]; break;
  1926. default: GGML_ASSERT(false);
  1927. };
  1928. [encoder setBuffer:id_src1 offset:offs_src1 atIndex:0];
  1929. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1930. [encoder setBytes:&ofs0 length:sizeof( int32_t) atIndex:2];
  1931. [encoder setBytes:&ofs1 length:sizeof( int32_t) atIndex:3];
  1932. [encoder setBytes:&IW length:sizeof( int32_t) atIndex:4];
  1933. [encoder setBytes:&IH length:sizeof( int32_t) atIndex:5];
  1934. [encoder setBytes:&CHW length:sizeof( int32_t) atIndex:6];
  1935. [encoder setBytes:&s0 length:sizeof( int32_t) atIndex:7];
  1936. [encoder setBytes:&s1 length:sizeof( int32_t) atIndex:8];
  1937. [encoder setBytes:&p0 length:sizeof( int32_t) atIndex:9];
  1938. [encoder setBytes:&p1 length:sizeof( int32_t) atIndex:10];
  1939. [encoder setBytes:&d0 length:sizeof( int32_t) atIndex:11];
  1940. [encoder setBytes:&d1 length:sizeof( int32_t) atIndex:12];
  1941. [encoder dispatchThreadgroups:MTLSizeMake(IC, OH, OW) threadsPerThreadgroup:MTLSizeMake(N, KH, KW)];
  1942. } break;
  1943. case GGML_OP_UPSCALE:
  1944. {
  1945. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1946. const int sf = dst->op_params[0];
  1947. [encoder setComputePipelineState:ctx->pipeline_upscale_f32];
  1948. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1949. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1950. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1951. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1952. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1953. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1954. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1955. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1956. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1957. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1958. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:10];
  1959. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:11];
  1960. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:12];
  1961. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:13];
  1962. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:14];
  1963. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1964. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:16];
  1965. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:17];
  1966. [encoder setBytes:&sf length:sizeof(sf) atIndex:18];
  1967. const int nth = MIN(1024, ne0);
  1968. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1969. } break;
  1970. case GGML_OP_PAD:
  1971. {
  1972. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1973. [encoder setComputePipelineState:ctx->pipeline_pad_f32];
  1974. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  1975. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  1976. [encoder setBytes:&ne00 length:sizeof(ne00) atIndex:2];
  1977. [encoder setBytes:&ne01 length:sizeof(ne01) atIndex:3];
  1978. [encoder setBytes:&ne02 length:sizeof(ne02) atIndex:4];
  1979. [encoder setBytes:&ne03 length:sizeof(ne03) atIndex:5];
  1980. [encoder setBytes:&nb00 length:sizeof(nb00) atIndex:6];
  1981. [encoder setBytes:&nb01 length:sizeof(nb01) atIndex:7];
  1982. [encoder setBytes:&nb02 length:sizeof(nb02) atIndex:8];
  1983. [encoder setBytes:&nb03 length:sizeof(nb03) atIndex:9];
  1984. [encoder setBytes:&ne0 length:sizeof(ne0) atIndex:10];
  1985. [encoder setBytes:&ne1 length:sizeof(ne1) atIndex:11];
  1986. [encoder setBytes:&ne2 length:sizeof(ne2) atIndex:12];
  1987. [encoder setBytes:&ne3 length:sizeof(ne3) atIndex:13];
  1988. [encoder setBytes:&nb0 length:sizeof(nb0) atIndex:14];
  1989. [encoder setBytes:&nb1 length:sizeof(nb1) atIndex:15];
  1990. [encoder setBytes:&nb2 length:sizeof(nb2) atIndex:16];
  1991. [encoder setBytes:&nb3 length:sizeof(nb3) atIndex:17];
  1992. const int nth = MIN(1024, ne0);
  1993. [encoder dispatchThreadgroups:MTLSizeMake(ne1, ne2, ne3) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  1994. } break;
  1995. case GGML_OP_ARGSORT:
  1996. {
  1997. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  1998. GGML_ASSERT( dst->type == GGML_TYPE_I32);
  1999. const int nrows = ggml_nrows(src0);
  2000. enum ggml_sort_order order = (enum ggml_sort_order) dst->op_params[0];
  2001. switch (order) {
  2002. case GGML_SORT_ASC: [encoder setComputePipelineState:ctx->pipeline_argsort_f32_i32_asc]; break;
  2003. case GGML_SORT_DESC: [encoder setComputePipelineState:ctx->pipeline_argsort_f32_i32_desc]; break;
  2004. default: GGML_ASSERT(false);
  2005. };
  2006. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  2007. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  2008. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  2009. [encoder dispatchThreadgroups:MTLSizeMake(1, nrows, 1) threadsPerThreadgroup:MTLSizeMake(ne00, 1, 1)];
  2010. } break;
  2011. case GGML_OP_LEAKY_RELU:
  2012. {
  2013. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  2014. float slope;
  2015. memcpy(&slope, dst->op_params, sizeof(float));
  2016. [encoder setComputePipelineState:ctx->pipeline_leaky_relu_f32];
  2017. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  2018. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  2019. [encoder setBytes:&slope length:sizeof(slope) atIndex:2];
  2020. const int64_t n = ggml_nelements(dst);
  2021. [encoder dispatchThreadgroups:MTLSizeMake(n, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
  2022. } break;
  2023. case GGML_OP_DUP:
  2024. case GGML_OP_CPY:
  2025. case GGML_OP_CONT:
  2026. {
  2027. GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0);
  2028. int nth = MIN(1024, ne00/ggml_blck_size(src0->type));
  2029. switch (src0t) {
  2030. case GGML_TYPE_F32:
  2031. {
  2032. GGML_ASSERT(ne0 % ggml_blck_size(dst->type) == 0);
  2033. switch (dstt) {
  2034. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f16]; break;
  2035. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_f32]; break;
  2036. case GGML_TYPE_Q8_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q8_0]; break;
  2037. case GGML_TYPE_Q4_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q4_0]; break;
  2038. case GGML_TYPE_Q4_1: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q4_1]; break;
  2039. //case GGML_TYPE_Q5_0: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q5_0]; break;
  2040. //case GGML_TYPE_Q5_1: [encoder setComputePipelineState:ctx->pipeline_cpy_f32_q5_1]; break;
  2041. default: GGML_ASSERT(false && "not implemented");
  2042. };
  2043. } break;
  2044. case GGML_TYPE_F16:
  2045. {
  2046. switch (dstt) {
  2047. case GGML_TYPE_F16: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f16]; break;
  2048. case GGML_TYPE_F32: [encoder setComputePipelineState:ctx->pipeline_cpy_f16_f32]; break;
  2049. default: GGML_ASSERT(false && "not implemented");
  2050. };
  2051. } break;
  2052. default: GGML_ASSERT(false && "not implemented");
  2053. }
  2054. [encoder setBuffer:id_src0 offset:offs_src0 atIndex:0];
  2055. [encoder setBuffer:id_dst offset:offs_dst atIndex:1];
  2056. [encoder setBytes:&ne00 length:sizeof( int64_t) atIndex:2];
  2057. [encoder setBytes:&ne01 length:sizeof( int64_t) atIndex:3];
  2058. [encoder setBytes:&ne02 length:sizeof( int64_t) atIndex:4];
  2059. [encoder setBytes:&ne03 length:sizeof( int64_t) atIndex:5];
  2060. [encoder setBytes:&nb00 length:sizeof(uint64_t) atIndex:6];
  2061. [encoder setBytes:&nb01 length:sizeof(uint64_t) atIndex:7];
  2062. [encoder setBytes:&nb02 length:sizeof(uint64_t) atIndex:8];
  2063. [encoder setBytes:&nb03 length:sizeof(uint64_t) atIndex:9];
  2064. [encoder setBytes:&ne0 length:sizeof( int64_t) atIndex:10];
  2065. [encoder setBytes:&ne1 length:sizeof( int64_t) atIndex:11];
  2066. [encoder setBytes:&ne2 length:sizeof( int64_t) atIndex:12];
  2067. [encoder setBytes:&ne3 length:sizeof( int64_t) atIndex:13];
  2068. [encoder setBytes:&nb0 length:sizeof(uint64_t) atIndex:14];
  2069. [encoder setBytes:&nb1 length:sizeof(uint64_t) atIndex:15];
  2070. [encoder setBytes:&nb2 length:sizeof(uint64_t) atIndex:16];
  2071. [encoder setBytes:&nb3 length:sizeof(uint64_t) atIndex:17];
  2072. [encoder dispatchThreadgroups:MTLSizeMake(ne01, ne02, ne03) threadsPerThreadgroup:MTLSizeMake(nth, 1, 1)];
  2073. } break;
  2074. default:
  2075. {
  2076. GGML_METAL_LOG_ERROR("%s: error: node %3d, op = %8s not implemented\n", __func__, i, ggml_op_name(dst->op));
  2077. GGML_ASSERT(false);
  2078. }
  2079. }
  2080. }
  2081. if (encoder != nil) {
  2082. [encoder endEncoding];
  2083. encoder = nil;
  2084. }
  2085. [command_buffer commit];
  2086. });
  2087. }
  2088. // wait for all threads to finish
  2089. dispatch_barrier_sync(ctx->d_queue, ^{});
  2090. // check status of command buffers
  2091. // needed to detect if the device ran out-of-memory for example (#1881)
  2092. for (int i = 0; i < n_cb; i++) {
  2093. [ctx->command_buffers[i] waitUntilCompleted];
  2094. MTLCommandBufferStatus status = (MTLCommandBufferStatus) [ctx->command_buffers[i] status];
  2095. if (status != MTLCommandBufferStatusCompleted) {
  2096. GGML_METAL_LOG_INFO("%s: command buffer %d failed with status %lu\n", __func__, i, status);
  2097. GGML_ASSERT(false);
  2098. }
  2099. }
  2100. }
  2101. }
  2102. ////////////////////////////////////////////////////////////////////////////////
  2103. // backend interface
  2104. // default buffer
  2105. static id<MTLDevice> g_backend_device = nil;
  2106. static int g_backend_device_ref_count = 0;
  2107. static id<MTLDevice> ggml_backend_metal_get_device(void) {
  2108. if (g_backend_device == nil) {
  2109. g_backend_device = MTLCreateSystemDefaultDevice();
  2110. }
  2111. g_backend_device_ref_count++;
  2112. return g_backend_device;
  2113. }
  2114. static void ggml_backend_metal_free_device(void) {
  2115. assert(g_backend_device_ref_count > 0);
  2116. g_backend_device_ref_count--;
  2117. if (g_backend_device_ref_count == 0) {
  2118. [g_backend_device release];
  2119. g_backend_device = nil;
  2120. }
  2121. }
  2122. static void * ggml_backend_metal_buffer_get_base(ggml_backend_buffer_t buffer) {
  2123. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2124. return ctx->all_data;
  2125. }
  2126. static void ggml_backend_metal_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  2127. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2128. for (int i = 0; i < ctx->n_buffers; i++) {
  2129. [ctx->buffers[i].metal release];
  2130. }
  2131. ggml_backend_metal_free_device();
  2132. if (ctx->owned) {
  2133. free(ctx->all_data);
  2134. }
  2135. free(ctx);
  2136. }
  2137. static void ggml_backend_metal_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  2138. memcpy((char *)tensor->data + offset, data, size);
  2139. UNUSED(buffer);
  2140. }
  2141. static void ggml_backend_metal_buffer_get_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  2142. memcpy(data, (const char *)tensor->data + offset, size);
  2143. UNUSED(buffer);
  2144. }
  2145. static void ggml_backend_metal_buffer_cpy_tensor_from(ggml_backend_buffer_t buffer, struct ggml_tensor * src, struct ggml_tensor * dst) {
  2146. ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
  2147. UNUSED(buffer);
  2148. }
  2149. static void ggml_backend_metal_buffer_cpy_tensor_to(ggml_backend_buffer_t buffer, struct ggml_tensor * src, struct ggml_tensor * dst) {
  2150. ggml_backend_tensor_set(dst, src->data, 0, ggml_nbytes(src));
  2151. UNUSED(buffer);
  2152. }
  2153. static void ggml_backend_metal_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  2154. struct ggml_backend_metal_buffer_context * ctx = (struct ggml_backend_metal_buffer_context *)buffer->context;
  2155. memset(ctx->all_data, value, ctx->all_size);
  2156. }
  2157. static struct ggml_backend_buffer_i ggml_backend_metal_buffer_i = {
  2158. /* .free_buffer = */ ggml_backend_metal_buffer_free_buffer,
  2159. /* .get_base = */ ggml_backend_metal_buffer_get_base,
  2160. /* .init_tensor = */ NULL,
  2161. /* .set_tensor = */ ggml_backend_metal_buffer_set_tensor,
  2162. /* .get_tensor = */ ggml_backend_metal_buffer_get_tensor,
  2163. /* .cpy_tensor_from = */ ggml_backend_metal_buffer_cpy_tensor_from,
  2164. /* .cpy_tensor_to = */ ggml_backend_metal_buffer_cpy_tensor_to,
  2165. /* .clear = */ ggml_backend_metal_buffer_clear,
  2166. };
  2167. // default buffer type
  2168. static ggml_backend_buffer_t ggml_backend_metal_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  2169. struct ggml_backend_metal_buffer_context * ctx = malloc(sizeof(struct ggml_backend_metal_buffer_context));
  2170. const size_t size_page = sysconf(_SC_PAGESIZE);
  2171. size_t size_aligned = size;
  2172. if ((size_aligned % size_page) != 0) {
  2173. size_aligned += (size_page - (size_aligned % size_page));
  2174. }
  2175. id<MTLDevice> device = ggml_backend_metal_get_device();
  2176. ctx->all_data = ggml_metal_host_malloc(size_aligned);
  2177. ctx->all_size = size_aligned;
  2178. ctx->owned = true;
  2179. ctx->n_buffers = 1;
  2180. ctx->buffers[0].data = ctx->all_data;
  2181. ctx->buffers[0].size = size;
  2182. ctx->buffers[0].metal = [device newBufferWithBytesNoCopy:ctx->all_data
  2183. length:size_aligned
  2184. options:MTLResourceStorageModeShared
  2185. deallocator:nil];
  2186. if (ctx->buffers[0].metal == nil) {
  2187. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
  2188. free(ctx);
  2189. ggml_backend_metal_free_device();
  2190. return NULL;
  2191. }
  2192. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB", __func__, size_aligned / 1024.0 / 1024.0);
  2193. #if TARGET_OS_OSX
  2194. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  2195. device.currentAllocatedSize / 1024.0 / 1024.0,
  2196. device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  2197. if (device.currentAllocatedSize > device.recommendedMaxWorkingSetSize) {
  2198. GGML_METAL_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
  2199. } else {
  2200. GGML_METAL_LOG_INFO("\n");
  2201. }
  2202. #else
  2203. GGML_METAL_LOG_INFO(", (%8.2f)\n", device.currentAllocatedSize / 1024.0 / 1024.0);
  2204. #endif
  2205. return ggml_backend_buffer_init(buft, ggml_backend_metal_buffer_i, ctx, size);
  2206. }
  2207. static size_t ggml_backend_metal_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  2208. return 32;
  2209. UNUSED(buft);
  2210. }
  2211. static bool ggml_backend_metal_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  2212. return ggml_backend_is_metal(backend) || ggml_backend_is_cpu(backend);
  2213. UNUSED(buft);
  2214. }
  2215. static bool ggml_backend_metal_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
  2216. return true;
  2217. UNUSED(buft);
  2218. }
  2219. ggml_backend_buffer_type_t ggml_backend_metal_buffer_type(void) {
  2220. static struct ggml_backend_buffer_type ggml_backend_buffer_type_metal = {
  2221. /* .iface = */ {
  2222. /* .alloc_buffer = */ ggml_backend_metal_buffer_type_alloc_buffer,
  2223. /* .get_alignment = */ ggml_backend_metal_buffer_type_get_alignment,
  2224. /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
  2225. /* .supports_backend = */ ggml_backend_metal_buffer_type_supports_backend,
  2226. /* .is_host = */ ggml_backend_metal_buffer_type_is_host,
  2227. },
  2228. /* .context = */ NULL,
  2229. };
  2230. return &ggml_backend_buffer_type_metal;
  2231. }
  2232. // buffer from ptr
  2233. ggml_backend_buffer_t ggml_backend_metal_buffer_from_ptr(void * data, size_t size, size_t max_size) {
  2234. struct ggml_backend_metal_buffer_context * ctx = malloc(sizeof(struct ggml_backend_metal_buffer_context));
  2235. ctx->all_data = data;
  2236. ctx->all_size = size;
  2237. ctx->owned = false;
  2238. ctx->n_buffers = 0;
  2239. const size_t size_page = sysconf(_SC_PAGESIZE);
  2240. size_t size_aligned = size;
  2241. if ((size_aligned % size_page) != 0) {
  2242. size_aligned += (size_page - (size_aligned % size_page));
  2243. }
  2244. id<MTLDevice> device = ggml_backend_metal_get_device();
  2245. // the buffer fits into the max buffer size allowed by the device
  2246. if (size_aligned <= device.maxBufferLength) {
  2247. ctx->buffers[ctx->n_buffers].data = data;
  2248. ctx->buffers[ctx->n_buffers].size = size;
  2249. ctx->buffers[ctx->n_buffers].metal = [device newBufferWithBytesNoCopy:data length:size_aligned options:MTLResourceStorageModeShared deallocator:nil];
  2250. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  2251. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_aligned / 1024.0 / 1024.0);
  2252. return false;
  2253. }
  2254. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB", __func__, size_aligned / 1024.0 / 1024.0);
  2255. ++ctx->n_buffers;
  2256. } else {
  2257. // this overlap between the views will guarantee that the tensor with the maximum size will fully fit into
  2258. // one of the views
  2259. const size_t size_ovlp = ((max_size + size_page - 1) / size_page + 1) * size_page; // round-up 2 pages just in case
  2260. const size_t size_step = device.maxBufferLength - size_ovlp;
  2261. const size_t size_view = device.maxBufferLength;
  2262. for (size_t i = 0; i < size; i += size_step) {
  2263. const size_t size_step_aligned = (i + size_view <= size) ? size_view : (size_aligned - i);
  2264. ctx->buffers[ctx->n_buffers].data = (void *) ((uint8_t *) data + i);
  2265. ctx->buffers[ctx->n_buffers].size = size_step_aligned;
  2266. ctx->buffers[ctx->n_buffers].metal = [device newBufferWithBytesNoCopy:(void *) ((uint8_t *) data + i) length:size_step_aligned options:MTLResourceStorageModeShared deallocator:nil];
  2267. if (ctx->buffers[ctx->n_buffers].metal == nil) {
  2268. GGML_METAL_LOG_ERROR("%s: error: failed to allocate buffer, size = %8.2f MiB\n", __func__, size_step_aligned / 1024.0 / 1024.0);
  2269. return false;
  2270. }
  2271. GGML_METAL_LOG_INFO("%s: allocated buffer, size = %8.2f MiB, offs = %12ld", __func__, size_step_aligned / 1024.0 / 1024.0, i);
  2272. if (i + size_step < size) {
  2273. GGML_METAL_LOG_INFO("\n");
  2274. }
  2275. ++ctx->n_buffers;
  2276. }
  2277. }
  2278. #if TARGET_OS_OSX
  2279. GGML_METAL_LOG_INFO(", (%8.2f / %8.2f)",
  2280. device.currentAllocatedSize / 1024.0 / 1024.0,
  2281. device.recommendedMaxWorkingSetSize / 1024.0 / 1024.0);
  2282. if (device.currentAllocatedSize > device.recommendedMaxWorkingSetSize) {
  2283. GGML_METAL_LOG_WARN("%s: warning: current allocated size is greater than the recommended max working set size\n", __func__);
  2284. } else {
  2285. GGML_METAL_LOG_INFO("\n");
  2286. }
  2287. #else
  2288. GGML_METAL_LOG_INFO(", (%8.2f)\n", device.currentAllocatedSize / 1024.0 / 1024.0);
  2289. #endif
  2290. return ggml_backend_buffer_init(ggml_backend_metal_buffer_type(), ggml_backend_metal_buffer_i, ctx, size);
  2291. }
  2292. // backend
  2293. static const char * ggml_backend_metal_name(ggml_backend_t backend) {
  2294. return "Metal";
  2295. UNUSED(backend);
  2296. }
  2297. static void ggml_backend_metal_free(ggml_backend_t backend) {
  2298. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2299. ggml_metal_free(ctx);
  2300. free(backend);
  2301. }
  2302. static ggml_backend_buffer_type_t ggml_backend_metal_get_default_buffer_type(ggml_backend_t backend) {
  2303. return ggml_backend_metal_buffer_type();
  2304. UNUSED(backend);
  2305. }
  2306. static void ggml_backend_metal_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
  2307. struct ggml_metal_context * metal_ctx = (struct ggml_metal_context *)backend->context;
  2308. ggml_metal_graph_compute(metal_ctx, cgraph);
  2309. }
  2310. static bool ggml_backend_metal_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
  2311. return ggml_metal_supports_op(op);
  2312. UNUSED(backend);
  2313. }
  2314. static struct ggml_backend_i metal_backend_i = {
  2315. /* .get_name = */ ggml_backend_metal_name,
  2316. /* .free = */ ggml_backend_metal_free,
  2317. /* .get_default_buffer_type = */ ggml_backend_metal_get_default_buffer_type,
  2318. /* .set_tensor_async = */ NULL,
  2319. /* .get_tensor_async = */ NULL,
  2320. /* .cpy_tensor_from_async = */ NULL,
  2321. /* .cpy_tensor_to_async = */ NULL,
  2322. /* .synchronize = */ NULL,
  2323. /* .graph_plan_create = */ NULL,
  2324. /* .graph_plan_free = */ NULL,
  2325. /* .graph_plan_compute = */ NULL,
  2326. /* .graph_compute = */ ggml_backend_metal_graph_compute,
  2327. /* .supports_op = */ ggml_backend_metal_supports_op,
  2328. };
  2329. ggml_backend_t ggml_backend_metal_init(void) {
  2330. struct ggml_metal_context * ctx = ggml_metal_init(GGML_DEFAULT_N_THREADS);
  2331. if (ctx == NULL) {
  2332. return NULL;
  2333. }
  2334. ggml_backend_t metal_backend = malloc(sizeof(struct ggml_backend));
  2335. *metal_backend = (struct ggml_backend) {
  2336. /* .interface = */ metal_backend_i,
  2337. /* .context = */ ctx,
  2338. };
  2339. return metal_backend;
  2340. }
  2341. bool ggml_backend_is_metal(ggml_backend_t backend) {
  2342. return backend->iface.get_name == ggml_backend_metal_name;
  2343. }
  2344. void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
  2345. GGML_ASSERT(ggml_backend_is_metal(backend));
  2346. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2347. ggml_metal_set_n_cb(ctx, n_cb);
  2348. }
  2349. bool ggml_backend_metal_supports_family(ggml_backend_t backend, int family) {
  2350. GGML_ASSERT(ggml_backend_is_metal(backend));
  2351. struct ggml_metal_context * ctx = (struct ggml_metal_context *)backend->context;
  2352. return [ctx->device supportsFamily:(MTLGPUFamilyApple1 + family - 1)];
  2353. }
  2354. ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data); // silence warning
  2355. ggml_backend_t ggml_backend_reg_metal_init(const char * params, void * user_data) {
  2356. return ggml_backend_metal_init();
  2357. GGML_UNUSED(params);
  2358. GGML_UNUSED(user_data);
  2359. }