ggml-metal.m 143 KB

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