ggml-cpu.c 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418
  1. #define _CRT_SECURE_NO_DEPRECATE // Disables "unsafe" warnings on Windows
  2. #define _USE_MATH_DEFINES // For M_PI on MSVC
  3. #include "ggml-backend-impl.h"
  4. #include "ggml-backend.h"
  5. #include "ggml-cpu-traits.h"
  6. #include "ggml-cpu-impl.h"
  7. #include "ggml-cpu.h"
  8. #include "ggml-impl.h"
  9. #include "ggml-cpu-quants.h"
  10. #include "ggml-threading.h"
  11. #include "unary-ops.h"
  12. #include "binary-ops.h"
  13. #include "vec.h"
  14. #include "ops.h"
  15. #include "ggml.h"
  16. #if defined(_MSC_VER) || defined(__MINGW32__)
  17. #include <malloc.h> // using malloc.h with MSC/MINGW
  18. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  19. #include <alloca.h>
  20. #endif
  21. #include <assert.h>
  22. #include <errno.h>
  23. #include <time.h>
  24. #include <math.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <stdint.h>
  28. #include <inttypes.h>
  29. #include <stdio.h>
  30. #include <float.h>
  31. #include <limits.h>
  32. #include <stdarg.h>
  33. #include <signal.h>
  34. #if defined(__gnu_linux__)
  35. #include <syscall.h>
  36. #endif
  37. #ifdef GGML_USE_OPENMP
  38. #include <omp.h>
  39. #endif
  40. #if defined(__ARM_FEATURE_SVE) || defined(__ARM_FEATURE_MATMUL_INT8)
  41. #undef GGML_USE_LLAMAFILE
  42. #endif
  43. #ifdef GGML_USE_LLAMAFILE
  44. #include "llamafile/sgemm.h"
  45. #endif
  46. #if defined(_MSC_VER)
  47. // disable "possible loss of data" to avoid hundreds of casts
  48. // we should just be careful :)
  49. #pragma warning(disable: 4244 4267)
  50. // disable POSIX deprecation warnings
  51. // these functions are never going away, anyway
  52. #pragma warning(disable: 4996)
  53. // unreachable code because of multiple instances of code after GGML_ABORT
  54. #pragma warning(disable: 4702)
  55. #endif
  56. // Note: once we move threading into a separate C++ file
  57. // will use std::hardware_destructive_interference_size instead of hardcoding it here
  58. // and we'll use C++ attribute syntax.
  59. #define GGML_CACHE_LINE 64
  60. #if defined(__clang__) || defined(__GNUC__)
  61. #define GGML_CACHE_ALIGN __attribute__((aligned(GGML_CACHE_LINE)))
  62. #endif
  63. #if defined(__has_feature)
  64. #if __has_feature(thread_sanitizer)
  65. #define GGML_TSAN_ENABLED 1
  66. #endif
  67. #else // __has_feature
  68. #if defined(__SANITIZE_THREAD__)
  69. #define GGML_TSAN_ENABLED 1
  70. #endif
  71. #endif // __has_feature
  72. #define UNUSED GGML_UNUSED
  73. #define SWAP(x, y, T) do { T SWAP = x; (x) = y; (y) = SWAP; } while (0)
  74. #if defined(__ARM_ARCH)
  75. struct ggml_arm_arch_features_type {
  76. int has_neon;
  77. int has_dotprod;
  78. int has_i8mm;
  79. int has_sve;
  80. int sve_cnt;
  81. int has_sme;
  82. } ggml_arm_arch_features = {-1, -1, -1, -1, 0, -1};
  83. #endif
  84. #if defined(_WIN32)
  85. #define WIN32_LEAN_AND_MEAN
  86. #ifndef NOMINMAX
  87. #define NOMINMAX
  88. #endif
  89. #include <windows.h>
  90. #if defined(_MSC_VER) && !defined(__clang__)
  91. #define GGML_CACHE_ALIGN __declspec(align(GGML_CACHE_LINE))
  92. typedef volatile LONG atomic_int;
  93. typedef atomic_int atomic_bool;
  94. typedef atomic_int atomic_flag;
  95. #define ATOMIC_FLAG_INIT 0
  96. typedef enum {
  97. memory_order_relaxed,
  98. memory_order_consume,
  99. memory_order_acquire,
  100. memory_order_release,
  101. memory_order_acq_rel,
  102. memory_order_seq_cst
  103. } memory_order;
  104. static void atomic_store(atomic_int * ptr, LONG val) {
  105. InterlockedExchange(ptr, val);
  106. }
  107. static void atomic_store_explicit(atomic_int * ptr, LONG val, memory_order mo) {
  108. // TODO: add support for explicit memory order
  109. InterlockedExchange(ptr, val);
  110. }
  111. static LONG atomic_load(atomic_int * ptr) {
  112. return InterlockedCompareExchange(ptr, 0, 0);
  113. }
  114. static LONG atomic_load_explicit(atomic_int * ptr, memory_order mo) {
  115. // TODO: add support for explicit memory order
  116. return InterlockedCompareExchange(ptr, 0, 0);
  117. }
  118. static LONG atomic_fetch_add(atomic_int * ptr, LONG inc) {
  119. return InterlockedExchangeAdd(ptr, inc);
  120. }
  121. static LONG atomic_fetch_add_explicit(atomic_int * ptr, LONG inc, memory_order mo) {
  122. // TODO: add support for explicit memory order
  123. return InterlockedExchangeAdd(ptr, inc);
  124. }
  125. static atomic_bool atomic_flag_test_and_set(atomic_flag * ptr) {
  126. return InterlockedExchange(ptr, 1);
  127. }
  128. static void atomic_flag_clear(atomic_flag * ptr) {
  129. InterlockedExchange(ptr, 0);
  130. }
  131. static void atomic_thread_fence(memory_order mo) {
  132. MemoryBarrier();
  133. }
  134. #else // clang
  135. #include <stdatomic.h>
  136. #endif
  137. typedef HANDLE pthread_t;
  138. typedef DWORD thread_ret_t;
  139. static int pthread_create(pthread_t * out, void * unused, thread_ret_t(*func)(void *), void * arg) {
  140. (void) unused;
  141. HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL);
  142. if (handle == NULL)
  143. {
  144. return EAGAIN;
  145. }
  146. *out = handle;
  147. return 0;
  148. }
  149. static int pthread_join(pthread_t thread, void * unused) {
  150. (void) unused;
  151. int ret = (int) WaitForSingleObject(thread, INFINITE);
  152. CloseHandle(thread);
  153. return ret;
  154. }
  155. static int sched_yield (void) {
  156. Sleep (0);
  157. return 0;
  158. }
  159. #else
  160. #include <pthread.h>
  161. #include <stdatomic.h>
  162. #include <sched.h>
  163. #if defined(__FreeBSD__)
  164. #include <pthread_np.h>
  165. #endif
  166. typedef void * thread_ret_t;
  167. #include <sys/types.h>
  168. #include <sys/stat.h>
  169. #include <unistd.h>
  170. #endif
  171. typedef pthread_t ggml_thread_t;
  172. #if defined(__APPLE__)
  173. #include <unistd.h>
  174. #include <mach/mach.h>
  175. #include <TargetConditionals.h>
  176. #endif
  177. static const struct ggml_type_traits_cpu type_traits_cpu[GGML_TYPE_COUNT] = {
  178. [GGML_TYPE_F32] = {
  179. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f32,
  180. .vec_dot_type = GGML_TYPE_F32,
  181. .nrows = 1,
  182. },
  183. [GGML_TYPE_F16] = {
  184. .from_float = (ggml_from_float_t) ggml_fp32_to_fp16_row,
  185. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f16,
  186. .vec_dot_type = GGML_TYPE_F16,
  187. .nrows = 1,
  188. },
  189. [GGML_TYPE_Q4_0] = {
  190. .from_float = quantize_row_q4_0,
  191. .vec_dot = ggml_vec_dot_q4_0_q8_0,
  192. .vec_dot_type = GGML_TYPE_Q8_0,
  193. #if defined (__ARM_FEATURE_MATMUL_INT8)
  194. .nrows = 2,
  195. #else
  196. .nrows = 1,
  197. #endif
  198. },
  199. [GGML_TYPE_Q4_1] = {
  200. .from_float = quantize_row_q4_1,
  201. .vec_dot = ggml_vec_dot_q4_1_q8_1,
  202. .vec_dot_type = GGML_TYPE_Q8_1,
  203. #if defined (__ARM_FEATURE_MATMUL_INT8)
  204. .nrows = 2,
  205. #else
  206. .nrows = 1,
  207. #endif
  208. },
  209. [GGML_TYPE_Q5_0] = {
  210. .from_float = quantize_row_q5_0,
  211. .vec_dot = ggml_vec_dot_q5_0_q8_0,
  212. .vec_dot_type = GGML_TYPE_Q8_0,
  213. .nrows = 1,
  214. },
  215. [GGML_TYPE_Q5_1] = {
  216. .from_float = quantize_row_q5_1,
  217. .vec_dot = ggml_vec_dot_q5_1_q8_1,
  218. .vec_dot_type = GGML_TYPE_Q8_1,
  219. .nrows = 1,
  220. },
  221. [GGML_TYPE_Q8_0] = {
  222. .from_float = quantize_row_q8_0,
  223. .vec_dot = ggml_vec_dot_q8_0_q8_0,
  224. .vec_dot_type = GGML_TYPE_Q8_0,
  225. #if defined (__ARM_FEATURE_MATMUL_INT8)
  226. .nrows = 2,
  227. #else
  228. .nrows = 1,
  229. #endif
  230. },
  231. [GGML_TYPE_Q8_1] = {
  232. .from_float = quantize_row_q8_1,
  233. .vec_dot_type = GGML_TYPE_Q8_1,
  234. .nrows = 1,
  235. },
  236. [GGML_TYPE_Q2_K] = {
  237. .from_float = quantize_row_q2_K,
  238. .vec_dot = ggml_vec_dot_q2_K_q8_K,
  239. .vec_dot_type = GGML_TYPE_Q8_K,
  240. .nrows = 1,
  241. },
  242. [GGML_TYPE_Q3_K] = {
  243. .from_float = quantize_row_q3_K,
  244. .vec_dot = ggml_vec_dot_q3_K_q8_K,
  245. .vec_dot_type = GGML_TYPE_Q8_K,
  246. .nrows = 1,
  247. },
  248. [GGML_TYPE_Q4_K] = {
  249. .from_float = quantize_row_q4_K,
  250. .vec_dot = ggml_vec_dot_q4_K_q8_K,
  251. .vec_dot_type = GGML_TYPE_Q8_K,
  252. .nrows = 1,
  253. },
  254. [GGML_TYPE_Q5_K] = {
  255. .from_float = quantize_row_q5_K,
  256. .vec_dot = ggml_vec_dot_q5_K_q8_K,
  257. .vec_dot_type = GGML_TYPE_Q8_K,
  258. .nrows = 1,
  259. },
  260. [GGML_TYPE_Q6_K] = {
  261. .from_float = quantize_row_q6_K,
  262. .vec_dot = ggml_vec_dot_q6_K_q8_K,
  263. .vec_dot_type = GGML_TYPE_Q8_K,
  264. .nrows = 1,
  265. },
  266. [GGML_TYPE_IQ2_XXS] = {
  267. .from_float = NULL,
  268. .vec_dot = ggml_vec_dot_iq2_xxs_q8_K,
  269. .vec_dot_type = GGML_TYPE_Q8_K,
  270. .nrows = 1,
  271. },
  272. [GGML_TYPE_IQ2_XS] = {
  273. .from_float = NULL,
  274. .vec_dot = ggml_vec_dot_iq2_xs_q8_K,
  275. .vec_dot_type = GGML_TYPE_Q8_K,
  276. .nrows = 1,
  277. },
  278. [GGML_TYPE_IQ3_XXS] = {
  279. // NOTE: from_float for iq3 and iq2_s was removed because these quants require initialization in ggml_quantize_init
  280. //.from_float = quantize_row_iq3_xxs,
  281. .vec_dot = ggml_vec_dot_iq3_xxs_q8_K,
  282. .vec_dot_type = GGML_TYPE_Q8_K,
  283. .nrows = 1,
  284. },
  285. [GGML_TYPE_IQ3_S] = {
  286. //.from_float = quantize_row_iq3_s,
  287. .vec_dot = ggml_vec_dot_iq3_s_q8_K,
  288. .vec_dot_type = GGML_TYPE_Q8_K,
  289. .nrows = 1,
  290. },
  291. [GGML_TYPE_IQ2_S] = {
  292. //.from_float = quantize_row_iq2_s,
  293. .vec_dot = ggml_vec_dot_iq2_s_q8_K,
  294. .vec_dot_type = GGML_TYPE_Q8_K,
  295. .nrows = 1,
  296. },
  297. [GGML_TYPE_IQ1_S] = {
  298. .from_float = NULL,
  299. .vec_dot = ggml_vec_dot_iq1_s_q8_K,
  300. .vec_dot_type = GGML_TYPE_Q8_K,
  301. .nrows = 1,
  302. },
  303. [GGML_TYPE_IQ1_M] = {
  304. .from_float = NULL,
  305. .vec_dot = ggml_vec_dot_iq1_m_q8_K,
  306. .vec_dot_type = GGML_TYPE_Q8_K,
  307. .nrows = 1,
  308. },
  309. [GGML_TYPE_IQ4_NL] = {
  310. .from_float = quantize_row_iq4_nl,
  311. .vec_dot = ggml_vec_dot_iq4_nl_q8_0,
  312. .vec_dot_type = GGML_TYPE_Q8_0,
  313. .nrows = 1,
  314. },
  315. [GGML_TYPE_IQ4_XS] = {
  316. .from_float = quantize_row_iq4_xs,
  317. .vec_dot = ggml_vec_dot_iq4_xs_q8_K,
  318. .vec_dot_type = GGML_TYPE_Q8_K,
  319. .nrows = 1,
  320. },
  321. [GGML_TYPE_Q8_K] = {
  322. .from_float = quantize_row_q8_K,
  323. },
  324. [GGML_TYPE_BF16] = {
  325. .from_float = (ggml_from_float_t) ggml_fp32_to_bf16_row,
  326. .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_bf16,
  327. .vec_dot_type = GGML_TYPE_BF16,
  328. .nrows = 1,
  329. },
  330. [GGML_TYPE_TQ1_0] = {
  331. .from_float = quantize_row_tq1_0,
  332. .vec_dot = ggml_vec_dot_tq1_0_q8_K,
  333. .vec_dot_type = GGML_TYPE_Q8_K,
  334. .nrows = 1,
  335. },
  336. [GGML_TYPE_TQ2_0] = {
  337. .from_float = quantize_row_tq2_0,
  338. .vec_dot = ggml_vec_dot_tq2_0_q8_K,
  339. .vec_dot_type = GGML_TYPE_Q8_K,
  340. .nrows = 1,
  341. },
  342. };
  343. const struct ggml_type_traits_cpu * ggml_get_type_traits_cpu(enum ggml_type type) {
  344. return &type_traits_cpu[type];
  345. }
  346. //
  347. // Threading defs
  348. //
  349. typedef pthread_t ggml_thread_t;
  350. #if defined(_WIN32)
  351. typedef CONDITION_VARIABLE ggml_cond_t;
  352. typedef SRWLOCK ggml_mutex_t;
  353. #define ggml_mutex_init(m) InitializeSRWLock(m)
  354. #define ggml_mutex_destroy(m)
  355. #define ggml_mutex_lock(m) AcquireSRWLockExclusive(m)
  356. #define ggml_mutex_unlock(m) ReleaseSRWLockExclusive(m)
  357. #define ggml_mutex_lock_shared(m) AcquireSRWLockShared(m)
  358. #define ggml_mutex_unlock_shared(m) ReleaseSRWLockShared(m)
  359. #define ggml_cond_init(c) InitializeConditionVariable(c)
  360. #define ggml_cond_destroy(c)
  361. #define ggml_cond_wait(c, m) SleepConditionVariableSRW(c, m, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED)
  362. #define ggml_cond_broadcast(c) WakeAllConditionVariable(c)
  363. #define ggml_thread_create pthread_create
  364. #define ggml_thread_join pthread_join
  365. #else
  366. typedef pthread_cond_t ggml_cond_t;
  367. typedef pthread_mutex_t ggml_mutex_t;
  368. #define ggml_mutex_init(m) pthread_mutex_init(m, NULL)
  369. #define ggml_mutex_destroy(m) pthread_mutex_destroy(m)
  370. #define ggml_mutex_lock(m) pthread_mutex_lock(m)
  371. #define ggml_mutex_unlock(m) pthread_mutex_unlock(m)
  372. #define ggml_mutex_lock_shared(m) pthread_mutex_lock(m)
  373. #define ggml_mutex_unlock_shared(m) pthread_mutex_unlock(m)
  374. #define ggml_lock_init(x) UNUSED(x)
  375. #define ggml_lock_destroy(x) UNUSED(x)
  376. #if defined(__x86_64__) || (defined(_MSC_VER) && defined(_M_AMD64))
  377. #define ggml_lock_lock(x) _mm_pause()
  378. #else
  379. #define ggml_lock_lock(x) UNUSED(x)
  380. #endif
  381. #define ggml_lock_unlock(x) UNUSED(x)
  382. #define GGML_LOCK_INITIALIZER 0
  383. #define ggml_cond_init(c) pthread_cond_init(c, NULL)
  384. #define ggml_cond_destroy(c) pthread_cond_destroy(c)
  385. #define ggml_cond_wait(c, m) pthread_cond_wait(c, m)
  386. #define ggml_cond_broadcast(c) pthread_cond_broadcast(c)
  387. #define ggml_thread_create pthread_create
  388. #define ggml_thread_join pthread_join
  389. #endif
  390. // Threadpool def
  391. struct ggml_threadpool {
  392. ggml_mutex_t mutex; // mutex for cond.var
  393. ggml_cond_t cond; // cond.var for waiting for new work
  394. struct ggml_cgraph * cgraph;
  395. struct ggml_cplan * cplan;
  396. // synchronization primitives
  397. atomic_int n_graph; // incremented when there is work to be done (i.e each graph)
  398. atomic_int GGML_CACHE_ALIGN n_barrier;
  399. atomic_int GGML_CACHE_ALIGN n_barrier_passed;
  400. atomic_int GGML_CACHE_ALIGN current_chunk; // currently processing chunk during Mat_Mul, shared between all the threads.
  401. // these are atomic as an annotation for thread-sanitizer
  402. atomic_bool stop; // Used for stopping the threadpool altogether
  403. atomic_bool pause; // Used for pausing the threadpool or individual threads
  404. atomic_int abort; // Used for aborting processing of a graph
  405. struct ggml_compute_state * workers; // per thread state
  406. int n_threads_max; // number of threads in the pool
  407. atomic_int n_threads_cur; // number of threads used in the current graph
  408. int32_t prio; // Scheduling priority
  409. uint32_t poll; // Polling level (0 - no polling)
  410. enum ggml_status ec;
  411. };
  412. // Per-thread state
  413. struct ggml_compute_state {
  414. #ifndef GGML_USE_OPENMP
  415. ggml_thread_t thrd;
  416. bool cpumask[GGML_MAX_N_THREADS];
  417. int last_graph;
  418. bool pending;
  419. #endif
  420. struct ggml_threadpool * threadpool;
  421. int ith;
  422. };
  423. // Helpers for polling loops
  424. #if defined(__aarch64__) && ( defined(__clang__) || defined(__GNUC__) )
  425. static inline void ggml_thread_cpu_relax(void) {
  426. __asm__ volatile("yield" ::: "memory");
  427. }
  428. #elif defined(__x86_64__)
  429. static inline void ggml_thread_cpu_relax(void) {
  430. _mm_pause();
  431. }
  432. #else
  433. static inline void ggml_thread_cpu_relax(void) {;}
  434. #endif
  435. //
  436. // NUMA support
  437. //
  438. #define GGML_NUMA_MAX_NODES 8
  439. #define GGML_NUMA_MAX_CPUS 512
  440. struct ggml_numa_node {
  441. uint32_t cpus[GGML_NUMA_MAX_CPUS]; // hardware threads on this node
  442. uint32_t n_cpus;
  443. };
  444. struct ggml_numa_nodes {
  445. enum ggml_numa_strategy numa_strategy;
  446. struct ggml_numa_node nodes[GGML_NUMA_MAX_NODES];
  447. uint32_t n_nodes;
  448. uint32_t total_cpus; // hardware threads on system
  449. uint32_t current_node; // node on which main process is execting
  450. #if defined(__gnu_linux__)
  451. cpu_set_t cpuset; // cpuset from numactl
  452. #else
  453. uint32_t cpuset; // no NUMA support outside of Linux at this time. Use a portable datatype
  454. #endif
  455. };
  456. //
  457. // ggml state
  458. //
  459. struct ggml_state {
  460. struct ggml_numa_nodes numa;
  461. };
  462. static struct ggml_state g_state = {0};
  463. void ggml_barrier(struct ggml_threadpool * tp) {
  464. int n_threads = atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed);
  465. if (n_threads == 1) {
  466. return;
  467. }
  468. #ifdef GGML_USE_OPENMP
  469. #pragma omp barrier
  470. #else
  471. int n_passed = atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed);
  472. // enter barrier (full seq-cst fence)
  473. int n_barrier = atomic_fetch_add_explicit(&tp->n_barrier, 1, memory_order_seq_cst);
  474. if (n_barrier == (n_threads - 1)) {
  475. // last thread
  476. atomic_store_explicit(&tp->n_barrier, 0, memory_order_relaxed);
  477. // exit barrier (fill seq-cst fence)
  478. atomic_fetch_add_explicit(&tp->n_barrier_passed, 1, memory_order_seq_cst);
  479. return;
  480. }
  481. // wait for other threads
  482. while (atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed) == n_passed) {
  483. ggml_thread_cpu_relax();
  484. }
  485. // exit barrier (full seq-cst fence)
  486. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  487. #ifdef GGML_TSAN_ENABLED
  488. atomic_fetch_add_explicit(&tp->n_barrier_passed, 0, memory_order_seq_cst);
  489. #else
  490. atomic_thread_fence(memory_order_seq_cst);
  491. #endif
  492. #endif
  493. }
  494. #if defined(__gnu_linux__)
  495. static cpu_set_t ggml_get_numa_affinity(void) {
  496. cpu_set_t cpuset;
  497. pthread_t thread;
  498. thread = pthread_self();
  499. CPU_ZERO(&cpuset);
  500. pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
  501. return cpuset;
  502. }
  503. #else
  504. static uint32_t ggml_get_numa_affinity(void) {
  505. return 0; // no NUMA support
  506. }
  507. #endif
  508. void ggml_numa_init(enum ggml_numa_strategy numa_flag) {
  509. if (g_state.numa.n_nodes > 0) {
  510. fprintf(stderr, "ggml_numa_init: NUMA already initialized\n");
  511. return;
  512. }
  513. #if defined(__gnu_linux__)
  514. struct stat st;
  515. char path[256];
  516. int rv;
  517. // set numa scheme
  518. g_state.numa.numa_strategy = numa_flag;
  519. GGML_PRINT_DEBUG("numa strategy %u\n",g_state.numa.numa_strategy);
  520. g_state.numa.cpuset = ggml_get_numa_affinity();
  521. // enumerate nodes
  522. while (g_state.numa.n_nodes < GGML_NUMA_MAX_NODES) {
  523. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u", g_state.numa.n_nodes);
  524. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  525. if (stat(path, &st) != 0) { break; }
  526. ++g_state.numa.n_nodes;
  527. }
  528. // enumerate CPUs
  529. while (g_state.numa.total_cpus < GGML_NUMA_MAX_CPUS) {
  530. rv = snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u", g_state.numa.total_cpus);
  531. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  532. if (stat(path, &st) != 0) { break; }
  533. ++g_state.numa.total_cpus;
  534. }
  535. GGML_PRINT_DEBUG("found %u numa nodes, %u CPUs\n", g_state.numa.n_nodes, g_state.numa.total_cpus);
  536. // figure out which node we're on
  537. uint current_cpu;
  538. int getcpu_ret = 0;
  539. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 33) || defined(__COSMOPOLITAN__)
  540. getcpu_ret = getcpu(&current_cpu, &g_state.numa.current_node);
  541. #else
  542. // old glibc doesn't have a wrapper for this call. Fall back on direct syscall
  543. # if !defined(SYS_getcpu) && defined(SYS_get_cpu)
  544. # define SYS_getcpu SYS_get_cpu // some older glibc versions use this name
  545. # endif
  546. getcpu_ret = syscall(SYS_getcpu, &current_cpu, &g_state.numa.current_node);
  547. #endif
  548. if (g_state.numa.n_nodes < 1 || g_state.numa.total_cpus < 1 || getcpu_ret != 0) {
  549. g_state.numa.n_nodes = 0;
  550. return;
  551. }
  552. GGML_PRINT_DEBUG("found our process on numa node %u, CPU %u\n", g_state.numa.current_node, current_cpu);
  553. for (uint32_t n = 0; n < g_state.numa.n_nodes; ++n) {
  554. struct ggml_numa_node * node = &g_state.numa.nodes[n];
  555. GGML_PRINT_DEBUG("CPUs on node %u:", n);
  556. node->n_cpus = 0;
  557. for (uint32_t c = 0; c < g_state.numa.total_cpus; ++c) {
  558. rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u/cpu%u", n, c);
  559. GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path));
  560. if (stat(path, &st) == 0) {
  561. node->cpus[node->n_cpus++] = c;
  562. GGML_PRINT_DEBUG(" %u", c);
  563. }
  564. }
  565. GGML_PRINT_DEBUG("\n");
  566. }
  567. if (ggml_is_numa()) {
  568. FILE *fptr = fopen("/proc/sys/kernel/numa_balancing", "r");
  569. if (fptr != NULL) {
  570. char buf[42];
  571. if (fgets(buf, sizeof(buf), fptr) && strncmp(buf, "0\n", sizeof(buf)) != 0) {
  572. GGML_LOG_WARN("/proc/sys/kernel/numa_balancing is enabled, this has been observed to impair performance\n");
  573. }
  574. fclose(fptr);
  575. }
  576. }
  577. #else
  578. UNUSED(numa_flag);
  579. // TODO
  580. #endif
  581. }
  582. bool ggml_is_numa(void) {
  583. return g_state.numa.n_nodes > 1;
  584. }
  585. #if defined(__ARM_ARCH)
  586. #if defined(__linux__) && defined(__aarch64__)
  587. #include <sys/auxv.h>
  588. #elif defined(__APPLE__)
  589. #include <sys/sysctl.h>
  590. #endif
  591. #if !defined(HWCAP2_I8MM)
  592. #define HWCAP2_I8MM (1 << 13)
  593. #endif
  594. #if !defined(HWCAP2_SME)
  595. #define HWCAP2_SME (1 << 23)
  596. #endif
  597. static void ggml_init_arm_arch_features(void) {
  598. #if defined(__linux__) && defined(__aarch64__)
  599. uint32_t hwcap = getauxval(AT_HWCAP);
  600. uint32_t hwcap2 = getauxval(AT_HWCAP2);
  601. ggml_arm_arch_features.has_neon = !!(hwcap & HWCAP_ASIMD);
  602. ggml_arm_arch_features.has_dotprod = !!(hwcap & HWCAP_ASIMDDP);
  603. ggml_arm_arch_features.has_i8mm = !!(hwcap2 & HWCAP2_I8MM);
  604. ggml_arm_arch_features.has_sve = !!(hwcap & HWCAP_SVE);
  605. ggml_arm_arch_features.has_sme = !!(hwcap2 & HWCAP2_SME);
  606. #if defined(__ARM_FEATURE_SVE)
  607. ggml_arm_arch_features.sve_cnt = PR_SVE_VL_LEN_MASK & prctl(PR_SVE_GET_VL);
  608. #endif
  609. #elif defined(__APPLE__)
  610. int oldp = 0;
  611. size_t size = sizeof(oldp);
  612. if (sysctlbyname("hw.optional.AdvSIMD", &oldp, &size, NULL, 0) != 0) {
  613. oldp = 0;
  614. }
  615. ggml_arm_arch_features.has_neon = oldp;
  616. if (sysctlbyname("hw.optional.arm.FEAT_DotProd", &oldp, &size, NULL, 0) != 0) {
  617. oldp = 0;
  618. }
  619. ggml_arm_arch_features.has_dotprod = oldp;
  620. if (sysctlbyname("hw.optional.arm.FEAT_I8MM", &oldp, &size, NULL, 0) != 0) {
  621. oldp = 0;
  622. }
  623. ggml_arm_arch_features.has_i8mm = oldp;
  624. if (sysctlbyname("hw.optional.arm.FEAT_SME", &oldp, &size, NULL, 0) != 0) {
  625. oldp = 0;
  626. }
  627. ggml_arm_arch_features.has_sme = oldp;
  628. ggml_arm_arch_features.has_sve = 0;
  629. ggml_arm_arch_features.sve_cnt = 0;
  630. #else
  631. // Run-time CPU feature detection not implemented for this platform, fallback to compile time
  632. #if defined(__ARM_NEON)
  633. ggml_arm_arch_features.has_neon = 1;
  634. #else
  635. ggml_arm_arch_features.has_neon = 0;
  636. #endif
  637. #if defined(__ARM_FEATURE_MATMUL_INT8)
  638. ggml_arm_arch_features.has_i8mm = 1;
  639. #else
  640. ggml_arm_arch_features.has_i8mm = 0;
  641. #endif
  642. #if defined(__ARM_FEATURE_SVE)
  643. ggml_arm_arch_features.has_sve = 1;
  644. ggml_arm_arch_features.sve_cnt = 16;
  645. #else
  646. ggml_arm_arch_features.has_sve = 0;
  647. ggml_arm_arch_features.sve_cnt = 0;
  648. #endif
  649. #if defined(__ARM_FEATURE_SME) || defined(__ARM_FEATURE_SME2)
  650. ggml_arm_arch_features.has_sme = 1;
  651. #else
  652. ggml_arm_arch_features.has_sme = 0;
  653. #endif
  654. #endif
  655. }
  656. #endif
  657. struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) {
  658. GGML_ASSERT(!ggml_get_no_alloc(ctx));
  659. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1);
  660. ggml_set_i32(result, value);
  661. return result;
  662. }
  663. struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) {
  664. GGML_ASSERT(!ggml_get_no_alloc(ctx));
  665. struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  666. ggml_set_f32(result, value);
  667. return result;
  668. }
  669. struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) {
  670. const int n = ggml_nrows(tensor);
  671. const int nc = tensor->ne[0];
  672. const size_t n1 = tensor->nb[1];
  673. char * const data = tensor->data;
  674. switch (tensor->type) {
  675. case GGML_TYPE_I8:
  676. {
  677. assert(tensor->nb[0] == sizeof(int8_t));
  678. for (int i = 0; i < n; i++) {
  679. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  680. }
  681. } break;
  682. case GGML_TYPE_I16:
  683. {
  684. assert(tensor->nb[0] == sizeof(int16_t));
  685. for (int i = 0; i < n; i++) {
  686. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  687. }
  688. } break;
  689. case GGML_TYPE_I32:
  690. {
  691. assert(tensor->nb[0] == sizeof(int32_t));
  692. for (int i = 0; i < n; i++) {
  693. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  694. }
  695. } break;
  696. case GGML_TYPE_F16:
  697. {
  698. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  699. for (int i = 0; i < n; i++) {
  700. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  701. }
  702. } break;
  703. case GGML_TYPE_BF16:
  704. {
  705. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  706. for (int i = 0; i < n; i++) {
  707. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  708. }
  709. } break;
  710. case GGML_TYPE_F32:
  711. {
  712. assert(tensor->nb[0] == sizeof(float));
  713. for (int i = 0; i < n; i++) {
  714. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  715. }
  716. } break;
  717. default:
  718. {
  719. GGML_ABORT("fatal error");
  720. }
  721. }
  722. return tensor;
  723. }
  724. struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) {
  725. const int n = ggml_nrows(tensor);
  726. const int nc = tensor->ne[0];
  727. const size_t n1 = tensor->nb[1];
  728. char * const data = tensor->data;
  729. switch (tensor->type) {
  730. case GGML_TYPE_I8:
  731. {
  732. assert(tensor->nb[0] == sizeof(int8_t));
  733. for (int i = 0; i < n; i++) {
  734. ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value);
  735. }
  736. } break;
  737. case GGML_TYPE_I16:
  738. {
  739. assert(tensor->nb[0] == sizeof(int16_t));
  740. for (int i = 0; i < n; i++) {
  741. ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value);
  742. }
  743. } break;
  744. case GGML_TYPE_I32:
  745. {
  746. assert(tensor->nb[0] == sizeof(int32_t));
  747. for (int i = 0; i < n; i++) {
  748. ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value);
  749. }
  750. } break;
  751. case GGML_TYPE_F16:
  752. {
  753. assert(tensor->nb[0] == sizeof(ggml_fp16_t));
  754. for (int i = 0; i < n; i++) {
  755. ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_FP32_TO_FP16(value));
  756. }
  757. } break;
  758. case GGML_TYPE_BF16:
  759. {
  760. assert(tensor->nb[0] == sizeof(ggml_bf16_t));
  761. for (int i = 0; i < n; i++) {
  762. ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value));
  763. }
  764. } break;
  765. case GGML_TYPE_F32:
  766. {
  767. assert(tensor->nb[0] == sizeof(float));
  768. for (int i = 0; i < n; i++) {
  769. ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
  770. }
  771. } break;
  772. default:
  773. {
  774. GGML_ABORT("fatal error");
  775. }
  776. }
  777. return tensor;
  778. }
  779. int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) {
  780. if (!ggml_is_contiguous(tensor)) {
  781. int64_t id[4] = { 0, 0, 0, 0 };
  782. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  783. return ggml_get_i32_nd(tensor, id[0], id[1], id[2], id[3]);
  784. }
  785. switch (tensor->type) {
  786. case GGML_TYPE_I8:
  787. {
  788. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  789. return ((int8_t *)(tensor->data))[i];
  790. }
  791. case GGML_TYPE_I16:
  792. {
  793. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  794. return ((int16_t *)(tensor->data))[i];
  795. }
  796. case GGML_TYPE_I32:
  797. {
  798. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  799. return ((int32_t *)(tensor->data))[i];
  800. }
  801. case GGML_TYPE_F16:
  802. {
  803. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  804. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  805. }
  806. case GGML_TYPE_BF16:
  807. {
  808. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  809. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  810. }
  811. case GGML_TYPE_F32:
  812. {
  813. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  814. return ((float *)(tensor->data))[i];
  815. }
  816. default:
  817. {
  818. GGML_ABORT("fatal error");
  819. }
  820. }
  821. }
  822. void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) {
  823. if (!ggml_is_contiguous(tensor)) {
  824. int64_t id[4] = { 0, 0, 0, 0 };
  825. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  826. ggml_set_i32_nd(tensor, id[0], id[1], id[2], id[3], value);
  827. return;
  828. }
  829. switch (tensor->type) {
  830. case GGML_TYPE_I8:
  831. {
  832. GGML_ASSERT(tensor->nb[0] == sizeof(int8_t));
  833. ((int8_t *)(tensor->data))[i] = value;
  834. } break;
  835. case GGML_TYPE_I16:
  836. {
  837. GGML_ASSERT(tensor->nb[0] == sizeof(int16_t));
  838. ((int16_t *)(tensor->data))[i] = value;
  839. } break;
  840. case GGML_TYPE_I32:
  841. {
  842. GGML_ASSERT(tensor->nb[0] == sizeof(int32_t));
  843. ((int32_t *)(tensor->data))[i] = value;
  844. } break;
  845. case GGML_TYPE_F16:
  846. {
  847. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t));
  848. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  849. } break;
  850. case GGML_TYPE_BF16:
  851. {
  852. GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t));
  853. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  854. } break;
  855. case GGML_TYPE_F32:
  856. {
  857. GGML_ASSERT(tensor->nb[0] == sizeof(float));
  858. ((float *)(tensor->data))[i] = value;
  859. } break;
  860. default:
  861. {
  862. GGML_ABORT("fatal error");
  863. }
  864. }
  865. }
  866. int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  867. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  868. switch (tensor->type) {
  869. case GGML_TYPE_I8:
  870. return ((int8_t *) data)[0];
  871. case GGML_TYPE_I16:
  872. return ((int16_t *) data)[0];
  873. case GGML_TYPE_I32:
  874. return ((int32_t *) data)[0];
  875. case GGML_TYPE_F16:
  876. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  877. case GGML_TYPE_BF16:
  878. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  879. case GGML_TYPE_F32:
  880. return ((float *) data)[0];
  881. default:
  882. GGML_ABORT("fatal error");
  883. }
  884. }
  885. void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value) {
  886. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  887. switch (tensor->type) {
  888. case GGML_TYPE_I8:
  889. {
  890. ((int8_t *)(data))[0] = value;
  891. } break;
  892. case GGML_TYPE_I16:
  893. {
  894. ((int16_t *)(data))[0] = value;
  895. } break;
  896. case GGML_TYPE_I32:
  897. {
  898. ((int32_t *)(data))[0] = value;
  899. } break;
  900. case GGML_TYPE_F16:
  901. {
  902. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  903. } break;
  904. case GGML_TYPE_BF16:
  905. {
  906. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  907. } break;
  908. case GGML_TYPE_F32:
  909. {
  910. ((float *)(data))[0] = value;
  911. } break;
  912. default:
  913. {
  914. GGML_ABORT("fatal error");
  915. }
  916. }
  917. }
  918. float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) {
  919. if (!ggml_is_contiguous(tensor)) {
  920. int64_t id[4] = { 0, 0, 0, 0 };
  921. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  922. return ggml_get_f32_nd(tensor, id[0], id[1], id[2], id[3]);
  923. }
  924. switch (tensor->type) {
  925. case GGML_TYPE_I8:
  926. {
  927. return ((int8_t *)(tensor->data))[i];
  928. }
  929. case GGML_TYPE_I16:
  930. {
  931. return ((int16_t *)(tensor->data))[i];
  932. }
  933. case GGML_TYPE_I32:
  934. {
  935. return ((int32_t *)(tensor->data))[i];
  936. }
  937. case GGML_TYPE_F16:
  938. {
  939. return GGML_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]);
  940. }
  941. case GGML_TYPE_BF16:
  942. {
  943. return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]);
  944. }
  945. case GGML_TYPE_F32:
  946. {
  947. return ((float *)(tensor->data))[i];
  948. }
  949. default:
  950. {
  951. GGML_ABORT("fatal error");
  952. }
  953. }
  954. }
  955. void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) {
  956. if (!ggml_is_contiguous(tensor)) {
  957. int64_t id[4] = { 0, 0, 0, 0 };
  958. ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]);
  959. ggml_set_f32_nd(tensor, id[0], id[1], id[2], id[3], value);
  960. return;
  961. }
  962. switch (tensor->type) {
  963. case GGML_TYPE_I8:
  964. {
  965. ((int8_t *)(tensor->data))[i] = value;
  966. } break;
  967. case GGML_TYPE_I16:
  968. {
  969. ((int16_t *)(tensor->data))[i] = value;
  970. } break;
  971. case GGML_TYPE_I32:
  972. {
  973. ((int32_t *)(tensor->data))[i] = value;
  974. } break;
  975. case GGML_TYPE_F16:
  976. {
  977. ((ggml_fp16_t *)(tensor->data))[i] = GGML_FP32_TO_FP16(value);
  978. } break;
  979. case GGML_TYPE_BF16:
  980. {
  981. ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value);
  982. } break;
  983. case GGML_TYPE_F32:
  984. {
  985. ((float *)(tensor->data))[i] = value;
  986. } break;
  987. default:
  988. {
  989. GGML_ABORT("fatal error");
  990. }
  991. }
  992. }
  993. float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  994. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  995. switch (tensor->type) {
  996. case GGML_TYPE_I8:
  997. return ((int8_t *) data)[0];
  998. case GGML_TYPE_I16:
  999. return ((int16_t *) data)[0];
  1000. case GGML_TYPE_I32:
  1001. return ((int32_t *) data)[0];
  1002. case GGML_TYPE_F16:
  1003. return GGML_FP16_TO_FP32(((ggml_fp16_t *) data)[0]);
  1004. case GGML_TYPE_BF16:
  1005. return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]);
  1006. case GGML_TYPE_F32:
  1007. return ((float *) data)[0];
  1008. default:
  1009. GGML_ABORT("fatal error");
  1010. }
  1011. }
  1012. void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value) {
  1013. void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3];
  1014. switch (tensor->type) {
  1015. case GGML_TYPE_I8:
  1016. {
  1017. ((int8_t *)(data))[0] = value;
  1018. } break;
  1019. case GGML_TYPE_I16:
  1020. {
  1021. ((int16_t *)(data))[0] = value;
  1022. } break;
  1023. case GGML_TYPE_I32:
  1024. {
  1025. ((int32_t *)(data))[0] = value;
  1026. } break;
  1027. case GGML_TYPE_F16:
  1028. {
  1029. ((ggml_fp16_t *)(data))[0] = GGML_FP32_TO_FP16(value);
  1030. } break;
  1031. case GGML_TYPE_BF16:
  1032. {
  1033. ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value);
  1034. } break;
  1035. case GGML_TYPE_F32:
  1036. {
  1037. ((float *)(data))[0] = value;
  1038. } break;
  1039. default:
  1040. {
  1041. GGML_ABORT("fatal error");
  1042. }
  1043. }
  1044. }
  1045. ////////////////////////////////////////////////////////////////////////////////
  1046. // ggml_compute_forward_mul_mat
  1047. static void ggml_compute_forward_mul_mat_one_chunk(
  1048. const struct ggml_compute_params * params,
  1049. struct ggml_tensor * dst,
  1050. const enum ggml_type type,
  1051. const int64_t num_rows_per_vec_dot,
  1052. const int64_t ir0_start,
  1053. const int64_t ir0_end,
  1054. const int64_t ir1_start,
  1055. const int64_t ir1_end) {
  1056. const struct ggml_tensor * src0 = dst->src[0];
  1057. const struct ggml_tensor * src1 = dst->src[1];
  1058. GGML_TENSOR_BINARY_OP_LOCALS
  1059. const bool src1_cont = ggml_is_contiguous(src1);
  1060. ggml_vec_dot_t const vec_dot = type_traits_cpu[type].vec_dot;
  1061. enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type;
  1062. // broadcast factors
  1063. const int64_t r2 = ne12 / ne02;
  1064. const int64_t r3 = ne13 / ne03;
  1065. //printf("ir0_start = %6lld, ir0_end = %6lld, ir1_start = %6lld, ir1_end = %6lld\n", ir0_start, ir0_end, ir1_start, ir1_end);
  1066. // threads with no work simply yield (not sure if it helps)
  1067. if (ir0_start >= ir0_end || ir1_start >= ir1_end) {
  1068. return;
  1069. }
  1070. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  1071. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  1072. assert(ne12 % ne02 == 0);
  1073. assert(ne13 % ne03 == 0);
  1074. // block-tiling attempt
  1075. const int64_t blck_0 = 16;
  1076. const int64_t blck_1 = 16;
  1077. const size_t src1_col_stride = src1_cont || src1->type != vec_dot_type ? row_size : nb11;
  1078. // attempt to reduce false-sharing (does not seem to make a difference)
  1079. // 16 * 2, accounting for mmla kernels
  1080. float tmp[32];
  1081. for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) {
  1082. for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) {
  1083. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) {
  1084. const int64_t i13 = (ir1 / (ne12 * ne1));
  1085. const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1;
  1086. const int64_t i11 = (ir1 - i13 * ne12 * ne1 - i12 * ne1);
  1087. // broadcast src0 into src1
  1088. const int64_t i03 = i13 / r3;
  1089. const int64_t i02 = i12 / r2;
  1090. const int64_t i1 = i11;
  1091. const int64_t i2 = i12;
  1092. const int64_t i3 = i13;
  1093. const char * src0_row = (const char*)src0->data + (0 + i02 * nb02 + i03 * nb03);
  1094. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  1095. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  1096. // the original src1 data pointer, so we should index using the indices directly
  1097. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  1098. const char * src1_col = (const char*)wdata +
  1099. (src1_cont || src1->type != vec_dot_type
  1100. ? (i11 + i12 * ne11 + i13 * ne12 * ne11) * row_size
  1101. : (i11 * nb11 + i12 * nb12 + i13 * nb13));
  1102. float * dst_col = (float*)((char*)dst->data + (i1 * nb1 + i2 * nb2 + i3 * nb3));
  1103. //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) {
  1104. // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col);
  1105. //}
  1106. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) {
  1107. vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot);
  1108. }
  1109. for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) {
  1110. memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float));
  1111. }
  1112. }
  1113. }
  1114. }
  1115. }
  1116. static void ggml_compute_forward_mul_mat(
  1117. const struct ggml_compute_params * params,
  1118. struct ggml_tensor * dst) {
  1119. const struct ggml_tensor * src0 = dst->src[0];
  1120. const struct ggml_tensor * src1 = dst->src[1];
  1121. GGML_TENSOR_BINARY_OP_LOCALS
  1122. const int ith = params->ith;
  1123. const int nth = params->nth;
  1124. enum ggml_type const vec_dot_type = type_traits_cpu[src0->type].vec_dot_type;
  1125. ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
  1126. int64_t const vec_dot_num_rows = type_traits_cpu[src0->type].nrows;
  1127. GGML_ASSERT(ne0 == ne01);
  1128. GGML_ASSERT(ne1 == ne11);
  1129. GGML_ASSERT(ne2 == ne12);
  1130. GGML_ASSERT(ne3 == ne13);
  1131. // we don't support permuted src0 or src1
  1132. GGML_ASSERT(nb00 == ggml_type_size(src0->type));
  1133. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  1134. // dst cannot be transposed or permuted
  1135. GGML_ASSERT(nb0 == sizeof(float));
  1136. GGML_ASSERT(nb0 <= nb1);
  1137. GGML_ASSERT(nb1 <= nb2);
  1138. GGML_ASSERT(nb2 <= nb3);
  1139. // nb01 >= nb00 - src0 is not transposed
  1140. // compute by src0 rows
  1141. // TODO: extract to "extra_op"
  1142. #if GGML_USE_LLAMAFILE
  1143. // broadcast factors
  1144. const int64_t r2 = ne12 / ne02;
  1145. const int64_t r3 = ne13 / ne03;
  1146. const bool src1_cont = ggml_is_contiguous(src1);
  1147. if (src1_cont) {
  1148. for (int64_t i13 = 0; i13 < ne13; i13++)
  1149. for (int64_t i12 = 0; i12 < ne12; i12++)
  1150. if (!llamafile_sgemm(params,
  1151. ne01, ne11, ne00/ggml_blck_size(src0->type),
  1152. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  1153. nb01/ggml_type_size(src0->type),
  1154. (const char *)src1->data + i12*nb12 + i13*nb13,
  1155. nb11/ggml_type_size(src1->type),
  1156. (char *)dst->data + i12*nb2 + i13*nb3,
  1157. nb1/ggml_type_size(dst->type),
  1158. src0->type,
  1159. src1->type,
  1160. dst->type))
  1161. goto UseGgmlGemm1;
  1162. return;
  1163. }
  1164. UseGgmlGemm1:;
  1165. #endif
  1166. if (src1->type != vec_dot_type) {
  1167. char * wdata = params->wdata;
  1168. const size_t nbw0 = ggml_type_size(vec_dot_type);
  1169. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  1170. const size_t nbw2 = nbw1*ne11;
  1171. const size_t nbw3 = nbw2*ne12;
  1172. assert(params->wsize >= ne13*nbw3);
  1173. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  1174. #if 0
  1175. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  1176. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  1177. for (int64_t i11 = ith; i11 < ne11; i11 += nth) {
  1178. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  1179. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  1180. ne10);
  1181. }
  1182. }
  1183. }
  1184. #else
  1185. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  1186. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  1187. for (int64_t i11 = 0; i11 < ne11; ++i11) {
  1188. size_t bs = ggml_blck_size(vec_dot_type);
  1189. int64_t ne10_block_start = (ith * ne10/bs) / nth;
  1190. int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
  1191. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
  1192. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
  1193. (ne10_block_end - ne10_block_start) * bs);
  1194. }
  1195. }
  1196. }
  1197. #endif
  1198. }
  1199. if (ith == 0) {
  1200. // Every thread starts at ith, so the first unprocessed chunk is nth. This save a bit of coordination right at the start.
  1201. atomic_store_explicit(&params->threadpool->current_chunk, nth, memory_order_relaxed);
  1202. }
  1203. ggml_barrier(params->threadpool);
  1204. #if GGML_USE_LLAMAFILE
  1205. if (src1->type != vec_dot_type) {
  1206. const void* wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  1207. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  1208. for (int64_t i13 = 0; i13 < ne13; i13++)
  1209. for (int64_t i12 = 0; i12 < ne12; i12++)
  1210. if (!llamafile_sgemm(params,
  1211. ne01, ne11, ne00/ggml_blck_size(src0->type),
  1212. (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03,
  1213. nb01/ggml_type_size(src0->type),
  1214. (const char *)wdata + (i12*ne11 + i13*ne12*ne11)*row_size,
  1215. row_size/ggml_type_size(vec_dot_type),
  1216. (char *)dst->data + i12*nb2 + i13*nb3,
  1217. nb1/ggml_type_size(dst->type),
  1218. src0->type,
  1219. vec_dot_type,
  1220. dst->type))
  1221. goto UseGgmlGemm2;
  1222. return;
  1223. }
  1224. UseGgmlGemm2:;
  1225. #endif
  1226. // This is the size of the first dimension of the result, so we can iterate that way. (see the ASSERT above, these are the same numbers)
  1227. const int64_t nr0 = ne0;
  1228. // This is the size of the rest of the dimensions of the result
  1229. const int64_t nr1 = ne1 * ne2 * ne3;
  1230. // Now select a reasonable chunk size.
  1231. int chunk_size = 16;
  1232. // We need to step up the size if it's small
  1233. if (nr0 == 1 || nr1 == 1) {
  1234. chunk_size = 64;
  1235. }
  1236. // distribute the work across the inner or outer loop based on which one is larger
  1237. // The number of chunks in the 0/1 dim.
  1238. // CEIL(nr0/chunk_size)
  1239. int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size;
  1240. int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size;
  1241. // If the chunking is poor for the number of threads on this setup, scrap the whole plan. Re-chunk it by thread.
  1242. // Also, chunking by thread was measured to have perform better on NUMA systems. See https://github.com/ggml-org/llama.cpp/pull/6915
  1243. // In theory, chunking should be just as useful on NUMA and non NUMA systems, but testing disagreed with that.
  1244. if (nchunk0 * nchunk1 < nth * 4 || ggml_is_numa()) {
  1245. // distribute the thread work across the inner or outer loop based on which one is larger
  1246. nchunk0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows
  1247. nchunk1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows
  1248. }
  1249. // The number of elements in each chunk
  1250. const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0;
  1251. const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1;
  1252. // The first chunk comes from our thread_id, the rest will get auto-assigned.
  1253. int current_chunk = ith;
  1254. while (current_chunk < nchunk0 * nchunk1) {
  1255. const int64_t ith0 = current_chunk % nchunk0;
  1256. const int64_t ith1 = current_chunk / nchunk0;
  1257. const int64_t ir0_start = dr0 * ith0;
  1258. const int64_t ir0_end = MIN(ir0_start + dr0, nr0);
  1259. const int64_t ir1_start = dr1 * ith1;
  1260. const int64_t ir1_end = MIN(ir1_start + dr1, nr1);
  1261. // dot kernels can handle 1 row and col at a time, but mmla kernels can process 2 rows and cols
  1262. int64_t num_rows_per_vec_dot = vec_dot_num_rows;
  1263. // these checks are needed to avoid crossing dim1 boundaries
  1264. // can be optimized, but the logic would become more complicated, so keeping it like this for simplicity
  1265. if ((nr0 % 2 != 0) || (ne11 % 2 != 0) || ((ir0_end - ir0_start) % 2 != 0) || ((ir1_end - ir1_start) % 2 != 0)) {
  1266. num_rows_per_vec_dot = 1;
  1267. }
  1268. ggml_compute_forward_mul_mat_one_chunk(params, dst, src0->type, num_rows_per_vec_dot, ir0_start, ir0_end, ir1_start, ir1_end);
  1269. if (nth >= nchunk0 * nchunk1) {
  1270. break;
  1271. }
  1272. current_chunk = atomic_fetch_add_explicit(&params->threadpool->current_chunk, 1, memory_order_relaxed);
  1273. }
  1274. }
  1275. // ggml_compute_forward_mul_mat_id
  1276. #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id)*ids->ne[0]*ids->ne[1] + (i1)]
  1277. struct mmid_row_mapping {
  1278. int32_t i1;
  1279. int32_t i2;
  1280. };
  1281. static void ggml_compute_forward_mul_mat_id_one_chunk(
  1282. struct ggml_tensor * dst,
  1283. const struct ggml_tensor * src0,
  1284. const struct ggml_tensor * src1,
  1285. const struct ggml_tensor * ids,
  1286. const int64_t cur_a,
  1287. const int64_t ir0_start,
  1288. const int64_t ir0_end,
  1289. const int64_t ir1_start,
  1290. const int64_t ir1_end,
  1291. const char * src0_cur,
  1292. const struct mmid_row_mapping * matrix_rows,
  1293. const size_t row_size,
  1294. const bool src1_cont,
  1295. const void * wdata) {
  1296. GGML_TENSOR_BINARY_OP_LOCALS
  1297. const enum ggml_type type = src0->type;
  1298. ggml_vec_dot_t const vec_dot = type_traits_cpu[type].vec_dot;
  1299. enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type;
  1300. const int64_t blck_0 = 16;
  1301. const int64_t blck_1 = 16;
  1302. float tmp[16];
  1303. for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) {
  1304. for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) {
  1305. for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ++ir1) {
  1306. const int64_t _i12 = ir1; // logical row index for this expert
  1307. struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, _i12);
  1308. const int id = row_mapping.i1; // selected expert index
  1309. const int64_t i11 = id % ne11;
  1310. const int64_t i12 = row_mapping.i2; // row index in src1
  1311. const int64_t i1 = id; // selected expert index
  1312. const int64_t i2 = i12; // row
  1313. // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides
  1314. // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using
  1315. // the original src1 data pointer, so we should index using the indices directly
  1316. // TODO: this is a bit of a hack, we should probably have a better way to handle this
  1317. const char * src1_col = (const char *) wdata +
  1318. (src1_cont || src1->type != vec_dot_type
  1319. ? (i11 + i12*ne11)*row_size
  1320. : (i11*nb11 + i12*nb12));
  1321. float * dst_col = (float *) ((char *) dst->data + (i1*nb1 + i2*nb2));
  1322. for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) {
  1323. vec_dot(ne00, &tmp[ir0 - iir0], 0, src0_cur + ir0*nb01, 0, src1_col, 0, 1);
  1324. }
  1325. memcpy(&dst_col[iir0], tmp, (MIN(iir0 + blck_0, ir0_end) - iir0)*sizeof(float));
  1326. }
  1327. }
  1328. }
  1329. }
  1330. static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
  1331. void * ptr = *p;
  1332. ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
  1333. *p = (void *) ((char *) ptr + size);
  1334. return ptr;
  1335. }
  1336. static void ggml_compute_forward_mul_mat_id(
  1337. const struct ggml_compute_params * params,
  1338. struct ggml_tensor * dst) {
  1339. const struct ggml_tensor * src0 = dst->src[0];
  1340. const struct ggml_tensor * src1 = dst->src[1];
  1341. const struct ggml_tensor * ids = dst->src[2];
  1342. GGML_TENSOR_BINARY_OP_LOCALS
  1343. const int ith = params->ith;
  1344. const int nth = params->nth;
  1345. const enum ggml_type type = src0->type;
  1346. const bool src1_cont = ggml_is_contiguous(src1);
  1347. enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type;
  1348. ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
  1349. // we don't support permuted src0 or src1
  1350. GGML_ASSERT(nb00 == ggml_type_size(type));
  1351. GGML_ASSERT(nb10 == ggml_type_size(src1->type));
  1352. // dst cannot be transposed or permuted
  1353. GGML_ASSERT(nb0 == sizeof(float));
  1354. GGML_ASSERT(nb0 <= nb1);
  1355. GGML_ASSERT(nb1 <= nb2);
  1356. GGML_ASSERT(nb2 <= nb3);
  1357. // row groups
  1358. const int n_ids = ids->ne[0]; // n_expert_used
  1359. const int n_as = ne02; // n_expert
  1360. void * wdata_cur = params->wdata;
  1361. if (src1->type != vec_dot_type) {
  1362. incr_ptr_aligned(&wdata_cur, ggml_row_size(vec_dot_type, ggml_nelements(src1)), sizeof(int64_t));
  1363. }
  1364. int64_t * matrix_row_counts = // [n_as]
  1365. incr_ptr_aligned(&wdata_cur, n_as*sizeof(int64_t), sizeof(int64_t));
  1366. struct mmid_row_mapping * matrix_rows = // [n_as][ids->ne[0]*ids->ne[1]]
  1367. incr_ptr_aligned(&wdata_cur, n_as*ids->ne[0]*ids->ne[1]*sizeof(struct mmid_row_mapping), sizeof(int64_t));
  1368. char (*atomic_current_chunk)[CACHE_LINE_SIZE] = // [n_as]
  1369. incr_ptr_aligned(&wdata_cur, CACHE_LINE_SIZE * n_as, CACHE_LINE_SIZE);
  1370. GGML_ASSERT(params->wsize >= (size_t)((char *) wdata_cur - (char *) params->wdata));
  1371. if (src1->type != vec_dot_type) {
  1372. char * wdata = params->wdata;
  1373. const size_t nbw0 = ggml_type_size(vec_dot_type);
  1374. const size_t nbw1 = ggml_row_size(vec_dot_type, ne10);
  1375. const size_t nbw2 = nbw1*ne11;
  1376. const size_t nbw3 = nbw2*ne12;
  1377. assert(params->wsize >= ne13*nbw3);
  1378. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  1379. #if 0
  1380. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  1381. for (int64_t i12 = ith; i12 < ne12; i12 += nth) {
  1382. for (int64_t i11 = 0; i11 < ne11; ++i11) {
  1383. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11),
  1384. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1),
  1385. ne10);
  1386. }
  1387. }
  1388. }
  1389. #else
  1390. for (int64_t i13 = 0; i13 < ne13; ++i13) {
  1391. for (int64_t i12 = 0; i12 < ne12; ++i12) {
  1392. for (int64_t i11 = 0; i11 < ne11; ++i11) {
  1393. size_t bs = ggml_blck_size(vec_dot_type);
  1394. int64_t ne10_block_start = (ith * ne10/bs) / nth;
  1395. int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
  1396. from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
  1397. (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
  1398. (ne10_block_end - ne10_block_start) * bs);
  1399. }
  1400. }
  1401. }
  1402. #endif
  1403. }
  1404. if (ith == 0) {
  1405. // initialize matrix_row_counts
  1406. memset(matrix_row_counts, 0, n_as*sizeof(int64_t));
  1407. // group rows by src0 matrix
  1408. for (int64_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) {
  1409. for (int id = 0; id < n_ids; ++id) {
  1410. const int32_t i02 = *(const int32_t *) ((const char *) ids->data + iid1*ids->nb[1] + id*ids->nb[0]);
  1411. assert(i02 >= 0 && i02 < n_as);
  1412. MMID_MATRIX_ROW(i02, matrix_row_counts[i02]) = (struct mmid_row_mapping) {id, iid1};
  1413. matrix_row_counts[i02] += 1;
  1414. }
  1415. }
  1416. }
  1417. // reset current_chunk
  1418. for (int cur_a = ith; cur_a < n_as; cur_a += nth) {
  1419. atomic_int * current_chunk_ctr = (atomic_int *)(atomic_current_chunk + cur_a);
  1420. *current_chunk_ctr = nth;
  1421. }
  1422. ggml_barrier(params->threadpool);
  1423. for (int cur_a = 0; cur_a < n_as; ++cur_a) {
  1424. const int64_t cne1 = matrix_row_counts[cur_a];
  1425. if (cne1 == 0) {
  1426. continue;
  1427. }
  1428. const char * src0_cur = (const char *) src0->data + cur_a * nb02;
  1429. const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata;
  1430. const size_t row_size = ggml_row_size(vec_dot_type, ne10);
  1431. const int64_t nr0 = ne01;
  1432. const int64_t nr1 = cne1;
  1433. int chunk_size = 16;
  1434. if (nr0 == 1 || nr1 == 1) {
  1435. chunk_size = 64;
  1436. }
  1437. #if defined(__aarch64__)
  1438. // disable for ARM
  1439. const bool disable_chunking = true;
  1440. #else
  1441. // disable for NUMA
  1442. const bool disable_chunking = ggml_is_numa();
  1443. #endif // defined(__aarch64__)
  1444. int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size;
  1445. int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size;
  1446. if (nchunk0 * nchunk1 < nth * 4 || disable_chunking) {
  1447. nchunk0 = nr0 > nr1 ? nth : 1;
  1448. nchunk1 = nr0 > nr1 ? 1 : nth;
  1449. }
  1450. const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0;
  1451. const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1;
  1452. int current_chunk = ith;
  1453. atomic_int * current_chunk_ctr = (atomic_int *)(atomic_current_chunk + cur_a);
  1454. while (current_chunk < nchunk0 * nchunk1) {
  1455. const int64_t ith0 = current_chunk % nchunk0;
  1456. const int64_t ith1 = current_chunk / nchunk0;
  1457. const int64_t ir0_start = dr0 * ith0;
  1458. const int64_t ir0_end = MIN(ir0_start + dr0, nr0);
  1459. const int64_t ir1_start = dr1 * ith1;
  1460. const int64_t ir1_end = MIN(ir1_start + dr1, nr1);
  1461. ggml_compute_forward_mul_mat_id_one_chunk(
  1462. dst, src0, src1, ids, cur_a,
  1463. ir0_start, ir0_end, ir1_start, ir1_end,
  1464. src0_cur, matrix_rows, row_size, src1_cont, wdata
  1465. );
  1466. if (nth >= nchunk0 * nchunk1) {
  1467. break;
  1468. }
  1469. current_chunk = atomic_fetch_add_explicit(current_chunk_ctr, 1, memory_order_relaxed);
  1470. }
  1471. }
  1472. }
  1473. /////////////////////////////////
  1474. static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  1475. GGML_ASSERT(params);
  1476. if (tensor->op == GGML_OP_NONE || ggml_is_empty(tensor)) {
  1477. return;
  1478. }
  1479. // extra_buffer op?
  1480. if (ggml_cpu_extra_compute_forward(params, tensor)) {
  1481. return;
  1482. }
  1483. switch (tensor->op) {
  1484. case GGML_OP_DUP:
  1485. {
  1486. ggml_compute_forward_dup(params, tensor);
  1487. } break;
  1488. case GGML_OP_ADD:
  1489. {
  1490. ggml_compute_forward_add(params, tensor);
  1491. } break;
  1492. case GGML_OP_ADD1:
  1493. {
  1494. ggml_compute_forward_add1(params, tensor);
  1495. } break;
  1496. case GGML_OP_ACC:
  1497. {
  1498. ggml_compute_forward_acc(params, tensor);
  1499. } break;
  1500. case GGML_OP_SUB:
  1501. {
  1502. ggml_compute_forward_sub(params, tensor);
  1503. } break;
  1504. case GGML_OP_MUL:
  1505. {
  1506. ggml_compute_forward_mul(params, tensor);
  1507. } break;
  1508. case GGML_OP_DIV:
  1509. {
  1510. ggml_compute_forward_div(params, tensor);
  1511. } break;
  1512. case GGML_OP_SQR:
  1513. {
  1514. ggml_compute_forward_sqr(params, tensor);
  1515. } break;
  1516. case GGML_OP_SQRT:
  1517. {
  1518. ggml_compute_forward_sqrt(params, tensor);
  1519. } break;
  1520. case GGML_OP_LOG:
  1521. {
  1522. ggml_compute_forward_log(params, tensor);
  1523. } break;
  1524. case GGML_OP_SIN:
  1525. {
  1526. ggml_compute_forward_sin(params, tensor);
  1527. } break;
  1528. case GGML_OP_COS:
  1529. {
  1530. ggml_compute_forward_cos(params, tensor);
  1531. } break;
  1532. case GGML_OP_SUM:
  1533. {
  1534. ggml_compute_forward_sum(params, tensor);
  1535. } break;
  1536. case GGML_OP_SUM_ROWS:
  1537. {
  1538. ggml_compute_forward_sum_rows(params, tensor);
  1539. } break;
  1540. case GGML_OP_MEAN:
  1541. {
  1542. ggml_compute_forward_mean(params, tensor);
  1543. } break;
  1544. case GGML_OP_ARGMAX:
  1545. {
  1546. ggml_compute_forward_argmax(params, tensor);
  1547. } break;
  1548. case GGML_OP_COUNT_EQUAL:
  1549. {
  1550. ggml_compute_forward_count_equal(params, tensor);
  1551. } break;
  1552. case GGML_OP_REPEAT:
  1553. {
  1554. ggml_compute_forward_repeat(params, tensor);
  1555. } break;
  1556. case GGML_OP_REPEAT_BACK:
  1557. {
  1558. ggml_compute_forward_repeat_back(params, tensor);
  1559. } break;
  1560. case GGML_OP_CONCAT:
  1561. {
  1562. ggml_compute_forward_concat(params, tensor);
  1563. } break;
  1564. case GGML_OP_SILU_BACK:
  1565. {
  1566. ggml_compute_forward_silu_back(params, tensor);
  1567. } break;
  1568. case GGML_OP_NORM:
  1569. {
  1570. ggml_compute_forward_norm(params, tensor);
  1571. } break;
  1572. case GGML_OP_RMS_NORM:
  1573. {
  1574. ggml_compute_forward_rms_norm(params, tensor);
  1575. } break;
  1576. case GGML_OP_RMS_NORM_BACK:
  1577. {
  1578. ggml_compute_forward_rms_norm_back(params, tensor);
  1579. } break;
  1580. case GGML_OP_GROUP_NORM:
  1581. {
  1582. ggml_compute_forward_group_norm(params, tensor);
  1583. } break;
  1584. case GGML_OP_L2_NORM:
  1585. {
  1586. ggml_compute_forward_l2_norm(params, tensor);
  1587. } break;
  1588. case GGML_OP_MUL_MAT:
  1589. {
  1590. ggml_compute_forward_mul_mat(params, tensor);
  1591. } break;
  1592. case GGML_OP_MUL_MAT_ID:
  1593. {
  1594. ggml_compute_forward_mul_mat_id(params, tensor);
  1595. } break;
  1596. case GGML_OP_OUT_PROD:
  1597. {
  1598. ggml_compute_forward_out_prod(params, tensor);
  1599. } break;
  1600. case GGML_OP_SCALE:
  1601. {
  1602. ggml_compute_forward_scale(params, tensor);
  1603. } break;
  1604. case GGML_OP_SET:
  1605. {
  1606. ggml_compute_forward_set(params, tensor);
  1607. } break;
  1608. case GGML_OP_CPY:
  1609. {
  1610. ggml_compute_forward_cpy(params, tensor);
  1611. } break;
  1612. case GGML_OP_CONT:
  1613. {
  1614. ggml_compute_forward_cont(params, tensor);
  1615. } break;
  1616. case GGML_OP_RESHAPE:
  1617. {
  1618. ggml_compute_forward_reshape(params, tensor);
  1619. } break;
  1620. case GGML_OP_VIEW:
  1621. {
  1622. ggml_compute_forward_view(params, tensor);
  1623. } break;
  1624. case GGML_OP_PERMUTE:
  1625. {
  1626. ggml_compute_forward_permute(params, tensor);
  1627. } break;
  1628. case GGML_OP_TRANSPOSE:
  1629. {
  1630. ggml_compute_forward_transpose(params, tensor);
  1631. } break;
  1632. case GGML_OP_GET_ROWS:
  1633. {
  1634. ggml_compute_forward_get_rows(params, tensor);
  1635. } break;
  1636. case GGML_OP_GET_ROWS_BACK:
  1637. {
  1638. ggml_compute_forward_get_rows_back(params, tensor);
  1639. } break;
  1640. case GGML_OP_DIAG:
  1641. {
  1642. ggml_compute_forward_diag(params, tensor);
  1643. } break;
  1644. case GGML_OP_DIAG_MASK_INF:
  1645. {
  1646. ggml_compute_forward_diag_mask_inf(params, tensor);
  1647. } break;
  1648. case GGML_OP_DIAG_MASK_ZERO:
  1649. {
  1650. ggml_compute_forward_diag_mask_zero(params, tensor);
  1651. } break;
  1652. case GGML_OP_SOFT_MAX:
  1653. {
  1654. ggml_compute_forward_soft_max(params, tensor);
  1655. } break;
  1656. case GGML_OP_SOFT_MAX_BACK:
  1657. {
  1658. ggml_compute_forward_soft_max_ext_back(params, tensor);
  1659. } break;
  1660. case GGML_OP_ROPE:
  1661. {
  1662. ggml_compute_forward_rope(params, tensor);
  1663. } break;
  1664. case GGML_OP_ROPE_BACK:
  1665. {
  1666. ggml_compute_forward_rope_back(params, tensor);
  1667. } break;
  1668. case GGML_OP_CLAMP:
  1669. {
  1670. ggml_compute_forward_clamp(params, tensor);
  1671. } break;
  1672. case GGML_OP_CONV_TRANSPOSE_1D:
  1673. {
  1674. ggml_compute_forward_conv_transpose_1d(params, tensor);
  1675. } break;
  1676. case GGML_OP_IM2COL:
  1677. {
  1678. ggml_compute_forward_im2col(params, tensor);
  1679. } break;
  1680. case GGML_OP_IM2COL_BACK:
  1681. {
  1682. ggml_compute_forward_im2col_back_f32(params, tensor);
  1683. } break;
  1684. case GGML_OP_CONV_2D_DW:
  1685. {
  1686. ggml_compute_forward_conv_2d_dw(params, tensor);
  1687. } break;
  1688. case GGML_OP_CONV_TRANSPOSE_2D:
  1689. {
  1690. ggml_compute_forward_conv_transpose_2d(params, tensor);
  1691. } break;
  1692. case GGML_OP_POOL_1D:
  1693. {
  1694. ggml_compute_forward_pool_1d(params, tensor);
  1695. } break;
  1696. case GGML_OP_POOL_2D:
  1697. {
  1698. ggml_compute_forward_pool_2d(params, tensor);
  1699. } break;
  1700. case GGML_OP_POOL_2D_BACK:
  1701. {
  1702. ggml_compute_forward_pool_2d_back(params, tensor);
  1703. } break;
  1704. case GGML_OP_UPSCALE:
  1705. {
  1706. ggml_compute_forward_upscale(params, tensor);
  1707. } break;
  1708. case GGML_OP_PAD:
  1709. {
  1710. ggml_compute_forward_pad(params, tensor);
  1711. } break;
  1712. case GGML_OP_PAD_REFLECT_1D:
  1713. {
  1714. ggml_compute_forward_pad_reflect_1d(params, tensor);
  1715. } break;
  1716. case GGML_OP_ARANGE:
  1717. {
  1718. ggml_compute_forward_arange(params, tensor);
  1719. } break;
  1720. case GGML_OP_TIMESTEP_EMBEDDING:
  1721. {
  1722. ggml_compute_forward_timestep_embedding(params, tensor);
  1723. } break;
  1724. case GGML_OP_ARGSORT:
  1725. {
  1726. ggml_compute_forward_argsort(params, tensor);
  1727. } break;
  1728. case GGML_OP_LEAKY_RELU:
  1729. {
  1730. ggml_compute_forward_leaky_relu(params, tensor);
  1731. } break;
  1732. case GGML_OP_FLASH_ATTN_EXT:
  1733. {
  1734. ggml_compute_forward_flash_attn_ext(params, tensor->src[0], tensor->src[1], tensor->src[2], tensor->src[3], tensor);
  1735. } break;
  1736. case GGML_OP_FLASH_ATTN_BACK:
  1737. {
  1738. int32_t t = ggml_get_op_params_i32(tensor, 0);
  1739. GGML_ASSERT(t == 0 || t == 1);
  1740. bool masked = t != 0;
  1741. ggml_compute_forward_flash_attn_back(params, masked, tensor);
  1742. } break;
  1743. case GGML_OP_SSM_CONV:
  1744. {
  1745. ggml_compute_forward_ssm_conv(params, tensor);
  1746. } break;
  1747. case GGML_OP_SSM_SCAN:
  1748. {
  1749. ggml_compute_forward_ssm_scan(params, tensor);
  1750. } break;
  1751. case GGML_OP_WIN_PART:
  1752. {
  1753. ggml_compute_forward_win_part(params, tensor);
  1754. } break;
  1755. case GGML_OP_WIN_UNPART:
  1756. {
  1757. ggml_compute_forward_win_unpart(params, tensor);
  1758. } break;
  1759. case GGML_OP_UNARY:
  1760. {
  1761. ggml_compute_forward_unary(params, tensor);
  1762. } break;
  1763. case GGML_OP_GET_REL_POS:
  1764. {
  1765. ggml_compute_forward_get_rel_pos(params, tensor);
  1766. } break;
  1767. case GGML_OP_ADD_REL_POS:
  1768. {
  1769. ggml_compute_forward_add_rel_pos(params, tensor);
  1770. } break;
  1771. case GGML_OP_RWKV_WKV6:
  1772. {
  1773. ggml_compute_forward_rwkv_wkv6(params, tensor);
  1774. } break;
  1775. case GGML_OP_GATED_LINEAR_ATTN:
  1776. {
  1777. ggml_compute_forward_gla(params, tensor);
  1778. } break;
  1779. case GGML_OP_RWKV_WKV7:
  1780. {
  1781. ggml_compute_forward_rwkv_wkv7(params, tensor);
  1782. } break;
  1783. case GGML_OP_MAP_CUSTOM1:
  1784. {
  1785. ggml_compute_forward_map_custom1(params, tensor);
  1786. }
  1787. break;
  1788. case GGML_OP_MAP_CUSTOM2:
  1789. {
  1790. ggml_compute_forward_map_custom2(params, tensor);
  1791. }
  1792. break;
  1793. case GGML_OP_MAP_CUSTOM3:
  1794. {
  1795. ggml_compute_forward_map_custom3(params, tensor);
  1796. }
  1797. break;
  1798. case GGML_OP_CUSTOM:
  1799. {
  1800. ggml_compute_forward_custom(params, tensor);
  1801. }
  1802. break;
  1803. case GGML_OP_CROSS_ENTROPY_LOSS:
  1804. {
  1805. ggml_compute_forward_cross_entropy_loss(params, tensor);
  1806. }
  1807. break;
  1808. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  1809. {
  1810. ggml_compute_forward_cross_entropy_loss_back(params, tensor);
  1811. }
  1812. break;
  1813. case GGML_OP_OPT_STEP_ADAMW:
  1814. {
  1815. ggml_compute_forward_opt_step_adamw(params, tensor);
  1816. }
  1817. break;
  1818. case GGML_OP_NONE:
  1819. {
  1820. // nop
  1821. } break;
  1822. case GGML_OP_COUNT:
  1823. {
  1824. GGML_ABORT("fatal error");
  1825. }
  1826. }
  1827. }
  1828. // Android's libc implementation "bionic" does not support setting affinity
  1829. #if defined(__gnu_linux__)
  1830. static void set_numa_thread_affinity(int thread_n) {
  1831. if (!ggml_is_numa()) {
  1832. return;
  1833. }
  1834. int node_num;
  1835. int rv;
  1836. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  1837. switch(g_state.numa.numa_strategy) {
  1838. case GGML_NUMA_STRATEGY_DISTRIBUTE:
  1839. // run thread on node_num thread_n / (threads per node)
  1840. node_num = thread_n % g_state.numa.n_nodes;
  1841. break;
  1842. case GGML_NUMA_STRATEGY_ISOLATE:
  1843. // run thread on current_node
  1844. node_num = g_state.numa.current_node;
  1845. break;
  1846. case GGML_NUMA_STRATEGY_NUMACTL:
  1847. // use the cpuset that numactl gave us
  1848. rv = pthread_setaffinity_np(pthread_self(), setsize, &g_state.numa.cpuset);
  1849. if (rv) {
  1850. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n",strerror(rv));
  1851. }
  1852. return;
  1853. default:
  1854. return;
  1855. }
  1856. struct ggml_numa_node * node = &g_state.numa.nodes[node_num];
  1857. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  1858. CPU_ZERO_S(setsize, cpus);
  1859. for (size_t i = 0; i < node->n_cpus; ++i) {
  1860. CPU_SET_S(node->cpus[i], setsize, cpus);
  1861. }
  1862. rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  1863. if (rv) {
  1864. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  1865. }
  1866. CPU_FREE(cpus);
  1867. }
  1868. static void clear_numa_thread_affinity(void) {
  1869. if (!ggml_is_numa()) {
  1870. return;
  1871. }
  1872. size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus);
  1873. cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus);
  1874. CPU_ZERO_S(setsize, cpus);
  1875. for (unsigned i = 0; i < g_state.numa.total_cpus; ++i) {
  1876. CPU_SET_S(i, setsize, cpus);
  1877. }
  1878. int rv = pthread_setaffinity_np(pthread_self(), setsize, cpus);
  1879. if (rv) {
  1880. fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv));
  1881. }
  1882. CPU_FREE(cpus);
  1883. }
  1884. #else
  1885. // TODO: Windows etc.
  1886. // (the linux implementation may also work on BSD, someone should test)
  1887. static void set_numa_thread_affinity(int thread_n) { UNUSED(thread_n); }
  1888. static void clear_numa_thread_affinity(void) {}
  1889. #endif
  1890. static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) {
  1891. int n_tasks = 0;
  1892. if (ggml_is_empty(node)) {
  1893. // no need to multi-thread a no-op
  1894. n_tasks = 1;
  1895. return n_tasks;
  1896. }
  1897. switch (node->op) {
  1898. case GGML_OP_CPY:
  1899. case GGML_OP_DUP:
  1900. case GGML_OP_CONT:
  1901. case GGML_OP_ADD:
  1902. case GGML_OP_ADD1:
  1903. case GGML_OP_ACC:
  1904. {
  1905. n_tasks = n_threads;
  1906. } break;
  1907. case GGML_OP_SUB:
  1908. case GGML_OP_SQR:
  1909. case GGML_OP_SQRT:
  1910. case GGML_OP_LOG:
  1911. case GGML_OP_SIN:
  1912. case GGML_OP_COS:
  1913. case GGML_OP_SUM:
  1914. case GGML_OP_SUM_ROWS:
  1915. case GGML_OP_MEAN:
  1916. case GGML_OP_ARGMAX:
  1917. {
  1918. n_tasks = 1;
  1919. } break;
  1920. case GGML_OP_COUNT_EQUAL:
  1921. {
  1922. n_tasks = n_threads;
  1923. } break;
  1924. case GGML_OP_REPEAT:
  1925. case GGML_OP_REPEAT_BACK:
  1926. case GGML_OP_LEAKY_RELU:
  1927. {
  1928. n_tasks = 1;
  1929. } break;
  1930. case GGML_OP_UNARY:
  1931. switch (ggml_get_unary_op(node)) {
  1932. case GGML_UNARY_OP_ABS:
  1933. case GGML_UNARY_OP_SGN:
  1934. case GGML_UNARY_OP_NEG:
  1935. case GGML_UNARY_OP_STEP:
  1936. case GGML_UNARY_OP_TANH:
  1937. case GGML_UNARY_OP_ELU:
  1938. case GGML_UNARY_OP_RELU:
  1939. case GGML_UNARY_OP_SIGMOID:
  1940. case GGML_UNARY_OP_HARDSWISH:
  1941. case GGML_UNARY_OP_HARDSIGMOID:
  1942. case GGML_UNARY_OP_EXP:
  1943. {
  1944. n_tasks = 1;
  1945. } break;
  1946. case GGML_UNARY_OP_GELU:
  1947. case GGML_UNARY_OP_GELU_QUICK:
  1948. case GGML_UNARY_OP_SILU:
  1949. {
  1950. n_tasks = n_threads;
  1951. } break;
  1952. default:
  1953. GGML_ABORT("fatal error");
  1954. }
  1955. break;
  1956. case GGML_OP_SILU_BACK:
  1957. case GGML_OP_MUL:
  1958. case GGML_OP_DIV:
  1959. case GGML_OP_NORM:
  1960. case GGML_OP_RMS_NORM:
  1961. case GGML_OP_RMS_NORM_BACK:
  1962. case GGML_OP_L2_NORM:
  1963. case GGML_OP_GROUP_NORM:
  1964. case GGML_OP_CONCAT:
  1965. case GGML_OP_MUL_MAT:
  1966. case GGML_OP_MUL_MAT_ID:
  1967. case GGML_OP_OUT_PROD:
  1968. {
  1969. n_tasks = n_threads;
  1970. } break;
  1971. case GGML_OP_GET_ROWS:
  1972. {
  1973. // FIXME: get_rows can use additional threads, but the cost of launching additional threads
  1974. // decreases performance with GPU offloading
  1975. //n_tasks = n_threads;
  1976. n_tasks = 1;
  1977. } break;
  1978. case GGML_OP_SCALE:
  1979. case GGML_OP_SET:
  1980. case GGML_OP_RESHAPE:
  1981. case GGML_OP_VIEW:
  1982. case GGML_OP_PERMUTE:
  1983. case GGML_OP_TRANSPOSE:
  1984. case GGML_OP_GET_ROWS_BACK:
  1985. case GGML_OP_DIAG:
  1986. {
  1987. n_tasks = 1;
  1988. } break;
  1989. case GGML_OP_DIAG_MASK_ZERO:
  1990. case GGML_OP_DIAG_MASK_INF:
  1991. case GGML_OP_SOFT_MAX_BACK:
  1992. case GGML_OP_ROPE:
  1993. case GGML_OP_ROPE_BACK:
  1994. case GGML_OP_ADD_REL_POS:
  1995. {
  1996. n_tasks = n_threads;
  1997. } break;
  1998. case GGML_OP_CLAMP:
  1999. {
  2000. n_tasks = 1; //TODO
  2001. } break;
  2002. case GGML_OP_SOFT_MAX:
  2003. {
  2004. n_tasks = MIN(n_threads, ggml_nrows(node->src[0]));
  2005. } break;
  2006. case GGML_OP_IM2COL:
  2007. case GGML_OP_IM2COL_BACK:
  2008. case GGML_OP_CONV_2D_DW:
  2009. case GGML_OP_CONV_TRANSPOSE_1D:
  2010. case GGML_OP_CONV_TRANSPOSE_2D:
  2011. {
  2012. n_tasks = n_threads;
  2013. } break;
  2014. case GGML_OP_POOL_1D:
  2015. case GGML_OP_POOL_2D:
  2016. case GGML_OP_POOL_2D_BACK:
  2017. {
  2018. n_tasks = 1;
  2019. } break;
  2020. case GGML_OP_UPSCALE:
  2021. case GGML_OP_PAD:
  2022. case GGML_OP_PAD_REFLECT_1D:
  2023. case GGML_OP_ARANGE:
  2024. case GGML_OP_TIMESTEP_EMBEDDING:
  2025. case GGML_OP_ARGSORT:
  2026. case GGML_OP_FLASH_ATTN_EXT:
  2027. case GGML_OP_FLASH_ATTN_BACK:
  2028. case GGML_OP_SSM_CONV:
  2029. case GGML_OP_SSM_SCAN:
  2030. case GGML_OP_RWKV_WKV6:
  2031. case GGML_OP_GATED_LINEAR_ATTN:
  2032. case GGML_OP_RWKV_WKV7:
  2033. {
  2034. n_tasks = n_threads;
  2035. } break;
  2036. case GGML_OP_WIN_PART:
  2037. case GGML_OP_WIN_UNPART:
  2038. case GGML_OP_GET_REL_POS:
  2039. {
  2040. n_tasks = 1;
  2041. } break;
  2042. case GGML_OP_MAP_CUSTOM1:
  2043. {
  2044. struct ggml_map_custom1_op_params p;
  2045. memcpy(&p, node->op_params, sizeof(p));
  2046. if (p.n_tasks == GGML_N_TASKS_MAX) {
  2047. n_tasks = n_threads;
  2048. } else {
  2049. n_tasks = MIN(p.n_tasks, n_threads);
  2050. }
  2051. } break;
  2052. case GGML_OP_MAP_CUSTOM2:
  2053. {
  2054. struct ggml_map_custom2_op_params p;
  2055. memcpy(&p, node->op_params, sizeof(p));
  2056. if (p.n_tasks == GGML_N_TASKS_MAX) {
  2057. n_tasks = n_threads;
  2058. } else {
  2059. n_tasks = MIN(p.n_tasks, n_threads);
  2060. }
  2061. } break;
  2062. case GGML_OP_MAP_CUSTOM3:
  2063. {
  2064. struct ggml_map_custom3_op_params p;
  2065. memcpy(&p, node->op_params, sizeof(p));
  2066. if (p.n_tasks == GGML_N_TASKS_MAX) {
  2067. n_tasks = n_threads;
  2068. } else {
  2069. n_tasks = MIN(p.n_tasks, n_threads);
  2070. }
  2071. } break;
  2072. case GGML_OP_CUSTOM:
  2073. {
  2074. struct ggml_custom_op_params p;
  2075. memcpy(&p, node->op_params, sizeof(p));
  2076. if (p.n_tasks == GGML_N_TASKS_MAX) {
  2077. n_tasks = n_threads;
  2078. } else {
  2079. n_tasks = MIN(p.n_tasks, n_threads);
  2080. }
  2081. } break;
  2082. case GGML_OP_CROSS_ENTROPY_LOSS:
  2083. case GGML_OP_CROSS_ENTROPY_LOSS_BACK:
  2084. case GGML_OP_OPT_STEP_ADAMW:
  2085. {
  2086. n_tasks = n_threads;
  2087. } break;
  2088. case GGML_OP_NONE:
  2089. {
  2090. n_tasks = 1;
  2091. } break;
  2092. case GGML_OP_COUNT:
  2093. {
  2094. GGML_ABORT("fatal error");
  2095. }
  2096. default:
  2097. {
  2098. fprintf(stderr, "%s: op not implemented: ", __func__);
  2099. if (node->op < GGML_OP_COUNT) {
  2100. fprintf(stderr, "%s\n", ggml_op_name(node->op));
  2101. } else {
  2102. fprintf(stderr, "%d\n", node->op);
  2103. }
  2104. GGML_ABORT("fatal error");
  2105. }
  2106. }
  2107. assert(n_tasks > 0);
  2108. return n_tasks;
  2109. }
  2110. static thread_ret_t ggml_graph_compute_secondary_thread(void* data);
  2111. #if defined(_WIN32)
  2112. #include "windows.h"
  2113. // TODO: support > 64 CPUs
  2114. static bool ggml_thread_apply_affinity(bool * mask) {
  2115. HANDLE h = GetCurrentThread();
  2116. uint64_t bitmask = 0ULL;
  2117. assert(GGML_MAX_N_THREADS >= 64);
  2118. for (int32_t i = 0; i < 8; i++) {
  2119. int32_t idx = i * 8;
  2120. uint8_t val = 0;
  2121. val |= mask[idx + 0] << 0;
  2122. val |= mask[idx + 1] << 1;
  2123. val |= mask[idx + 2] << 2;
  2124. val |= mask[idx + 3] << 3;
  2125. val |= mask[idx + 4] << 4;
  2126. val |= mask[idx + 5] << 5;
  2127. val |= mask[idx + 6] << 6;
  2128. val |= mask[idx + 7] << 7;
  2129. bitmask |= (uint64_t)val << idx;
  2130. }
  2131. for (int32_t i = 64; i < GGML_MAX_N_THREADS; i++) {
  2132. if (mask[i]) {
  2133. fprintf(stderr, "warn: setting thread-affinity for > 64 CPUs isn't supported on windows!\n");
  2134. break;
  2135. }
  2136. }
  2137. DWORD_PTR m = (DWORD_PTR)bitmask;
  2138. m = SetThreadAffinityMask(h, m);
  2139. return m != 0;
  2140. }
  2141. static bool ggml_thread_apply_priority(int32_t prio) {
  2142. // Note that on Windows the Process Priority Class must be updated in order to set Thread priority.
  2143. // This is up to the applications.
  2144. DWORD p = THREAD_PRIORITY_NORMAL;
  2145. switch (prio) {
  2146. case GGML_SCHED_PRIO_NORMAL: p = THREAD_PRIORITY_NORMAL; break;
  2147. case GGML_SCHED_PRIO_MEDIUM: p = THREAD_PRIORITY_ABOVE_NORMAL; break;
  2148. case GGML_SCHED_PRIO_HIGH: p = THREAD_PRIORITY_HIGHEST; break;
  2149. case GGML_SCHED_PRIO_REALTIME: p = THREAD_PRIORITY_TIME_CRITICAL; break;
  2150. }
  2151. if (prio == GGML_SCHED_PRIO_NORMAL) {
  2152. // Keep inherited policy/priority
  2153. return true;
  2154. }
  2155. if (!SetThreadPriority(GetCurrentThread(), p)) {
  2156. fprintf(stderr, "warn: failed to set thread priority %d : (%d)\n", prio, (int) GetLastError());
  2157. return false;
  2158. }
  2159. return true;
  2160. }
  2161. #elif defined(__APPLE__)
  2162. #include <sys/types.h>
  2163. #include <sys/resource.h>
  2164. static bool ggml_thread_apply_affinity(const bool * mask) {
  2165. // Not supported on Apple platforms
  2166. UNUSED(mask);
  2167. return true;
  2168. }
  2169. static bool ggml_thread_apply_priority(int32_t prio) {
  2170. struct sched_param p;
  2171. int32_t policy = SCHED_OTHER;
  2172. switch (prio) {
  2173. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  2174. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  2175. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  2176. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  2177. }
  2178. if (prio == GGML_SCHED_PRIO_NORMAL) {
  2179. // Keep inherited policy/priority
  2180. return true;
  2181. }
  2182. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  2183. if (err != 0) {
  2184. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  2185. return false;
  2186. }
  2187. return true;
  2188. }
  2189. #elif defined(__gnu_linux__)
  2190. // TODO: this may not work on BSD, to be verified
  2191. static bool ggml_thread_apply_affinity(const bool * mask) {
  2192. cpu_set_t cpuset;
  2193. int err;
  2194. CPU_ZERO(&cpuset);
  2195. for (uint32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  2196. if (mask[i]) {
  2197. GGML_PRINT_DEBUG("Thread %lx: adding %d to cpuset\n", pthread_self(), i);
  2198. CPU_SET(i, &cpuset);
  2199. }
  2200. }
  2201. #ifdef __ANDROID__
  2202. err = sched_setaffinity(0, sizeof(cpuset), &cpuset);
  2203. if (err < 0) {
  2204. err = errno;
  2205. }
  2206. #else
  2207. err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
  2208. #endif
  2209. if (err != 0) {
  2210. fprintf(stderr, "warn: failed to set affinity mask 0x%llx : %s (%d)\n", (unsigned long long)mask, strerror(err), err);
  2211. return false;
  2212. }
  2213. return true;
  2214. }
  2215. static bool ggml_thread_apply_priority(int32_t prio) {
  2216. struct sched_param p;
  2217. int32_t policy = SCHED_OTHER;
  2218. switch (prio) {
  2219. case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break;
  2220. case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break;
  2221. case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break;
  2222. case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break;
  2223. }
  2224. if (prio == GGML_SCHED_PRIO_NORMAL) {
  2225. // Keep inherited policy/priority
  2226. return true;
  2227. }
  2228. int32_t err = pthread_setschedparam(pthread_self(), policy, &p);
  2229. if (err != 0) {
  2230. fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err);
  2231. return false;
  2232. }
  2233. return true;
  2234. }
  2235. #else // unsupported platforms
  2236. static bool ggml_thread_apply_affinity(const bool * mask) {
  2237. UNUSED(mask);
  2238. return true;
  2239. }
  2240. static bool ggml_thread_apply_priority(int32_t prio) {
  2241. UNUSED(prio);
  2242. return true;
  2243. }
  2244. #endif
  2245. static bool ggml_thread_cpumask_is_valid(const bool * mask) {
  2246. for (int i = 0; i < GGML_MAX_N_THREADS; i++) {
  2247. if (mask[i]) { return true; }
  2248. }
  2249. return false;
  2250. }
  2251. static void ggml_thread_cpumask_next(const bool * global_mask, bool * local_mask, bool strict, int32_t* iter) {
  2252. if (!strict) {
  2253. memcpy(local_mask, global_mask, GGML_MAX_N_THREADS);
  2254. return;
  2255. } else {
  2256. memset(local_mask, 0, GGML_MAX_N_THREADS);
  2257. int32_t base_idx = *iter;
  2258. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  2259. int32_t idx = base_idx + i;
  2260. if (idx >= GGML_MAX_N_THREADS) {
  2261. // Just a cheaper modulo
  2262. idx -= GGML_MAX_N_THREADS;
  2263. }
  2264. if (global_mask[idx]) {
  2265. local_mask[idx] = 1;
  2266. *iter = idx + 1;
  2267. return;
  2268. }
  2269. }
  2270. }
  2271. }
  2272. void ggml_threadpool_free(struct ggml_threadpool* threadpool) {
  2273. if (!threadpool) return;
  2274. const int n_threads = threadpool->n_threads_max;
  2275. #ifndef GGML_USE_OPENMP
  2276. struct ggml_compute_state* workers = threadpool->workers;
  2277. ggml_mutex_lock(&threadpool->mutex);
  2278. threadpool->stop = true;
  2279. threadpool->pause = false;
  2280. ggml_cond_broadcast(&threadpool->cond);
  2281. ggml_mutex_unlock(&threadpool->mutex);
  2282. for (int j = 1; j < n_threads; j++) {
  2283. int32_t rc = ggml_thread_join(workers[j].thrd, NULL);
  2284. GGML_ASSERT(rc == GGML_EXIT_SUCCESS || rc == GGML_EXIT_ABORTED);
  2285. UNUSED(rc);
  2286. }
  2287. ggml_mutex_destroy(&threadpool->mutex);
  2288. ggml_cond_destroy(&threadpool->cond);
  2289. #endif // GGML_USE_OPENMP
  2290. const size_t workers_size = sizeof(struct ggml_compute_state) * n_threads;
  2291. ggml_aligned_free(threadpool->workers, workers_size);
  2292. ggml_aligned_free(threadpool, sizeof(struct ggml_threadpool));
  2293. }
  2294. #ifndef GGML_USE_OPENMP
  2295. // pause/resume must be called under mutex
  2296. static void ggml_threadpool_pause_locked(struct ggml_threadpool * threadpool) {
  2297. GGML_PRINT_DEBUG("Pausing threadpool\n");
  2298. threadpool->pause = true;
  2299. ggml_cond_broadcast(&threadpool->cond);
  2300. }
  2301. static void ggml_threadpool_resume_locked(struct ggml_threadpool * threadpool) {
  2302. GGML_PRINT_DEBUG("Resuming threadpool\n");
  2303. threadpool->pause = false;
  2304. ggml_cond_broadcast(&threadpool->cond);
  2305. }
  2306. #endif
  2307. void ggml_threadpool_pause(struct ggml_threadpool * threadpool) {
  2308. #ifndef GGML_USE_OPENMP
  2309. ggml_mutex_lock(&threadpool->mutex);
  2310. if (!threadpool->pause) {
  2311. ggml_threadpool_pause_locked(threadpool);
  2312. }
  2313. ggml_mutex_unlock(&threadpool->mutex);
  2314. #else
  2315. UNUSED(threadpool);
  2316. #endif
  2317. }
  2318. void ggml_threadpool_resume(struct ggml_threadpool * threadpool) {
  2319. #ifndef GGML_USE_OPENMP
  2320. ggml_mutex_lock(&threadpool->mutex);
  2321. if (threadpool->pause) {
  2322. ggml_threadpool_resume_locked(threadpool);
  2323. }
  2324. ggml_mutex_unlock(&threadpool->mutex);
  2325. #else
  2326. UNUSED(threadpool);
  2327. #endif
  2328. }
  2329. struct ggml_cplan ggml_graph_plan(
  2330. const struct ggml_cgraph * cgraph,
  2331. int n_threads,
  2332. struct ggml_threadpool * threadpool) {
  2333. if (threadpool == NULL) {
  2334. //GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  2335. }
  2336. if (n_threads <= 0) {
  2337. n_threads = threadpool ? threadpool->n_threads_max : GGML_DEFAULT_N_THREADS;
  2338. }
  2339. size_t work_size = 0;
  2340. struct ggml_cplan cplan;
  2341. memset(&cplan, 0, sizeof(struct ggml_cplan));
  2342. int max_tasks = 1;
  2343. // thread scheduling for the different operations + work buffer size estimation
  2344. for (int i = 0; i < cgraph->n_nodes; i++) {
  2345. struct ggml_tensor * node = cgraph->nodes[i];
  2346. const int n_tasks = ggml_get_n_tasks(node, n_threads);
  2347. max_tasks = MAX(max_tasks, n_tasks);
  2348. size_t cur = 0;
  2349. if (!ggml_cpu_extra_work_size(n_threads, node, &cur)) {
  2350. switch (node->op) {
  2351. case GGML_OP_CPY:
  2352. case GGML_OP_DUP:
  2353. {
  2354. if (ggml_is_quantized(node->type) ||
  2355. // F16 -> BF16 and BF16 -> F16 copies go through intermediate F32
  2356. (node->src[0]->type == GGML_TYPE_F16 && node->src[1] && node->src[1]->type == GGML_TYPE_BF16) ||
  2357. (node->src[0]->type == GGML_TYPE_BF16 && node->src[1] && node->src[1]->type == GGML_TYPE_F16)) {
  2358. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  2359. }
  2360. } break;
  2361. case GGML_OP_ADD:
  2362. case GGML_OP_ADD1:
  2363. {
  2364. if (ggml_is_quantized(node->src[0]->type)) {
  2365. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  2366. }
  2367. } break;
  2368. case GGML_OP_ACC:
  2369. {
  2370. if (ggml_is_quantized(node->src[0]->type)) {
  2371. cur = ggml_type_size(GGML_TYPE_F32) * node->src[1]->ne[0] * n_tasks;
  2372. }
  2373. } break;
  2374. case GGML_OP_COUNT_EQUAL:
  2375. {
  2376. cur = ggml_type_size(node->type)*n_tasks;
  2377. } break;
  2378. case GGML_OP_MUL_MAT:
  2379. {
  2380. const enum ggml_type vec_dot_type = type_traits_cpu[node->src[0]->type].vec_dot_type;
  2381. if (node->src[1]->type != vec_dot_type) {
  2382. cur = ggml_row_size(vec_dot_type, ggml_nelements(node->src[1]));
  2383. }
  2384. } break;
  2385. case GGML_OP_MUL_MAT_ID:
  2386. {
  2387. cur = 0;
  2388. const struct ggml_tensor * src0 = node->src[0];
  2389. const struct ggml_tensor * src1 = node->src[1];
  2390. const struct ggml_tensor * ids = node->src[2];
  2391. const enum ggml_type vec_dot_type = type_traits_cpu[src0->type].vec_dot_type;
  2392. const int n_as = src0->ne[2];
  2393. // src1
  2394. if (src1->type != vec_dot_type) {
  2395. cur += ggml_row_size(vec_dot_type, ggml_nelements(src1)) + sizeof(int64_t);
  2396. }
  2397. // matrix_row_counts
  2398. cur += n_as * sizeof(int64_t) + sizeof(int64_t);
  2399. // matrix_rows
  2400. cur += n_as*ids->ne[0]*ids->ne[1]*sizeof(struct mmid_row_mapping) + sizeof(int64_t);
  2401. // atomic_current_chunk
  2402. cur += CACHE_LINE_SIZE*n_as + CACHE_LINE_SIZE;
  2403. } break;
  2404. case GGML_OP_OUT_PROD:
  2405. {
  2406. if (ggml_is_quantized(node->src[0]->type)) {
  2407. cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
  2408. }
  2409. } break;
  2410. case GGML_OP_SOFT_MAX:
  2411. case GGML_OP_ROPE:
  2412. case GGML_OP_ROPE_BACK:
  2413. {
  2414. cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks;
  2415. } break;
  2416. case GGML_OP_CONV_TRANSPOSE_1D:
  2417. {
  2418. GGML_ASSERT(node->src[0]->ne[3] == 1);
  2419. GGML_ASSERT(node->src[1]->ne[2] == 1);
  2420. GGML_ASSERT(node->src[1]->ne[3] == 1);
  2421. const int64_t ne00 = node->src[0]->ne[0]; // K
  2422. const int64_t ne01 = node->src[0]->ne[1]; // Cout
  2423. const int64_t ne02 = node->src[0]->ne[2]; // Cin
  2424. const int64_t ne10 = node->src[1]->ne[0]; // L
  2425. const int64_t ne11 = node->src[1]->ne[1]; // Cin
  2426. if ((node->src[0]->type == GGML_TYPE_F16 ||
  2427. node->src[0]->type == GGML_TYPE_BF16) &&
  2428. node->src[1]->type == GGML_TYPE_F32) {
  2429. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02;
  2430. cur += sizeof(ggml_fp16_t)*ne10*ne11;
  2431. } else if (node->src[0]->type == GGML_TYPE_F32 &&
  2432. node->src[1]->type == GGML_TYPE_F32) {
  2433. cur += sizeof(float)*ne00*ne01*ne02;
  2434. cur += sizeof(float)*ne10*ne11;
  2435. } else {
  2436. GGML_ABORT("fatal error");
  2437. }
  2438. } break;
  2439. case GGML_OP_CONV_TRANSPOSE_2D:
  2440. {
  2441. const int64_t ne00 = node->src[0]->ne[0]; // W
  2442. const int64_t ne01 = node->src[0]->ne[1]; // H
  2443. const int64_t ne02 = node->src[0]->ne[2]; // Channels Out
  2444. const int64_t ne03 = node->src[0]->ne[3]; // Channels In
  2445. const int64_t ne10 = node->src[1]->ne[0]; // W
  2446. const int64_t ne11 = node->src[1]->ne[1]; // H
  2447. const int64_t ne12 = node->src[1]->ne[2]; // Channels In
  2448. cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02*ne03;
  2449. cur += sizeof(ggml_fp16_t)*ne10*ne11*ne12;
  2450. } break;
  2451. case GGML_OP_FLASH_ATTN_EXT:
  2452. {
  2453. const int64_t ne10 = node->src[1]->ne[0]; // DK
  2454. const int64_t ne20 = node->src[2]->ne[0]; // DV
  2455. cur = sizeof(float)*(1*ne10 + 2*ne20)*n_tasks; // 1x head size K + 2x head size V (per thread)
  2456. } break;
  2457. case GGML_OP_FLASH_ATTN_BACK:
  2458. {
  2459. const int64_t D = node->src[0]->ne[0];
  2460. const int64_t ne11 = ggml_up(node->src[1]->ne[1], GGML_SOFT_MAX_UNROLL);
  2461. const int64_t mxDn = MAX(D, ne11) * 2; // *2 because of S and SM in ggml_compute_forward_flash_attn_back
  2462. if (node->src[1]->type == GGML_TYPE_F32) {
  2463. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  2464. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  2465. } else if (node->src[1]->type == GGML_TYPE_F16) {
  2466. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  2467. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  2468. } else if (node->src[1]->type == GGML_TYPE_BF16) {
  2469. cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1)
  2470. cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2
  2471. }
  2472. } break;
  2473. case GGML_OP_CROSS_ENTROPY_LOSS:
  2474. {
  2475. cur = ggml_type_size(node->type)*(n_tasks + node->src[0]->ne[0]*n_tasks);
  2476. } break;
  2477. case GGML_OP_COUNT:
  2478. {
  2479. GGML_ABORT("fatal error");
  2480. }
  2481. default:
  2482. break;
  2483. }
  2484. }
  2485. work_size = MAX(work_size, cur);
  2486. }
  2487. if (work_size > 0) {
  2488. work_size += CACHE_LINE_SIZE*(n_threads);
  2489. }
  2490. cplan.threadpool = threadpool;
  2491. cplan.n_threads = MIN(max_tasks, n_threads);
  2492. cplan.work_size = work_size;
  2493. cplan.work_data = NULL;
  2494. return cplan;
  2495. }
  2496. static thread_ret_t ggml_graph_compute_thread(void * data) {
  2497. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  2498. struct ggml_threadpool * tp = state->threadpool;
  2499. const struct ggml_cgraph * cgraph = tp->cgraph;
  2500. const struct ggml_cplan * cplan = tp->cplan;
  2501. set_numa_thread_affinity(state->ith);
  2502. struct ggml_compute_params params = {
  2503. /*.ith =*/ state->ith,
  2504. /*.nth =*/ atomic_load_explicit(&tp->n_threads_cur, memory_order_relaxed),
  2505. /*.wsize =*/ cplan->work_size,
  2506. /*.wdata =*/ cplan->work_data,
  2507. /*.threadpool=*/ tp,
  2508. };
  2509. for (int node_n = 0; node_n < cgraph->n_nodes && atomic_load_explicit(&tp->abort, memory_order_relaxed) != node_n; node_n++) {
  2510. struct ggml_tensor * node = cgraph->nodes[node_n];
  2511. ggml_compute_forward(&params, node);
  2512. if (state->ith == 0 && cplan->abort_callback &&
  2513. cplan->abort_callback(cplan->abort_callback_data)) {
  2514. atomic_store_explicit(&tp->abort, node_n + 1, memory_order_relaxed);
  2515. tp->ec = GGML_STATUS_ABORTED;
  2516. }
  2517. if (node_n + 1 < cgraph->n_nodes) {
  2518. ggml_barrier(state->threadpool);
  2519. }
  2520. }
  2521. ggml_barrier(state->threadpool);
  2522. return 0;
  2523. }
  2524. #ifndef GGML_USE_OPENMP
  2525. // check if thread is active
  2526. static inline bool ggml_graph_compute_thread_active(struct ggml_compute_state * state) {
  2527. struct ggml_threadpool * threadpool = state->threadpool;
  2528. int n_threads = atomic_load_explicit(&threadpool->n_threads_cur, memory_order_relaxed);
  2529. return (state->ith < n_threads);
  2530. }
  2531. // check if thread is ready to proceed (exit from polling or sleeping)
  2532. static inline bool ggml_graph_compute_thread_ready(struct ggml_compute_state * state) {
  2533. struct ggml_threadpool * threadpool = state->threadpool;
  2534. if (state->pending || threadpool->stop || threadpool->pause) { return true; }
  2535. // check for new graph/work
  2536. int new_graph = atomic_load_explicit(&threadpool->n_graph, memory_order_relaxed);
  2537. if (new_graph != state->last_graph) {
  2538. state->pending = ggml_graph_compute_thread_active(state);
  2539. state->last_graph = new_graph;
  2540. }
  2541. return state->pending;
  2542. }
  2543. // sync thread state after polling
  2544. static inline void ggml_graph_compute_thread_sync(struct ggml_compute_state * state) {
  2545. // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead
  2546. #ifdef GGML_TSAN_ENABLED
  2547. atomic_fetch_add_explicit(&state->threadpool->n_graph, 0, memory_order_seq_cst);
  2548. #else
  2549. atomic_thread_fence(memory_order_seq_cst);
  2550. #endif
  2551. UNUSED(state);
  2552. }
  2553. static inline bool ggml_graph_compute_poll_for_work(struct ggml_compute_state * state) {
  2554. struct ggml_threadpool * threadpool = state->threadpool;
  2555. // Skip polling for unused threads
  2556. if (!ggml_graph_compute_thread_active(state)) {
  2557. return state->pending;
  2558. }
  2559. // This seems to make 0 ... 100 a decent range for polling level across modern processors.
  2560. // Perhaps, we can adjust it dynamically based on load and things.
  2561. const uint64_t n_rounds = 1024UL * 128 * threadpool->poll;
  2562. for (uint64_t i=0; !ggml_graph_compute_thread_ready(state) && i < n_rounds; i++) {
  2563. // No new work. Keep polling.
  2564. ggml_thread_cpu_relax();
  2565. }
  2566. return state->pending;
  2567. }
  2568. static inline bool ggml_graph_compute_check_for_work(struct ggml_compute_state * state) {
  2569. struct ggml_threadpool * threadpool = state->threadpool;
  2570. if (ggml_graph_compute_poll_for_work(state)) {
  2571. ggml_graph_compute_thread_sync(state);
  2572. return state->pending;
  2573. }
  2574. ggml_mutex_lock_shared(&threadpool->mutex);
  2575. while (!ggml_graph_compute_thread_ready(state)) {
  2576. // No new work. Wait for the signal.
  2577. GGML_PRINT_DEBUG("thread #%d waiting for work (sleeping)\n", state->ith);
  2578. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  2579. }
  2580. ggml_mutex_unlock_shared(&threadpool->mutex);
  2581. return state->pending;
  2582. }
  2583. static thread_ret_t ggml_graph_compute_secondary_thread(void* data) {
  2584. struct ggml_compute_state * state = (struct ggml_compute_state *) data;
  2585. struct ggml_threadpool * threadpool = state->threadpool;
  2586. ggml_thread_apply_priority(threadpool->prio);
  2587. if (ggml_thread_cpumask_is_valid(state->cpumask)) {
  2588. ggml_thread_apply_affinity(state->cpumask);
  2589. }
  2590. while (true) {
  2591. // Check if we need to sleep
  2592. while (threadpool->pause) {
  2593. GGML_PRINT_DEBUG("thread #%d inside pause loop\n", state->ith);
  2594. ggml_mutex_lock_shared(&threadpool->mutex);
  2595. if (threadpool->pause) {
  2596. ggml_cond_wait(&threadpool->cond, &threadpool->mutex);
  2597. }
  2598. GGML_PRINT_DEBUG("thread #%d resuming after wait\n", state->ith);
  2599. ggml_mutex_unlock_shared(&threadpool->mutex);
  2600. }
  2601. // This needs to be checked for after the cond_wait
  2602. if (threadpool->stop) break;
  2603. // Check if there is new work
  2604. // The main thread is the only one that can dispatch new work
  2605. ggml_graph_compute_check_for_work(state);
  2606. if (state->pending) {
  2607. state->pending = false;
  2608. ggml_graph_compute_thread(state);
  2609. }
  2610. }
  2611. return (thread_ret_t) 0;
  2612. }
  2613. // Start processing new graph
  2614. static void ggml_graph_compute_kickoff(struct ggml_threadpool * threadpool, int n_threads)
  2615. {
  2616. // Always take the mutex here because the worker threads are doing hybrid poll/wait
  2617. ggml_mutex_lock(&threadpool->mutex);
  2618. GGML_PRINT_DEBUG("threadpool: n_threads_cur %d n_threads %d\n", threadpool->n_threads_cur, n_threads);
  2619. // Update the number of active threads
  2620. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  2621. // Indicate the graph is ready to be processed
  2622. // We need the full seq-cst fence here because of the polling threads (used in thread_sync)
  2623. atomic_fetch_add_explicit(&threadpool->n_graph, 1, memory_order_seq_cst);
  2624. if (threadpool->pause) {
  2625. // Update main thread prio and affinity to match the threadpool settings
  2626. ggml_thread_apply_priority(threadpool->prio);
  2627. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  2628. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  2629. }
  2630. // resume does cond broadcast
  2631. ggml_threadpool_resume_locked(threadpool);
  2632. } else {
  2633. ggml_cond_broadcast(&threadpool->cond);
  2634. }
  2635. ggml_mutex_unlock(&threadpool->mutex);
  2636. }
  2637. #endif // GGML_USE_OPENMP
  2638. static struct ggml_threadpool * ggml_threadpool_new_impl(
  2639. struct ggml_threadpool_params * tpp,
  2640. struct ggml_cgraph * cgraph,
  2641. struct ggml_cplan * cplan) {
  2642. struct ggml_threadpool * threadpool =
  2643. ggml_aligned_malloc(sizeof(struct ggml_threadpool));
  2644. {
  2645. threadpool->cgraph = cgraph;
  2646. threadpool->cplan = cplan;
  2647. threadpool->n_graph = 0;
  2648. threadpool->n_barrier = 0;
  2649. threadpool->n_barrier_passed = 0;
  2650. threadpool->current_chunk = 0;
  2651. threadpool->stop = false;
  2652. threadpool->pause = tpp->paused;
  2653. threadpool->abort = -1;
  2654. threadpool->workers = NULL;
  2655. threadpool->n_threads_max = tpp->n_threads;
  2656. threadpool->n_threads_cur = tpp->n_threads;
  2657. threadpool->poll = tpp->poll;
  2658. threadpool->prio = tpp->prio;
  2659. threadpool->ec = GGML_STATUS_SUCCESS;
  2660. }
  2661. // Allocate and init workers state
  2662. const size_t workers_size = sizeof(struct ggml_compute_state) * tpp->n_threads;
  2663. struct ggml_compute_state * workers = ggml_aligned_malloc(workers_size);
  2664. memset(workers, 0, workers_size);
  2665. for (int j = 0; j < tpp->n_threads; j++) {
  2666. workers[j].threadpool = threadpool;
  2667. workers[j].ith = j;
  2668. }
  2669. threadpool->workers = workers;
  2670. #ifndef GGML_USE_OPENMP
  2671. ggml_mutex_init(&threadpool->mutex);
  2672. ggml_cond_init(&threadpool->cond);
  2673. // Spin the threads for all workers, and update CPU placements.
  2674. // Place the main thread last (towards the higher numbered CPU cores).
  2675. int32_t cpumask_iter = 0;
  2676. for (int j = 1; j < tpp->n_threads; j++) {
  2677. ggml_thread_cpumask_next(tpp->cpumask, workers[j].cpumask, tpp->strict_cpu, &cpumask_iter);
  2678. int32_t rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_secondary_thread, &workers[j]);
  2679. GGML_ASSERT(rc == 0);
  2680. }
  2681. ggml_thread_cpumask_next(tpp->cpumask, workers[0].cpumask, tpp->strict_cpu, &cpumask_iter);
  2682. if (!threadpool->pause) {
  2683. // Update main thread prio and affinity at the start, otherwise we'll do it in resume
  2684. ggml_thread_apply_priority(threadpool->prio);
  2685. if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) {
  2686. ggml_thread_apply_affinity(threadpool->workers[0].cpumask);
  2687. }
  2688. }
  2689. #endif // GGML_USE_OPENMP
  2690. return threadpool;
  2691. }
  2692. struct ggml_threadpool * ggml_threadpool_new(struct ggml_threadpool_params * tpp) {
  2693. return ggml_threadpool_new_impl(tpp, NULL, NULL);
  2694. }
  2695. enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan) {
  2696. ggml_cpu_init();
  2697. GGML_ASSERT(cplan);
  2698. GGML_ASSERT(cplan->n_threads > 0);
  2699. GGML_ASSERT(cplan->work_size == 0 || cplan->work_data != NULL);
  2700. int n_threads = cplan->n_threads;
  2701. struct ggml_threadpool * threadpool = cplan->threadpool;
  2702. bool disposable_threadpool = false;
  2703. if (threadpool == NULL) {
  2704. //GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads);
  2705. disposable_threadpool = true;
  2706. struct ggml_threadpool_params ttp = ggml_threadpool_params_default(n_threads);
  2707. threadpool = ggml_threadpool_new_impl(&ttp, cgraph, cplan);
  2708. } else {
  2709. // Reset some of the parameters that need resetting
  2710. // No worker threads should be accessing the parameters below at this stage
  2711. threadpool->cgraph = cgraph;
  2712. threadpool->cplan = cplan;
  2713. threadpool->current_chunk = 0;
  2714. threadpool->abort = -1;
  2715. threadpool->ec = GGML_STATUS_SUCCESS;
  2716. }
  2717. #ifdef GGML_USE_OPENMP
  2718. if (n_threads > 1) {
  2719. #pragma omp parallel num_threads(n_threads)
  2720. {
  2721. #pragma omp single
  2722. {
  2723. // update the number of threads from the actual number of threads that we got from OpenMP
  2724. n_threads = omp_get_num_threads();
  2725. atomic_store_explicit(&threadpool->n_threads_cur, n_threads, memory_order_relaxed);
  2726. }
  2727. ggml_graph_compute_thread(&threadpool->workers[omp_get_thread_num()]);
  2728. }
  2729. } else {
  2730. atomic_store_explicit(&threadpool->n_threads_cur, 1, memory_order_relaxed);
  2731. ggml_graph_compute_thread(&threadpool->workers[0]);
  2732. }
  2733. #else
  2734. if (n_threads > threadpool->n_threads_max) {
  2735. GGML_LOG_WARN("cplan requested more threads (%d) than available (%d)\n", n_threads, threadpool->n_threads_max);
  2736. n_threads = threadpool->n_threads_max;
  2737. }
  2738. // Kick all threads to start the new graph
  2739. ggml_graph_compute_kickoff(threadpool, n_threads);
  2740. // This is a work thread too
  2741. ggml_graph_compute_thread(&threadpool->workers[0]);
  2742. #endif
  2743. // don't leave affinity set on the main thread
  2744. clear_numa_thread_affinity();
  2745. enum ggml_status ret = threadpool->ec;
  2746. if (disposable_threadpool) {
  2747. ggml_threadpool_free(threadpool);
  2748. }
  2749. return ret;
  2750. }
  2751. enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads) {
  2752. struct ggml_cplan cplan = ggml_graph_plan(cgraph, n_threads, NULL);
  2753. cplan.work_data = (uint8_t *)ggml_new_buffer(ctx, cplan.work_size);
  2754. return ggml_graph_compute(cgraph, &cplan);
  2755. }
  2756. int ggml_cpu_has_avx(void) {
  2757. #if defined(__AVX__)
  2758. return 1;
  2759. #else
  2760. return 0;
  2761. #endif
  2762. }
  2763. int ggml_cpu_has_avx_vnni(void) {
  2764. #if defined(__AVXVNNI__)
  2765. return 1;
  2766. #else
  2767. return 0;
  2768. #endif
  2769. }
  2770. int ggml_cpu_has_avx2(void) {
  2771. #if defined(__AVX2__)
  2772. return 1;
  2773. #else
  2774. return 0;
  2775. #endif
  2776. }
  2777. int ggml_cpu_has_avx512(void) {
  2778. #if defined(__AVX512F__)
  2779. return 1;
  2780. #else
  2781. return 0;
  2782. #endif
  2783. }
  2784. int ggml_cpu_has_avx512_vbmi(void) {
  2785. #if defined(__AVX512VBMI__)
  2786. return 1;
  2787. #else
  2788. return 0;
  2789. #endif
  2790. }
  2791. int ggml_cpu_has_avx512_vnni(void) {
  2792. #if defined(__AVX512VNNI__)
  2793. return 1;
  2794. #else
  2795. return 0;
  2796. #endif
  2797. }
  2798. int ggml_cpu_has_avx512_bf16(void) {
  2799. #if defined(__AVX512BF16__)
  2800. return 1;
  2801. #else
  2802. return 0;
  2803. #endif
  2804. }
  2805. int ggml_cpu_has_amx_int8(void) {
  2806. #if defined(__AMX_INT8__)
  2807. return 1;
  2808. #else
  2809. return 0;
  2810. #endif
  2811. }
  2812. int ggml_cpu_has_bmi2(void) {
  2813. #if defined(__BMI2__)
  2814. return 1;
  2815. #else
  2816. return 0;
  2817. #endif
  2818. }
  2819. int ggml_cpu_has_fma(void) {
  2820. #if defined(__FMA__)
  2821. return 1;
  2822. #else
  2823. return 0;
  2824. #endif
  2825. }
  2826. int ggml_cpu_has_arm_fma(void) {
  2827. #if defined(__ARM_FEATURE_FMA)
  2828. return 1;
  2829. #else
  2830. return 0;
  2831. #endif
  2832. }
  2833. int ggml_cpu_has_riscv_v(void) {
  2834. #if defined(__riscv_v_intrinsic)
  2835. return 1;
  2836. #else
  2837. return 0;
  2838. #endif
  2839. }
  2840. int ggml_cpu_has_f16c(void) {
  2841. #if defined(__F16C__)
  2842. return 1;
  2843. #else
  2844. return 0;
  2845. #endif
  2846. }
  2847. int ggml_cpu_has_fp16_va(void) {
  2848. #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
  2849. return 1;
  2850. #else
  2851. return 0;
  2852. #endif
  2853. }
  2854. int ggml_cpu_has_wasm_simd(void) {
  2855. #if defined(__wasm_simd128__)
  2856. return 1;
  2857. #else
  2858. return 0;
  2859. #endif
  2860. }
  2861. int ggml_cpu_has_llamafile(void) {
  2862. #if defined(GGML_USE_LLAMAFILE)
  2863. return 1;
  2864. #else
  2865. return 0;
  2866. #endif
  2867. }
  2868. int ggml_cpu_has_sse3(void) {
  2869. #if defined(__SSE3__)
  2870. return 1;
  2871. #else
  2872. return 0;
  2873. #endif
  2874. }
  2875. int ggml_cpu_has_ssse3(void) {
  2876. #if defined(__SSSE3__)
  2877. return 1;
  2878. #else
  2879. return 0;
  2880. #endif
  2881. }
  2882. int ggml_cpu_has_vsx(void) {
  2883. #if defined(__POWER9_VECTOR__)
  2884. return 1;
  2885. #else
  2886. return 0;
  2887. #endif
  2888. }
  2889. int ggml_cpu_has_vxe(void) {
  2890. #if defined(__VXE__) || defined(__VXE2__)
  2891. return 1;
  2892. #else
  2893. return 0;
  2894. #endif
  2895. }
  2896. int ggml_cpu_has_neon(void) {
  2897. #if defined(__ARM_ARCH) && defined(__ARM_NEON)
  2898. return ggml_arm_arch_features.has_neon;
  2899. #else
  2900. return 0;
  2901. #endif
  2902. }
  2903. int ggml_cpu_has_dotprod(void) {
  2904. #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_DOTPROD)
  2905. return ggml_arm_arch_features.has_dotprod;
  2906. #else
  2907. return 0;
  2908. #endif
  2909. }
  2910. int ggml_cpu_has_sve(void) {
  2911. #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SVE)
  2912. return ggml_arm_arch_features.has_sve;
  2913. #else
  2914. return 0;
  2915. #endif
  2916. }
  2917. int ggml_cpu_has_matmul_int8(void) {
  2918. #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_MATMUL_INT8)
  2919. return ggml_arm_arch_features.has_i8mm;
  2920. #else
  2921. return 0;
  2922. #endif
  2923. }
  2924. int ggml_cpu_get_sve_cnt(void) {
  2925. #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SVE)
  2926. return ggml_arm_arch_features.sve_cnt;
  2927. #else
  2928. return 0;
  2929. #endif
  2930. }
  2931. int ggml_cpu_has_sme(void) {
  2932. #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SME)
  2933. return ggml_arm_arch_features.has_sme;
  2934. #else
  2935. return 0;
  2936. #endif
  2937. }
  2938. void ggml_cpu_init(void) {
  2939. // needed to initialize f16 tables
  2940. {
  2941. struct ggml_init_params params = { 0, NULL, false };
  2942. struct ggml_context * ctx = ggml_init(params);
  2943. ggml_free(ctx);
  2944. }
  2945. ggml_critical_section_start();
  2946. static bool is_first_call = true;
  2947. if (is_first_call) {
  2948. // initialize GELU, Quick GELU, SILU and EXP F32 tables
  2949. {
  2950. const uint64_t t_start = ggml_time_us(); UNUSED(t_start);
  2951. for (int i = 0; i < (1 << 16); ++i) {
  2952. union {
  2953. uint16_t u16;
  2954. ggml_fp16_t fp16;
  2955. } u = {i};
  2956. float f = GGML_FP16_TO_FP32(u.fp16);
  2957. ggml_table_gelu_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_f32(f));
  2958. ggml_table_gelu_quick_f16[i] = GGML_FP32_TO_FP16(ggml_gelu_quick_f32(f));
  2959. }
  2960. const uint64_t t_end = ggml_time_us(); UNUSED(t_end);
  2961. GGML_PRINT_DEBUG("%s: GELU, Quick GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0);
  2962. }
  2963. #if defined(__ARM_ARCH)
  2964. ggml_init_arm_arch_features();
  2965. #endif
  2966. is_first_call = false;
  2967. }
  2968. ggml_critical_section_end();
  2969. }