ggml-cpu.c 116 KB

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