test-backend-ops.cpp 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952
  1. // This file defines tests for various GGML ops and backends.
  2. // For the forward pass it asserts that the results of multiple backends computing the same GGML ops are consistent.
  3. // For the backward pass it asserts that the gradients from backpropagation are consistent
  4. // with the gradients obtained via the method of finite differences ("grad" mode, this is optional).
  5. // It is also possible to check the performance ("perf" mode).
  6. //
  7. // this file has three sections: Section 1 does general setup, section 2 defines the GGML ops to be tested,
  8. // and section 3 defines which tests to run.
  9. // Quick start for adding a new GGML op: Go to section 2 and create a struct that inherits from test_case,
  10. // then go to section 3 and add an instantiation of your struct.
  11. // ##############################
  12. // ## Section 1: General Setup ##
  13. // ##############################
  14. #include <ggml.h>
  15. #include <ggml-cpu.h>
  16. #include <ggml-alloc.h>
  17. #include <ggml-backend.h>
  18. #include <algorithm>
  19. #include <array>
  20. #include <cfloat>
  21. #include <cstdint>
  22. #include <cstring>
  23. #include <cinttypes>
  24. #include <functional>
  25. #include <memory>
  26. #include <random>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string>
  30. #include <thread>
  31. #include <future>
  32. #include <vector>
  33. static void init_tensor_uniform(ggml_tensor * tensor, float min = -1.0f, float max = 1.0f) {
  34. size_t nels = ggml_nelements(tensor);
  35. std::vector<float> data(nels);
  36. {
  37. // parallel initialization
  38. static const size_t n_threads = std::thread::hardware_concurrency();
  39. // static RNG initialization (revisit if n_threads stops being constant)
  40. static std::vector<std::default_random_engine> generators = []() {
  41. std::random_device rd;
  42. std::vector<std::default_random_engine> vec;
  43. vec.reserve(n_threads);
  44. //for (size_t i = 0; i < n_threads; i++) { vec.emplace_back(1234 + i); } // fixed seed
  45. for (size_t i = 0; i < n_threads; i++) { vec.emplace_back(rd()); }
  46. return vec;
  47. }();
  48. auto init_thread = [&](size_t ith, size_t start, size_t end) {
  49. std::uniform_real_distribution<float> distribution(min, max);
  50. auto & gen = generators[ith];
  51. for (size_t i = start; i < end; i++) {
  52. data[i] = distribution(gen);
  53. }
  54. };
  55. std::vector<std::future<void>> tasks;
  56. tasks.reserve(n_threads);
  57. for (size_t i = 0; i < n_threads; i++) {
  58. size_t start = i*nels/n_threads;
  59. size_t end = (i+1)*nels/n_threads;
  60. tasks.push_back(std::async(std::launch::async, init_thread, i, start, end));
  61. }
  62. for (auto & t : tasks) {
  63. t.get();
  64. }
  65. }
  66. if (tensor->type == GGML_TYPE_F32 || tensor->type == GGML_TYPE_I32) {
  67. ggml_backend_tensor_set(tensor, data.data(), 0, nels * sizeof(float));
  68. } else if (ggml_is_quantized(tensor->type) || tensor->type == GGML_TYPE_F16 || tensor->type == GGML_TYPE_BF16) {
  69. GGML_ASSERT(nels % ggml_blck_size(tensor->type) == 0);
  70. // dummy importance matrix
  71. std::vector<float> imatrix(tensor->ne[0], 1.0f);
  72. const float * im = imatrix.data();
  73. if (!ggml_quantize_requires_imatrix(tensor->type)) {
  74. // when the imatrix is optional, we want to test both quantization with and without imatrix
  75. // use one of the random numbers to decide
  76. if (data[0] > 0.5f*(min + max)) {
  77. im = nullptr;
  78. }
  79. }
  80. std::vector<uint8_t> dataq(ggml_row_size(tensor->type, nels));
  81. {
  82. // parallel quantization by block
  83. size_t blck_size = ggml_blck_size(tensor->type);
  84. size_t n_blocks = nels / blck_size;
  85. auto quantize_thread = [&](size_t start, size_t end) {
  86. ggml_quantize_chunk(tensor->type, data.data(), dataq.data(),
  87. start * blck_size, end - start, blck_size, im);
  88. };
  89. const size_t min_blocks_per_thread = 1;
  90. const size_t n_threads = std::min<size_t>(std::thread::hardware_concurrency()/2,
  91. std::max<size_t>(1, n_blocks / min_blocks_per_thread));
  92. std::vector<std::future<void>> tasks;
  93. tasks.reserve(n_threads);
  94. for (size_t i = 0; i < n_threads; i++) {
  95. size_t start = i*n_blocks/n_threads;
  96. size_t end = (i+1)*n_blocks/n_threads;
  97. tasks.push_back(std::async(std::launch::async, quantize_thread, start, end));
  98. }
  99. for (auto & t : tasks) {
  100. t.get();
  101. }
  102. }
  103. ggml_backend_tensor_set(tensor, dataq.data(), 0, dataq.size());
  104. } else if (tensor->type == GGML_TYPE_I8 || tensor->type == GGML_TYPE_I16 || tensor->type == GGML_TYPE_I32) {
  105. // This is going to create some weird integers though.
  106. ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor));
  107. } else if (tensor->type == GGML_TYPE_I64) {
  108. // Integers with a size of 8 bytes can be set by mirroring the float data, the specific values are again not really meaningful.
  109. const size_t nbytes_half = ggml_nbytes(tensor)/2;
  110. ggml_backend_tensor_set(tensor, data.data(), 0*nbytes_half, nbytes_half);
  111. ggml_backend_tensor_set(tensor, data.data(), 1*nbytes_half, nbytes_half);
  112. } else {
  113. GGML_ABORT("fatal error");
  114. }
  115. }
  116. static std::vector<float> tensor_to_float(const ggml_tensor * t) {
  117. std::vector<float> tv;
  118. tv.reserve(ggml_nelements(t));
  119. std::vector<uint8_t> buf(ggml_nbytes(t));
  120. ggml_backend_tensor_get(t, buf.data(), 0, ggml_nbytes(t));
  121. const auto * tt = ggml_get_type_traits(t->type);
  122. size_t bs = ggml_blck_size(t->type);
  123. std::vector<float> vq(ggml_blck_size(t->type));
  124. bool quantized = ggml_is_quantized(t->type);
  125. // access elements by index to avoid gaps in views
  126. for (int64_t i3 = 0; i3 < t->ne[3]; i3++) {
  127. for (int64_t i2 = 0; i2 < t->ne[2]; i2++) {
  128. for (int64_t i1 = 0; i1 < t->ne[1]; i1++) {
  129. for (int64_t i0 = 0; i0 < t->ne[0]; i0 += bs) {
  130. size_t i = i3*t->nb[3] + i2*t->nb[2] + i1*t->nb[1] + i0/bs*t->nb[0];
  131. if (t->type == GGML_TYPE_F16) {
  132. tv.push_back(ggml_fp16_to_fp32(*(ggml_fp16_t*)&buf[i]));
  133. } else if (t->type == GGML_TYPE_BF16) {
  134. tv.push_back(ggml_bf16_to_fp32(*(ggml_bf16_t*)&buf[i]));
  135. } else if (t->type == GGML_TYPE_F32) {
  136. tv.push_back(*(float *) &buf[i]);
  137. } else if (t->type == GGML_TYPE_I64) {
  138. tv.push_back((float)*(int64_t *) &buf[i]);
  139. } else if (t->type == GGML_TYPE_I32) {
  140. tv.push_back((float)*(int32_t *) &buf[i]);
  141. } else if (t->type == GGML_TYPE_I16) {
  142. tv.push_back((float)*(int16_t *) &buf[i]);
  143. } else if (t->type == GGML_TYPE_I8) {
  144. tv.push_back((float)*(int8_t *) &buf[i]);
  145. } else if (quantized) {
  146. tt->to_float(&buf[i], vq.data(), bs);
  147. tv.insert(tv.end(), vq.begin(), vq.end());
  148. } else {
  149. GGML_ABORT("fatal error");
  150. }
  151. }
  152. }
  153. }
  154. }
  155. return tv;
  156. }
  157. // normalized mean squared error = mse(a, b) / mse(a, 0)
  158. static double nmse(const float * a, const float * b, size_t n) {
  159. double mse_a_b = 0.0;
  160. double mse_a_0 = 0.0;
  161. for (size_t i = 0; i < n; i++) {
  162. float a_i = a[i];
  163. float b_i = b[i];
  164. mse_a_b += (a_i - b_i) * (a_i - b_i);
  165. mse_a_0 += a_i * a_i;
  166. }
  167. return mse_a_b / mse_a_0;
  168. }
  169. // maximum absolute asymmetry between a and b
  170. // asymmetry: (a - b) / (a + b)
  171. // This is more stable than relative error if one of the values fluctuates towards zero.
  172. // n: number of values to compare.
  173. // expected_vals: optional vector of expected values for a. If expected_vals is not empty, filter out all comparisons where
  174. // a does not match any of the expected values. Needed for noncontinuous gradients where the numerical calculation can fail.
  175. static double mean_abs_asymm(const float * a, const float * b, const size_t n, const std::vector<float> & expected_vals) {
  176. double sum = 0.0f;
  177. size_t nvalid = 0;
  178. for (size_t i = 0; i < n; i++) {
  179. if (!expected_vals.empty()) {
  180. bool matches_any = false;
  181. for (const float & ev : expected_vals) {
  182. if (fabsf(a[i] - ev) < 1e-3f) {
  183. matches_any = true;
  184. break;
  185. }
  186. }
  187. if (!matches_any) {
  188. continue;
  189. }
  190. }
  191. const float asymm = (a[i] - b[i]) / (a[i] + b[i]);
  192. sum += fabsf(asymm);
  193. nvalid++;
  194. }
  195. return sum/nvalid;
  196. }
  197. // utils for printing the variables of the test cases
  198. template<typename T>
  199. static std::string var_to_str(const T & x) {
  200. return std::to_string(x);
  201. }
  202. template<typename T, size_t N>
  203. static std::string var_to_str(const T (&x)[N]) {
  204. std::string s = "[";
  205. for (size_t i = 0; i < N; i++) {
  206. if (i > 0) {
  207. s += ",";
  208. }
  209. s += var_to_str(x[i]);
  210. }
  211. s += "]";
  212. return s;
  213. }
  214. template<typename T, size_t N>
  215. static std::string var_to_str(const std::array<T, N> & x) {
  216. std::string s = "[";
  217. for (size_t i = 0; i < N; i++) {
  218. if (i > 0) {
  219. s += ",";
  220. }
  221. s += var_to_str(x[i]);
  222. }
  223. s += "]";
  224. return s;
  225. }
  226. static std::string var_to_str(ggml_type type) {
  227. return ggml_type_name(type);
  228. }
  229. static std::string var_to_str(ggml_op_pool pool) {
  230. switch (pool) {
  231. case GGML_OP_POOL_AVG: return "avg";
  232. case GGML_OP_POOL_MAX: return "max";
  233. default: return std::to_string(pool);
  234. }
  235. }
  236. #define VAR_TO_STR(x) (#x "=" + var_to_str(x))
  237. #define VARS_TO_STR1(a) VAR_TO_STR(a)
  238. #define VARS_TO_STR2(a, b) VAR_TO_STR(a) + "," + VAR_TO_STR(b)
  239. #define VARS_TO_STR3(a, b, c) VAR_TO_STR(a) + "," + VARS_TO_STR2(b, c)
  240. #define VARS_TO_STR4(a, b, c, d) VAR_TO_STR(a) + "," + VARS_TO_STR3(b, c, d)
  241. #define VARS_TO_STR5(a, b, c, d, e) VAR_TO_STR(a) + "," + VARS_TO_STR4(b, c, d, e)
  242. #define VARS_TO_STR6(a, b, c, d, e, f) VAR_TO_STR(a) + "," + VARS_TO_STR5(b, c, d, e, f)
  243. #define VARS_TO_STR7(a, b, c, d, e, f, g) VAR_TO_STR(a) + "," + VARS_TO_STR6(b, c, d, e, f, g)
  244. #define VARS_TO_STR8(a, b, c, d, e, f, g, h) VAR_TO_STR(a) + "," + VARS_TO_STR7(b, c, d, e, f, g, h)
  245. #define VARS_TO_STR9(a, b, c, d, e, f, g, h, i) VAR_TO_STR(a) + "," + VARS_TO_STR8(b, c, d, e, f, g, h, i)
  246. #define VARS_TO_STR10(a, b, c, d, e, f, g, h, i, j) VAR_TO_STR(a) + "," + VARS_TO_STR9(b, c, d, e, f, g, h, i, j)
  247. #define VARS_TO_STR11(a, b, c, d, e, f, g, h, i, j, k) VAR_TO_STR(a) + "," + VARS_TO_STR10(b, c, d, e, f, g, h, i, j, k)
  248. #define VARS_TO_STR12(a, b, c, d, e, f, g, h, i, j, k, l) VAR_TO_STR(a) + "," + VARS_TO_STR11(b, c, d, e, f, g, h, i, j, k, l)
  249. #ifdef GGML_USE_SYCL
  250. static bool inline _isinf(float f) {
  251. return (*(uint32_t *)&f & 0x7fffffff) == 0x7f800000;
  252. }
  253. #else
  254. static bool inline _isinf(float f) { return std::isinf(f); }
  255. #endif
  256. // accept FLT_MAX as infinity
  257. static bool isinf_or_max(float f) {
  258. return _isinf(f) || f == FLT_MAX || f == -FLT_MAX;
  259. }
  260. static bool ggml_is_view_op(enum ggml_op op) {
  261. return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE;
  262. }
  263. enum test_mode {
  264. MODE_TEST,
  265. MODE_PERF,
  266. MODE_GRAD,
  267. };
  268. struct test_case {
  269. virtual ~test_case() {}
  270. virtual std::string op_desc(ggml_tensor * t) {
  271. return ggml_op_desc(t);
  272. }
  273. virtual std::string vars() {
  274. return "";
  275. }
  276. virtual ggml_tensor * build_graph(ggml_context * ctx) = 0;
  277. virtual double max_nmse_err() {
  278. return 1e-7;
  279. }
  280. virtual double max_maa_err() {
  281. return 1e-4;
  282. }
  283. virtual float grad_eps() {
  284. return 1e-1f;
  285. }
  286. // If false, estimate gradient with 2 points, neglects 3rd order derivative and higher.
  287. // If true, estimate gradient with 4 points, neglects 5th order derivative and higher.
  288. virtual bool grad_precise() {
  289. return false;
  290. }
  291. // Skip gradient checks if total number of gradients to be checked is larger than this (to speed up the tests).
  292. virtual int64_t grad_nmax() {
  293. return 10000;
  294. }
  295. // No effect if empty.
  296. // If not empty, skip all gradient checks where the numerical result does not match any of the values.
  297. // Needed for dealing with noncontinuous gradients (e.g. ReLU) where estimation using finite differences is unreliable.
  298. virtual std::vector<float> grad_expect() {
  299. return {};
  300. }
  301. virtual void initialize_tensors(ggml_context * ctx) {
  302. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
  303. init_tensor_uniform(t);
  304. }
  305. }
  306. virtual size_t op_size(ggml_tensor * t) {
  307. size_t size = ggml_nbytes(t);
  308. // add source tensors
  309. for (int i = 0; i < GGML_MAX_SRC; i++) {
  310. if (t->src[i] != NULL) {
  311. size += ggml_nbytes(t->src[i]);
  312. }
  313. }
  314. return size;
  315. }
  316. virtual uint64_t op_flops(ggml_tensor * t) {
  317. GGML_UNUSED(t);
  318. return 0;
  319. }
  320. ggml_cgraph * gf = nullptr;
  321. ggml_cgraph * gb = nullptr;
  322. static const int sentinel_size = 1024;
  323. test_mode mode;
  324. std::vector<ggml_tensor *> sentinels;
  325. void add_sentinel(ggml_context * ctx) {
  326. if (mode == MODE_PERF || mode == MODE_GRAD) {
  327. return;
  328. }
  329. ggml_tensor * sentinel = ::ggml_new_tensor_1d(ctx, GGML_TYPE_F32, sentinel_size);
  330. ggml_format_name(sentinel, "sent_%zu", sentinels.size());
  331. sentinels.push_back(sentinel);
  332. }
  333. // hijack ggml_new_tensor to add sentinels after each tensor to check for overflows in the backend
  334. ggml_tensor * ggml_new_tensor(ggml_context * ctx, ggml_type type, int n_dims, const int64_t * ne) {
  335. ggml_tensor * t = ::ggml_new_tensor(ctx, type, n_dims, ne);
  336. add_sentinel(ctx);
  337. return t;
  338. }
  339. ggml_tensor * ggml_new_tensor_1d(ggml_context * ctx, ggml_type type, int64_t ne0) {
  340. ggml_tensor * t = ::ggml_new_tensor_1d(ctx, type, ne0);
  341. add_sentinel(ctx);
  342. return t;
  343. }
  344. ggml_tensor * ggml_new_tensor_2d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1) {
  345. ggml_tensor * t = ::ggml_new_tensor_2d(ctx, type, ne0, ne1);
  346. add_sentinel(ctx);
  347. return t;
  348. }
  349. ggml_tensor * ggml_new_tensor_3d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1, int64_t ne2) {
  350. ggml_tensor * t = ::ggml_new_tensor_3d(ctx, type, ne0, ne1, ne2);
  351. add_sentinel(ctx);
  352. return t;
  353. }
  354. ggml_tensor * ggml_new_tensor_4d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  355. ggml_tensor * t = ::ggml_new_tensor_4d(ctx, type, ne0, ne1, ne2, ne3);
  356. add_sentinel(ctx);
  357. return t;
  358. }
  359. bool eval(ggml_backend_t backend1, ggml_backend_t backend2, const char * op_name) {
  360. mode = MODE_TEST;
  361. ggml_init_params params = {
  362. /* .mem_size = */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  363. /* .mem_base = */ NULL,
  364. /* .no_alloc = */ true,
  365. };
  366. ggml_context * ctx = ggml_init(params);
  367. GGML_ASSERT(ctx);
  368. gf = ggml_new_graph(ctx);
  369. // pre-graph sentinel
  370. add_sentinel(ctx);
  371. ggml_tensor * out = build_graph(ctx);
  372. if (op_name != nullptr && op_desc(out) != op_name) {
  373. //printf(" %s: skipping\n", op_desc(out).c_str());
  374. ggml_free(ctx);
  375. return true;
  376. }
  377. printf(" %s(%s): ", op_desc(out).c_str(), vars().c_str());
  378. fflush(stdout);
  379. // check if the backends support the ops
  380. bool supported = true;
  381. for (ggml_backend_t backend : {backend1, backend2}) {
  382. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  383. if (!ggml_backend_supports_op(backend, t)) {
  384. printf("not supported [%s] ", ggml_backend_name(backend));
  385. supported = false;
  386. break;
  387. }
  388. }
  389. }
  390. if (!supported) {
  391. printf("\n");
  392. ggml_free(ctx);
  393. return true;
  394. }
  395. // post-graph sentinel
  396. add_sentinel(ctx);
  397. // allocate
  398. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend1);
  399. if (buf == NULL) {
  400. printf("failed to allocate tensors [%s] ", ggml_backend_name(backend1));
  401. ggml_free(ctx);
  402. return false;
  403. }
  404. // build graph
  405. ggml_build_forward_expand(gf, out);
  406. // add sentinels as graph nodes so that they are checked in the callback
  407. for (ggml_tensor * sentinel : sentinels) {
  408. ggml_graph_add_node(gf, sentinel);
  409. }
  410. // randomize tensors
  411. initialize_tensors(ctx);
  412. // compare
  413. struct callback_userdata {
  414. bool ok;
  415. double max_err;
  416. ggml_backend_t backend1;
  417. ggml_backend_t backend2;
  418. };
  419. callback_userdata ud {
  420. true,
  421. max_nmse_err(),
  422. backend1,
  423. backend2
  424. };
  425. auto callback = [](int index, ggml_tensor * t1, ggml_tensor * t2, void * user_data) -> bool {
  426. callback_userdata * ud = (callback_userdata *) user_data;
  427. const char * bn1 = ggml_backend_name(ud->backend1);
  428. const char * bn2 = ggml_backend_name(ud->backend2);
  429. if (t1->op == GGML_OP_NONE) {
  430. // sentinels must be unchanged
  431. std::vector<uint8_t> t1_data(ggml_nbytes(t1));
  432. std::vector<uint8_t> t2_data(ggml_nbytes(t2));
  433. ggml_backend_tensor_get(t1, t1_data.data(), 0, ggml_nbytes(t1));
  434. ggml_backend_tensor_get(t2, t2_data.data(), 0, ggml_nbytes(t2));
  435. if (memcmp(t1_data.data(), t2_data.data(), ggml_nbytes(t1)) != 0) {
  436. printf("sentinel mismatch: %s ", t1->name);
  437. ud->ok = false;
  438. return true;
  439. }
  440. }
  441. std::vector<float> f1 = tensor_to_float(t1);
  442. std::vector<float> f2 = tensor_to_float(t2);
  443. for (size_t i = 0; i < f1.size(); i++) {
  444. // check for nans
  445. if (std::isnan(f1[i]) || std::isnan(f2[i])) {
  446. printf("[%s] NaN at index %zu (%s=%f %s=%f) ", ggml_op_desc(t1), i, bn1, f1[i], bn2, f2[i]);
  447. ud->ok = false;
  448. return true;
  449. }
  450. // check for infs: both must be inf of the same sign, or both must be finite
  451. if (isinf_or_max(f1[i]) || isinf_or_max(f2[i])) {
  452. if (isinf_or_max(f1[i]) && isinf_or_max(f2[i])) {
  453. if (std::signbit(f1[i]) != std::signbit(f2[i])) {
  454. printf("[%s] inf sign mismatch: %s=%f %s=%f ", ggml_op_desc(t1), bn1, f1[i], bn2, f2[i]);
  455. ud->ok = false;
  456. return true;
  457. }
  458. } else {
  459. printf("[%s] inf mismatch: %s=%f %s=%f ", ggml_op_desc(t1), bn1, f1[i], bn2, f2[i]);
  460. ud->ok = false;
  461. return true;
  462. }
  463. }
  464. }
  465. double err = nmse(f1.data(), f2.data(), f1.size());
  466. if (err > ud->max_err) {
  467. printf("[%s] NMSE = %.9f > %.9f ", ggml_op_desc(t1), err, ud->max_err);
  468. //for (int i = 0; i < (int) f1.size(); i++) {
  469. // printf("%5d %9.6f %9.6f, diff = %9.6f\n", i, f1[i], f2[i], f1[i] - f2[i]);
  470. //}
  471. //printf("\n");
  472. //exit(1);
  473. ud->ok = false;
  474. }
  475. return true;
  476. GGML_UNUSED(index);
  477. };
  478. const bool cmp_ok = ggml_backend_compare_graph_backend(backend1, backend2, gf, callback, &ud);
  479. if (!cmp_ok) {
  480. printf("compare failed ");
  481. }
  482. ggml_backend_buffer_free(buf);
  483. ggml_free(ctx);
  484. if (ud.ok && cmp_ok) {
  485. printf("\033[1;32mOK\033[0m\n");
  486. return true;
  487. }
  488. printf("\033[1;31mFAIL\033[0m\n");
  489. return false;
  490. }
  491. bool eval_perf(ggml_backend_t backend, const char * op_name) {
  492. mode = MODE_PERF;
  493. static const size_t graph_nodes = 8192;
  494. ggml_init_params params = {
  495. /* .mem_size = */ ggml_tensor_overhead()*128 + ggml_graph_overhead_custom(graph_nodes, false),
  496. /* .mem_base = */ NULL,
  497. /* .no_alloc = */ true,
  498. };
  499. ggml_context * ctx = ggml_init(params);
  500. GGML_ASSERT(ctx);
  501. ggml_tensor * out = build_graph(ctx);
  502. if (op_name != nullptr && op_desc(out) != op_name) {
  503. //printf(" %s: skipping\n", op_desc(out).c_str());
  504. ggml_free(ctx);
  505. return true;
  506. }
  507. int len = printf(" %s(%s): ", op_desc(out).c_str(), vars().c_str());
  508. fflush(stdout);
  509. // check if backends support op
  510. if (!ggml_backend_supports_op(backend, out)) {
  511. printf("not supported\n");
  512. ggml_free(ctx);
  513. return true;
  514. }
  515. // align while also leaving some margin for variations in parameters
  516. int align = 8;
  517. int last = (len + align - 1) / align * align;
  518. if (last - len < 5) {
  519. last += align;
  520. }
  521. printf("%*s", last - len, "");
  522. // allocate
  523. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend);
  524. if (buf == NULL) {
  525. printf("failed to allocate tensors\n");
  526. ggml_free(ctx);
  527. return false;
  528. }
  529. // randomize tensors
  530. initialize_tensors(ctx);
  531. // build graph
  532. ggml_cgraph * gf = ggml_new_graph_custom(ctx, graph_nodes, false);
  533. ggml_build_forward_expand(gf, out);
  534. // warmup run
  535. ggml_backend_graph_compute(backend, gf);
  536. // determine number of runs
  537. int n_runs;
  538. if (op_flops(out) > 0) {
  539. // based on flops
  540. const uint64_t GFLOP = 1000 * 1000 * 1000;
  541. const uint64_t target_flops_cpu = 8ULL * GFLOP;
  542. const uint64_t target_flops_gpu = 100ULL * GFLOP;
  543. uint64_t target_flops = ggml_backend_is_cpu(backend) ? target_flops_cpu : target_flops_gpu;
  544. n_runs = std::min<int>(ggml_graph_size(gf) - ggml_graph_n_nodes(gf), target_flops / op_flops(out)) + 1;
  545. } else {
  546. // based on memory size
  547. const size_t GB = 1ULL << 30;
  548. const size_t target_size_cpu = 8 * GB;
  549. const size_t target_size_gpu = 32 * GB;
  550. size_t target_size = ggml_backend_is_cpu(backend) ? target_size_cpu : target_size_gpu;
  551. n_runs = std::min<int>(ggml_graph_size(gf) - ggml_graph_n_nodes(gf), target_size / op_size(out)) + 1;
  552. }
  553. // duplicate the op
  554. for (int i = 1; i < n_runs; i++) {
  555. ggml_graph_add_node(gf, out);
  556. }
  557. // calculate memory
  558. size_t mem = n_runs * op_size(out);
  559. auto tensor_op_size = [](ggml_tensor * t) {
  560. size_t size = ggml_nbytes(t);
  561. // add source tensors
  562. for (int i = 0; i < GGML_MAX_SRC; i++) {
  563. if (t->src[i] != NULL) {
  564. size += ggml_nbytes(t->src[i]);
  565. }
  566. }
  567. return size;
  568. };
  569. for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) {
  570. if (ggml_is_view_op(ggml_graph_node(gf, i)->op) || ggml_graph_node(gf, i) == out) {
  571. continue;
  572. }
  573. mem += tensor_op_size(ggml_graph_node(gf, i));
  574. }
  575. // run
  576. int64_t total_time_us = 0;
  577. int64_t total_mem = 0;
  578. int total_runs = 0;
  579. do {
  580. int64_t start_time = ggml_time_us();
  581. ggml_backend_graph_compute(backend, gf);
  582. int64_t end_time = ggml_time_us();
  583. total_time_us += end_time - start_time;
  584. total_mem += mem;
  585. total_runs += n_runs;
  586. } while (total_time_us < 1000*1000); // run for at least 1 second
  587. printf(" %8d runs - %8.2f us/run - ",
  588. total_runs,
  589. (double)total_time_us / total_runs);
  590. if (op_flops(out) > 0) {
  591. double flops_per_sec = (op_flops(out) * total_runs) / (total_time_us / 1e6);
  592. auto format_flops = [](double flops) -> std::string {
  593. char buf[256];
  594. if (flops >= 1e12) {
  595. snprintf(buf, sizeof(buf), "%6.2f TFLOP", flops / 1e12);
  596. } else if (flops >= 1e9) {
  597. snprintf(buf, sizeof(buf), "%6.2f GFLOP", flops / 1e9);
  598. } else if (flops >= 1e6) {
  599. snprintf(buf, sizeof(buf), "%6.2f MFLOP", flops / 1e6);
  600. } else {
  601. snprintf(buf, sizeof(buf), "%6.2f KFLOP", flops / 1e3);
  602. }
  603. return buf;
  604. };
  605. printf("%s/run - \033[1;34m%sS\033[0m",
  606. format_flops(op_flops(out)).c_str(),
  607. format_flops(flops_per_sec).c_str());
  608. } else {
  609. printf("%8zu kB/run - \033[1;34m%7.2f GB/s\033[0m",
  610. op_size(out) / 1024,
  611. total_mem / (total_time_us / 1e6) / 1024.0 / 1024.0 / 1024.0);
  612. }
  613. printf("\n");
  614. ggml_backend_buffer_free(buf);
  615. ggml_free(ctx);
  616. return true;
  617. }
  618. bool eval_grad(ggml_backend_t backend, const char * op_name) {
  619. mode = MODE_GRAD;
  620. const std::vector<float> expect = grad_expect();
  621. ggml_init_params params = {
  622. /* .mem_size = */ ggml_tensor_overhead()*128 + 2*ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, true),
  623. /* .mem_base = */ NULL,
  624. /* .no_alloc = */ true,
  625. };
  626. ggml_context * ctx = ggml_init(params);
  627. GGML_ASSERT(ctx);
  628. gf = ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, true);
  629. gb = ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, true);
  630. ggml_tensor * out = build_graph(ctx);
  631. if ((op_name != nullptr && op_desc(out) != op_name) || out->op == GGML_OP_OPT_STEP_ADAMW) {
  632. //printf(" %s: skipping\n", op_desc(out).c_str());
  633. ggml_free(ctx);
  634. return true;
  635. }
  636. printf(" %s(%s): ", op_desc(out).c_str(), vars().c_str());
  637. fflush(stdout);
  638. if (out->type != GGML_TYPE_F32) {
  639. ggml_free(ctx);
  640. printf("not supported [%s->type != FP32]\n", out->name);
  641. return true;
  642. }
  643. // check if the backend supports the ops
  644. bool supported = true;
  645. bool any_params = false;
  646. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  647. if (!ggml_backend_supports_op(backend, t)) {
  648. printf("not supported [%s] ", ggml_backend_name(backend));
  649. supported = false;
  650. break;
  651. }
  652. if ((t->flags & GGML_TENSOR_FLAG_PARAM)) {
  653. any_params = true;
  654. if (t->type != GGML_TYPE_F32) {
  655. printf("not supported [%s->type != FP32] ", t->name);
  656. supported = false;
  657. break;
  658. }
  659. }
  660. }
  661. if (!any_params) {
  662. printf("not supported [%s] \n", op_name);
  663. supported = false;
  664. }
  665. if (!supported) {
  666. printf("\n");
  667. ggml_free(ctx);
  668. return true;
  669. }
  670. int64_t ngrads = 0;
  671. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  672. if (t->flags & GGML_TENSOR_FLAG_PARAM) {
  673. ngrads += ggml_nelements(t);
  674. }
  675. }
  676. if (ngrads > grad_nmax()) {
  677. printf("skipping large tensors for speed \n");
  678. ggml_free(ctx);
  679. return true;
  680. }
  681. if (!ggml_is_scalar(out)) {
  682. out = ggml_sum(ctx, out);
  683. ggml_set_name(out, "sum_of_out");
  684. }
  685. ggml_set_loss(out);
  686. ggml_build_forward_expand(gf, out);
  687. ggml_graph_cpy(gf, gb);
  688. ggml_build_backward_expand(ctx, gf, gb, false);
  689. if (expect.size() != 1 || expect[0] != 0.0f) {
  690. GGML_ASSERT(ggml_graph_n_nodes(gb) > ggml_graph_n_nodes(gf));
  691. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  692. GGML_ASSERT(!(t->flags & GGML_TENSOR_FLAG_PARAM) || t->grad->op != GGML_OP_NONE);
  693. }
  694. }
  695. // TODO: refactor so that this check is only needed once
  696. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  697. if (!ggml_backend_supports_op(backend, t)) {
  698. printf("not supported [%s] ", ggml_backend_name(backend));
  699. supported = false;
  700. break;
  701. }
  702. if ((t->flags & GGML_TENSOR_FLAG_PARAM) && t->type != GGML_TYPE_F32) {
  703. printf("not supported [%s->type != FP32] ", t->name);
  704. supported = false;
  705. break;
  706. }
  707. }
  708. if (!supported) {
  709. printf("\n");
  710. ggml_free(ctx);
  711. return true;
  712. }
  713. // allocate
  714. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend);
  715. if (buf == NULL) {
  716. printf("failed to allocate tensors [%s] ", ggml_backend_name(backend));
  717. ggml_free(ctx);
  718. return false;
  719. }
  720. initialize_tensors(ctx); // Randomizes all tensors (including gradients).
  721. ggml_graph_reset(gb); // Sets gradients to 1 if loss, 0 otherwise.
  722. ggml_backend_graph_compute(backend, gf);
  723. ggml_backend_graph_compute(backend, gb);
  724. bool ok = true;
  725. for (struct ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
  726. if (!(t->flags & GGML_TENSOR_FLAG_PARAM)) {
  727. continue;
  728. }
  729. const char * bn = ggml_backend_name(backend);
  730. const int64_t ne = ggml_nelements(t);
  731. std::vector<float> ga = tensor_to_float(t->grad);
  732. for (int64_t i = 0; i < ne; ++i) { // gradient algebraic
  733. // check for nans
  734. if (!std::isfinite(ga[i])) {
  735. printf("[%s] nonfinite gradient at index %" PRId64 " (%s=%f) ", ggml_op_desc(t), i, bn, ga[i]);
  736. ok = false;
  737. break;
  738. }
  739. }
  740. if (!ok) {
  741. break;
  742. }
  743. std::vector<float> gn(ne); // gradient numeric
  744. GGML_ASSERT(ga.size() == gn.size());
  745. std::vector<float> x0 = tensor_to_float(t); // original t data
  746. GGML_ASSERT(ggml_is_scalar(out));
  747. GGML_ASSERT(out->type == GGML_TYPE_F32);
  748. const float eps = grad_eps();
  749. for (int64_t i = 0; i < ne; ++i) {
  750. const float xiu = x0[i] + 1.0f*eps; // x, index i, up
  751. const float xiuh = x0[i] + 0.5f*eps; // x, index i, up half
  752. const float xidh = x0[i] - 0.5f*eps; // x, index i, down half
  753. const float xid = x0[i] - 1.0f*eps; // x, index i, down
  754. float fu, fuh, fdh, fd; // output values for xiu, xiuh, xid, xidh
  755. ggml_backend_tensor_set(t, &xiu, i*sizeof(float), sizeof(float));
  756. ggml_backend_graph_compute(backend, gf);
  757. ggml_backend_tensor_get(out, &fu, 0, ggml_nbytes(out));
  758. ggml_backend_tensor_set(t, &xid, i*sizeof(float), sizeof(float));
  759. ggml_backend_graph_compute(backend, gf);
  760. ggml_backend_tensor_get(out, &fd, 0, ggml_nbytes(out));
  761. if (grad_precise()) {
  762. ggml_backend_tensor_set(t, &xiuh, i*sizeof(float), sizeof(float));
  763. ggml_backend_graph_compute(backend, gf);
  764. ggml_backend_tensor_get(out, &fuh, 0, ggml_nbytes(out));
  765. ggml_backend_tensor_set(t, &xidh, i*sizeof(float), sizeof(float));
  766. ggml_backend_graph_compute(backend, gf);
  767. ggml_backend_tensor_get(out, &fdh, 0, ggml_nbytes(out));
  768. gn[i] = (8.0*(double)fuh + (double)fd - (8.0*(double)fdh + (double)fu)) / (6.0*(double)eps);
  769. } else {
  770. gn[i] = (fu - fd) / (2.0f*eps);
  771. }
  772. ggml_backend_tensor_set(t, x0.data(), 0, ggml_nbytes(t));
  773. }
  774. const double err = mean_abs_asymm(gn.data(), ga.data(), gn.size(), expect);
  775. if (err > max_maa_err()) {
  776. printf("[%s] MAA = %.9f > %.9f ", ggml_op_desc(t), err, max_maa_err());
  777. ok = false;
  778. break;
  779. }
  780. if (!ok) {
  781. break;
  782. }
  783. }
  784. if (!ok) {
  785. printf("compare failed ");
  786. }
  787. ggml_backend_buffer_free(buf);
  788. ggml_free(ctx);
  789. if (ok) {
  790. printf("\033[1;32mOK\033[0m\n");
  791. return true;
  792. }
  793. printf("\033[1;31mFAIL\033[0m\n");
  794. return false;
  795. }
  796. };
  797. // ###################################
  798. // ## Section 2: GGML Op Defintions ##
  799. // ###################################
  800. // The following is an example showing the bare minimum for creating a test for a GGML op.
  801. // GGML_OP_EXAMPLE
  802. struct test_example : public test_case {
  803. // Always define these 2 or variants thereof:
  804. const ggml_type type; // The type of the input tensors.
  805. const std::array<int64_t, 4> ne; // The shape of the input tensors.
  806. // For some ops it's necessary to define multiple types or shapes for the inputs.
  807. // Or they may need additional parameters.
  808. // Put all parameters needed to fully define the test into one of the VARS_TO_STR macros.
  809. // In most cases these are just the properties of the struct that you defined above.
  810. // This is needed for info prints.
  811. std::string vars() override {
  812. return VARS_TO_STR2(type, ne);
  813. }
  814. // Define a constructor for the struct.
  815. // In most cases it will be sufficient to have the same arguments as the struct has properties
  816. // and just use initializer lists.
  817. test_example(ggml_type type = GGML_TYPE_F32,
  818. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  819. : type(type), ne(ne) {}
  820. // Define how a simple GGML compute graph can be constructed for the new GGML op.
  821. ggml_tensor * build_graph(ggml_context * ctx) override {
  822. // Step 1: create input tensors that don't depend on any other tensors:
  823. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  824. ggml_set_name(a, "a"); // Setting names is optional but it's useful for debugging.
  825. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  826. ggml_set_name(b, "b");
  827. // Step 2: use the op that you want to test in the GGML compute graph.
  828. ggml_tensor * out = ggml_add(ctx, a, b); // For this example we're just doing a simple addition.
  829. ggml_set_name(out, "out");
  830. // Step 3: return the output tensor.
  831. return out;
  832. }
  833. // In order to also check the gradients for your op, add calls like ggml_set_param(ctx, a)
  834. // immediately after you create the tensors.
  835. // This is optional and only makes sense if a backward pass has actually been implemented for the new op.
  836. };
  837. // GGML_OP_UNARY
  838. struct test_unary : public test_case {
  839. const ggml_unary_op op;
  840. const ggml_type type;
  841. const std::array<int64_t, 4> ne_a;
  842. int v; // view (1 : non-contiguous a)
  843. std::string vars() override {
  844. return VARS_TO_STR3(type, ne_a, v);
  845. }
  846. test_unary(ggml_unary_op op,
  847. ggml_type type = GGML_TYPE_F32,
  848. std::array<int64_t, 4> ne_a = {128, 2, 2, 2},
  849. int v = 0)
  850. : op(op), type(type), ne_a(ne_a), v(v) {}
  851. ggml_tensor * build_graph(ggml_context * ctx) override {
  852. const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG ||
  853. op == GGML_UNARY_OP_STEP || op == GGML_UNARY_OP_RELU || op == GGML_UNARY_OP_SILU;
  854. ggml_tensor * a;
  855. if (v & 1) {
  856. auto ne = ne_a; ne[0] *= 3;
  857. a = ggml_new_tensor(ctx, type, 4, ne.data());
  858. if (grad_supported) {
  859. ggml_set_param(ctx, a);
  860. }
  861. ggml_set_name(a, "a");
  862. a = ggml_view_4d(ctx, a, ne_a[0], ne_a[1], ne_a[2], ne_a[3], a->nb[1], a->nb[2], a->nb[3], 0);
  863. ggml_set_name(a, "view_of_a");
  864. } else {
  865. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  866. if (grad_supported) {
  867. ggml_set_param(ctx, a);
  868. }
  869. ggml_set_name(a, "a");
  870. }
  871. ggml_tensor * out = ggml_unary(ctx, a, op);
  872. ggml_set_name(out, "out");
  873. return out;
  874. }
  875. void initialize_tensors(ggml_context * ctx) override {
  876. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  877. // test extended range of values to check for NaNs in GELU
  878. init_tensor_uniform(t, -150.f, 150.f);
  879. }
  880. }
  881. float grad_eps() override {
  882. return 15.0f;
  883. }
  884. std::vector<float> grad_expect() override {
  885. if (op == GGML_UNARY_OP_ABS) {
  886. return {-1.0f, 1.0f};
  887. }
  888. if (op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_STEP) {
  889. return {0.0f};
  890. }
  891. if (op == GGML_UNARY_OP_RELU) {
  892. return {0.0f, 1.0f};
  893. }
  894. return {};
  895. }
  896. };
  897. // GGML_OP_GET_ROWS
  898. struct test_get_rows : public test_case {
  899. const ggml_type type;
  900. const int n; // cols
  901. const int m; // rows
  902. const int r; // rows to get
  903. const int b; // batch size
  904. const bool v; // view (non-contiguous src1)
  905. std::string vars() override {
  906. return VARS_TO_STR6(type, n, m, r, b, v);
  907. }
  908. test_get_rows(ggml_type type = GGML_TYPE_F32, int n = 10, int m = 5, int r = 3, int b = 1, bool v = false)
  909. : type(type), n(n), m(m), r(r), b(b), v(v) {}
  910. ggml_tensor * build_graph(ggml_context * ctx) override {
  911. ggml_tensor * in = ggml_new_tensor_3d(ctx, type, n, m, b);
  912. ggml_set_name(in, "in");
  913. ggml_tensor * rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, r, b);
  914. ggml_set_name(rows, "rows");
  915. if (v) {
  916. rows = ggml_view_2d(ctx, rows, r/2, b, rows->nb[1], 0);
  917. ggml_set_name(rows, "view_of_rows");
  918. }
  919. const bool grad_supported = ggml_is_matrix(in) && ggml_is_vector(rows);
  920. if (grad_supported) {
  921. ggml_set_param(ctx, in);
  922. // rows is a constant input -> no gradients
  923. }
  924. ggml_tensor * out = ggml_get_rows(ctx, in, rows);
  925. ggml_set_name(out, "out");
  926. return out;
  927. }
  928. void initialize_tensors(ggml_context * ctx) override {
  929. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  930. if (t->type == GGML_TYPE_I32) {
  931. if (ggml_is_view_op(t->op)) { continue; }
  932. // rows
  933. std::vector<int> data(r*b);
  934. for (int i = 0; i < r*b; i++) {
  935. data[i] = rand() % m;
  936. }
  937. ggml_backend_tensor_set(t, data.data(), 0, r * b * sizeof(int));
  938. } else {
  939. init_tensor_uniform(t);
  940. }
  941. }
  942. }
  943. };
  944. // GGML_OP_ARGMAX
  945. struct test_argmax : public test_case {
  946. const ggml_type type;
  947. const std::array<int64_t, 4> ne;
  948. std::string vars() override {
  949. return VARS_TO_STR2(type, ne);
  950. }
  951. test_argmax(ggml_type type = GGML_TYPE_F32,
  952. std::array<int64_t, 4> ne = {10, 100, 1, 1})
  953. : type(type), ne(ne) {}
  954. ggml_tensor * build_graph(ggml_context * ctx) override {
  955. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  956. ggml_set_name(a, "a");
  957. ggml_tensor * out = ggml_argmax(ctx, a);
  958. ggml_set_name(out, "out");
  959. return out;
  960. }
  961. double max_nmse_err() override {
  962. return 0.0;
  963. }
  964. };
  965. // GGML_OP_COUNT_EQUAL
  966. struct test_count_equal : public test_case {
  967. const ggml_type type;
  968. const std::array<int64_t, 4> ne;
  969. std::string vars() override {
  970. return VARS_TO_STR2(type, ne);
  971. }
  972. test_count_equal(ggml_type type = GGML_TYPE_F32,
  973. std::array<int64_t, 4> ne = {4, 500, 1, 1})
  974. : type(type), ne(ne) {}
  975. ggml_tensor * build_graph(ggml_context * ctx) override {
  976. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  977. ggml_set_name(a, "a");
  978. ggml_tensor * a_argmax = ggml_argmax(ctx, a);
  979. ggml_set_name(a_argmax, "a_argmax");
  980. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  981. ggml_set_name(b, "b");
  982. ggml_tensor * b_argmax = ggml_argmax(ctx, a);
  983. ggml_set_name(b_argmax, "b_argmax");
  984. ggml_tensor * out = ggml_count_equal(ctx, a_argmax, b_argmax);
  985. ggml_set_name(out, "out");
  986. return out;
  987. }
  988. double max_nmse_err() override {
  989. return 0.0;
  990. }
  991. };
  992. // GGML_OP_REPEAT
  993. struct test_repeat : public test_case {
  994. const ggml_type type;
  995. const std::array<int64_t, 4> ne;
  996. const std::array<int, 4> nr;
  997. std::string vars() override {
  998. return VARS_TO_STR3(type, ne, nr);
  999. }
  1000. size_t op_size(ggml_tensor * t) override {
  1001. return ggml_nbytes(t) * 2;
  1002. }
  1003. test_repeat(ggml_type type = GGML_TYPE_F32,
  1004. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  1005. std::array<int, 4> nr = {2, 2, 2, 2})
  1006. : type(type), ne(ne), nr(nr) {}
  1007. ggml_tensor * build_graph(ggml_context * ctx) override {
  1008. ggml_tensor * target = ggml_new_tensor_4d(ctx, type, ne[0]*nr[0], ne[1]*nr[1], ne[2]*nr[2], ne[3]*nr[3]);
  1009. ggml_set_name(target, "target");
  1010. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1011. ggml_set_param(ctx, src);
  1012. ggml_set_name(src, "src");
  1013. ggml_tensor * out = ggml_repeat(ctx, src, target);
  1014. ggml_set_name(out, "out");
  1015. return out;
  1016. }
  1017. };
  1018. // GGML_OP_DUP
  1019. struct test_dup : public test_case {
  1020. const ggml_type type;
  1021. const std::array<int64_t, 4> ne;
  1022. const std::array<int64_t, 4> permute;
  1023. bool _use_permute;
  1024. std::string vars() override {
  1025. std::string v = VARS_TO_STR2(type, ne);
  1026. if (_use_permute) v += "," + VAR_TO_STR(permute);
  1027. return v;
  1028. }
  1029. test_dup(ggml_type type = GGML_TYPE_F32,
  1030. std::array<int64_t, 4> ne = {10, 10, 20, 1},
  1031. std::array<int64_t, 4> permute = {0, 0, 0, 0})
  1032. : type(type), ne(ne), permute(permute),
  1033. _use_permute(permute[0] + permute[1] + permute[2] + permute[3] > 0) {}
  1034. ggml_tensor * build_graph(ggml_context * ctx) override {
  1035. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1036. ggml_set_param(ctx, src);
  1037. ggml_set_name(src, "src");
  1038. if (_use_permute) {
  1039. src = ggml_permute(ctx, src, permute[0], permute[1], permute[2], permute[3]);
  1040. ggml_set_name(src, "src_permuted");
  1041. }
  1042. ggml_tensor * out = ggml_dup(ctx, src);
  1043. ggml_set_name(out, "out");
  1044. return out;
  1045. }
  1046. };
  1047. // GGML_OP_SET
  1048. struct test_set : public test_case {
  1049. const ggml_type type_src;
  1050. const ggml_type type_dst;
  1051. const std::array<int64_t, 4> ne;
  1052. const int dim;
  1053. std::string vars() override {
  1054. return VARS_TO_STR4(type_src, type_dst, ne, dim);
  1055. }
  1056. size_t op_size(ggml_tensor * t) override {
  1057. return ggml_nbytes(t) + ggml_nbytes(t->src[0]);
  1058. }
  1059. test_set(ggml_type type_src = GGML_TYPE_F32, ggml_type type_dst = GGML_TYPE_F32,
  1060. std::array<int64_t, 4> ne = {6, 5, 4, 3}, int dim = 1)
  1061. : type_src(type_src), type_dst(type_dst), ne(ne), dim(dim) {}
  1062. ggml_tensor * build_graph(ggml_context * ctx) override {
  1063. ggml_tensor * src = ggml_new_tensor(ctx, type_src, 4, ne.data());
  1064. ggml_set_param(ctx, src);
  1065. ggml_set_name(src, "src");
  1066. auto ne_dst = ne;
  1067. for (int i = 0; i < dim; ++i) {
  1068. ne_dst[i] *= 2;
  1069. }
  1070. ggml_tensor* dst = ggml_new_tensor(ctx, type_dst, 4, ne_dst.data());
  1071. ggml_set_param(ctx, dst);
  1072. ggml_set_name(dst, "dst");
  1073. size_t offset = 0;
  1074. for (int i = 0; i < dim; ++i) {
  1075. offset += ((ne_dst[i] - ne[i])/2)*dst->nb[i];
  1076. }
  1077. ggml_tensor * out = ggml_set(ctx, dst, src,
  1078. // The backward pass requires setting a contiguous region:
  1079. src->nb[1], src->nb[2], src->nb[3], offset);
  1080. ggml_set_name(out, "out");
  1081. return out;
  1082. }
  1083. };
  1084. // GGML_OP_CPY
  1085. struct test_cpy : public test_case {
  1086. const ggml_type type_src;
  1087. const ggml_type type_dst;
  1088. const std::array<int64_t, 4> ne;
  1089. const std::array<int64_t, 4> permute;
  1090. bool _src_use_permute;
  1091. std::string vars() override {
  1092. return VARS_TO_STR4(type_src, type_dst, ne, permute);
  1093. }
  1094. double max_nmse_err() override {
  1095. return 1e-6;
  1096. }
  1097. size_t op_size(ggml_tensor * t) override {
  1098. return ggml_nbytes(t) + ggml_nbytes(t->src[0]);
  1099. }
  1100. test_cpy(ggml_type type_src = GGML_TYPE_F32, ggml_type type_dst = GGML_TYPE_F32,
  1101. std::array<int64_t, 4> ne = {10, 10, 10, 1},
  1102. std::array<int64_t, 4> permute = {0, 0, 0, 0})
  1103. : type_src(type_src), type_dst(type_dst), ne(ne), permute(permute),
  1104. _src_use_permute(permute[0] + permute[1] + permute[2] + permute[3] > 0) {}
  1105. ggml_tensor * build_graph(ggml_context * ctx) override {
  1106. ggml_tensor * src = ggml_new_tensor(ctx, type_src, 4, ne.data());
  1107. ggml_set_param(ctx, src);
  1108. ggml_set_name(src, "src");
  1109. if (_src_use_permute) {
  1110. src = ggml_permute(ctx, src, permute[0], permute[1], permute[2], permute[3]);
  1111. ggml_set_name(src, "src_permuted");
  1112. }
  1113. ggml_tensor* dst = ggml_new_tensor(ctx, type_dst, 4, src->ne);
  1114. ggml_set_name(dst, "dst");
  1115. ggml_tensor * out = ggml_cpy(ctx, src, dst);
  1116. ggml_set_name(out, "out");
  1117. return out;
  1118. }
  1119. };
  1120. // GGML_OP_CONT
  1121. struct test_cont : public test_case {
  1122. const ggml_type type;
  1123. const std::array<int64_t, 4> ne;
  1124. std::string vars() override {
  1125. return VARS_TO_STR2(type, ne);
  1126. }
  1127. test_cont(ggml_type type = GGML_TYPE_F32,
  1128. std::array<int64_t, 4> ne = {10, 10, 10, 1})
  1129. : type(type), ne(ne) {}
  1130. ggml_tensor * build_graph(ggml_context * ctx) override {
  1131. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1132. ggml_set_param(ctx, src);
  1133. ggml_set_name(src, "src");
  1134. src = ggml_transpose(ctx, src);
  1135. ggml_set_name(src, "src_transposed");
  1136. ggml_tensor * out = ggml_cont(ctx, src);
  1137. ggml_set_name(out, "out");
  1138. return out;
  1139. }
  1140. };
  1141. // GGML_OP_ADD
  1142. // GGML_OP_MUL
  1143. // GGML_OP_DIV
  1144. struct test_bin_bcast : public test_case {
  1145. using op_t = ggml_tensor * (*) (ggml_context *, ggml_tensor *, ggml_tensor *);
  1146. op_t op;
  1147. const ggml_type type;
  1148. const std::array<int64_t, 4> ne;
  1149. const std::array<int, 4> nr;
  1150. std::string vars() override {
  1151. return VARS_TO_STR3(type, ne, nr);
  1152. }
  1153. size_t op_size(ggml_tensor * t) override {
  1154. return ggml_nbytes(t) * 3;
  1155. }
  1156. test_bin_bcast(op_t op, ggml_type type = GGML_TYPE_F32,
  1157. std::array<int64_t, 4> ne = {10, 10, 1, 1},
  1158. std::array<int, 4> nr = {1, 2, 1, 1})
  1159. : op(op), type(type), ne(ne), nr(nr) {}
  1160. ggml_tensor * build_graph(ggml_context * ctx) override {
  1161. ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0]*nr[0], ne[1]*nr[1], ne[2]*nr[2], ne[3]*nr[3]);
  1162. ggml_set_name(a, "a");
  1163. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  1164. ggml_set_name(b, "b");
  1165. // The backward pass supports broadcasting only for GGML_ADD:
  1166. const bool grad_supported = op == ggml_add || ggml_are_same_shape(a, b);
  1167. if (grad_supported) {
  1168. ggml_set_param(ctx, a);
  1169. ggml_set_param(ctx, b);
  1170. }
  1171. ggml_tensor * out = op(ctx, a, b);
  1172. ggml_set_name(out, "out");
  1173. return out;
  1174. }
  1175. void initialize_tensors(ggml_context * ctx) override {
  1176. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1177. if (op == ggml_mul || op == ggml_div) {
  1178. // MUL and DIV have numerical issues around zero:
  1179. init_tensor_uniform(t, 0.9f, 1.1f);
  1180. } else {
  1181. init_tensor_uniform(t);
  1182. }
  1183. }
  1184. }
  1185. float grad_eps() override {
  1186. return 0.1f * (op == ggml_mul ? ne[0]*ne[1]*ne[2]*ne[3] : 1);
  1187. }
  1188. bool grad_precise() override {
  1189. return op == ggml_div;
  1190. }
  1191. double max_maa_err() override {
  1192. return op == ggml_add ? 1e-4 : 1e-3;
  1193. }
  1194. };
  1195. // GGML_OP_ADD1
  1196. struct test_add1 : public test_case {
  1197. const ggml_type type;
  1198. const std::array<int64_t, 4> ne;
  1199. std::string vars() override {
  1200. return VARS_TO_STR2(type, ne);
  1201. }
  1202. test_add1(ggml_type type = GGML_TYPE_F32,
  1203. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  1204. : type(type), ne(ne) {}
  1205. ggml_tensor * build_graph(ggml_context * ctx) override {
  1206. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1207. ggml_set_param(ctx, a);
  1208. ggml_set_name(a, "a");
  1209. ggml_tensor * b = ggml_new_tensor_1d(ctx, type, 1);
  1210. // ggml_set_param(ctx, b); // TODO: implement
  1211. ggml_set_name(b, "b");
  1212. ggml_tensor * out = ggml_add1(ctx, a, b);
  1213. ggml_set_name(out, "out");
  1214. return out;
  1215. }
  1216. float grad_eps() override {
  1217. return 0.1f * ne[0]*ne[1]*ne[2]*ne[3];
  1218. }
  1219. };
  1220. // GGML_OP_SCALE
  1221. struct test_scale : public test_case {
  1222. const ggml_type type;
  1223. const std::array<int64_t, 4> ne;
  1224. float scale;
  1225. std::string vars() override {
  1226. return VARS_TO_STR3(type, ne, scale);
  1227. }
  1228. test_scale(ggml_type type = GGML_TYPE_F32,
  1229. std::array<int64_t, 4> ne = {10, 10, 10, 10},
  1230. float scale = 2.0f)
  1231. : type(type), ne(ne), scale(scale) {}
  1232. ggml_tensor * build_graph(ggml_context * ctx) override {
  1233. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1234. ggml_set_param(ctx, a);
  1235. ggml_set_name(a, "a");
  1236. ggml_tensor * out = ggml_scale(ctx, a, scale);
  1237. ggml_set_name(out, "out");
  1238. return out;
  1239. }
  1240. };
  1241. // GGML_OP_NORM
  1242. struct test_norm : public test_case {
  1243. const ggml_type type;
  1244. const std::array<int64_t, 4> ne;
  1245. float eps;
  1246. std::string vars() override {
  1247. return VARS_TO_STR3(type, ne, eps);
  1248. }
  1249. test_norm(ggml_type type = GGML_TYPE_F32,
  1250. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  1251. float eps = 1e-6f)
  1252. : type(type), ne(ne), eps(eps) {}
  1253. ggml_tensor * build_graph(ggml_context * ctx) override {
  1254. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1255. ggml_set_name(a, "a");
  1256. ggml_tensor * out = ggml_norm(ctx, a, eps);
  1257. ggml_set_name(out, "out");
  1258. return out;
  1259. }
  1260. };
  1261. // GGML_OP_RMS_NORM
  1262. struct test_rms_norm : public test_case {
  1263. const ggml_type type;
  1264. const std::array<int64_t, 4> ne;
  1265. float eps;
  1266. std::string vars() override {
  1267. return VARS_TO_STR3(type, ne, eps);
  1268. }
  1269. test_rms_norm(ggml_type type = GGML_TYPE_F32,
  1270. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  1271. float eps = 1e-6f)
  1272. : type(type), ne(ne), eps(eps) {}
  1273. ggml_tensor * build_graph(ggml_context * ctx) override {
  1274. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1275. ggml_set_param(ctx, a);
  1276. ggml_set_name(a, "a");
  1277. ggml_tensor * out = ggml_rms_norm(ctx, a, eps);
  1278. ggml_set_name(out, "out");
  1279. return out;
  1280. }
  1281. bool grad_precise() override {
  1282. return true;
  1283. }
  1284. };
  1285. // GGML_OP_SSM_CONV
  1286. struct test_ssm_conv : public test_case {
  1287. const ggml_type type;
  1288. const std::array<int64_t, 4> ne_a;
  1289. const std::array<int64_t, 4> ne_b;
  1290. std::string vars() override {
  1291. return VARS_TO_STR3(type, ne_a, ne_b);
  1292. }
  1293. test_ssm_conv(ggml_type type = GGML_TYPE_F32,
  1294. std::array<int64_t, 4> ne_a = {10, 10, 10, 1},
  1295. std::array<int64_t, 4> ne_b = {3, 3, 1, 1})
  1296. : type(type), ne_a(ne_a), ne_b(ne_b) {}
  1297. ggml_tensor * build_graph(ggml_context * ctx) override {
  1298. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1299. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  1300. ggml_tensor * out = ggml_ssm_conv(ctx, a, b);
  1301. return out;
  1302. }
  1303. };
  1304. // GGML_OP_SSM_SCAN
  1305. struct test_ssm_scan : public test_case {
  1306. const ggml_type type;
  1307. const int64_t d_state;
  1308. const int64_t d_inner;
  1309. const int64_t n_seq_tokens;
  1310. const int64_t n_seqs;
  1311. std::string vars() override {
  1312. return VARS_TO_STR5(type, d_state, d_inner, n_seq_tokens, n_seqs);
  1313. }
  1314. test_ssm_scan(ggml_type type = GGML_TYPE_F32,
  1315. int64_t d_state = 32, int64_t d_inner = 32, int64_t n_seq_tokens = 32, int64_t n_seqs = 32)
  1316. : type(type), d_state(d_state), d_inner(d_inner), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  1317. ggml_tensor * build_graph(ggml_context * ctx) override {
  1318. ggml_tensor * s = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_state, d_inner, n_seqs, 1 }.data());
  1319. ggml_tensor * x = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_inner, n_seq_tokens, n_seqs, 1 }.data());
  1320. ggml_tensor * dt = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_inner, n_seq_tokens, n_seqs, 1 }.data());
  1321. ggml_tensor * A = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_state, d_inner, 1 , 1 }.data());
  1322. ggml_tensor * B = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_state, n_seq_tokens, n_seqs, 1 }.data());
  1323. ggml_tensor * C = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ d_state, n_seq_tokens, n_seqs, 1 }.data());
  1324. ggml_tensor * out = ggml_ssm_scan(ctx, s, x, dt, A, B, C);
  1325. return out;
  1326. }
  1327. };
  1328. // GGML_OP_RWKV_WKV6
  1329. struct test_rwkv_wkv6 : public test_case {
  1330. const ggml_type type;
  1331. const int64_t head_count;
  1332. const int64_t head_size;
  1333. const int64_t n_seq_tokens;
  1334. const int64_t n_seqs;
  1335. std::string vars() override {
  1336. return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
  1337. }
  1338. test_rwkv_wkv6(ggml_type type = GGML_TYPE_F32,
  1339. int64_t head_count = 32, int64_t head_size = 64, int64_t n_seq_tokens = 32, int64_t n_seqs = 32)
  1340. : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  1341. ggml_tensor * build_graph(ggml_context * ctx) override {
  1342. const int64_t n_tokens = n_seq_tokens * n_seqs;
  1343. ggml_tensor * r = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ 1, head_size, head_count, n_tokens }.data());
  1344. ggml_tensor * k = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ head_size, 1, head_count, n_tokens }.data());
  1345. ggml_tensor * v = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ 1, head_size, head_count, n_tokens }.data());
  1346. ggml_tensor * tf = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size, head_count }.data());
  1347. ggml_tensor * td = ggml_new_tensor(ctx, type, 4, std::vector<int64_t>{ 1, head_size, head_count, n_tokens }.data());
  1348. ggml_tensor * s = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size * head_size * head_count, n_seqs }.data());
  1349. ggml_tensor * out = ggml_rwkv_wkv6(ctx, k, v, r, tf, td, s);
  1350. return out;
  1351. }
  1352. };
  1353. // GGML_OP_MUL_MAT
  1354. struct test_mul_mat : public test_case {
  1355. const ggml_type type_a;
  1356. const ggml_type type_b;
  1357. const int64_t m;
  1358. const int64_t n;
  1359. const int64_t k;
  1360. const std::array<int64_t, 2> bs; // dims 3 and 4
  1361. const std::array<int64_t, 2> nr; // repeat in dims 3 and 4
  1362. const std::array<int64_t, 4> per; // permutation of dimensions
  1363. std::string vars() override {
  1364. return VARS_TO_STR8(type_a, type_b, m, n, k, bs, nr, per);
  1365. }
  1366. double max_nmse_err() override {
  1367. return 5e-4;
  1368. }
  1369. uint64_t op_flops(ggml_tensor * t) override {
  1370. GGML_UNUSED(t);
  1371. return 2 * m * n * k * bs[0] * nr[0] * bs[1] * nr[1];
  1372. }
  1373. test_mul_mat(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  1374. int64_t m = 32, int64_t n = 32, int64_t k = 32,
  1375. std::array<int64_t, 2> bs = {10, 10},
  1376. std::array<int64_t, 2> nr = {2, 2},
  1377. std::array<int64_t, 4> per = {0, 1, 2, 3})
  1378. : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), nr(nr), per(per) {}
  1379. ggml_tensor * build_graph(ggml_context * ctx) override {
  1380. // C^T = A * B^T: (k, m) * (k, n) => (m, n)
  1381. ggml_tensor * a;
  1382. ggml_tensor * b;
  1383. const int npermuted = (per[0] != 0) + (per[1] != 1) + (per[2] != 2) + (per[3] != 3);
  1384. if (npermuted > 0) {
  1385. GGML_ASSERT(npermuted == 2);
  1386. GGML_ASSERT(!ggml_is_quantized(type_a) || per[0] == 0);
  1387. GGML_ASSERT(!ggml_is_quantized(type_b) || per[0] == 0);
  1388. // Create tensors with the permuted dimensions, then permute them back to the dimensions given by m,n,k.
  1389. const int64_t ne_a[4] = {k, m, bs[0], bs[1]};
  1390. const int64_t ne_b[4] = {k, n, bs[0]*nr[0], bs[1]*nr[1]};
  1391. a = ggml_new_tensor_4d(ctx, type_a, ne_a[per[0]], ne_a[per[1]], ne_a[per[2]], ne_a[per[3]]);
  1392. b = ggml_new_tensor_4d(ctx, type_b, ne_b[per[0]], ne_b[per[1]], ne_b[per[2]], ne_b[per[3]]);
  1393. ggml_set_param(ctx, a);
  1394. ggml_set_param(ctx, b);
  1395. ggml_set_name(a, "a");
  1396. ggml_set_name(b, "b");
  1397. a = ggml_permute(ctx, a, per[0], per[1], per[2], per[3]);
  1398. b = ggml_permute(ctx, b, per[0], per[1], per[2], per[3]);
  1399. ggml_set_name(a, "a_permuted");
  1400. ggml_set_name(b, "b_permuted");
  1401. } else {
  1402. a = ggml_new_tensor_4d(ctx, type_a, k, m, bs[0], bs[1]);
  1403. b = ggml_new_tensor_4d(ctx, type_b, k, n, bs[0]*nr[0], bs[1]*nr[1]);
  1404. ggml_set_param(ctx, a);
  1405. ggml_set_param(ctx, b);
  1406. ggml_set_name(a, "a");
  1407. ggml_set_name(b, "b");
  1408. }
  1409. ggml_tensor * out = ggml_mul_mat(ctx, a, b);
  1410. ggml_set_name(out, "out");
  1411. return out;
  1412. }
  1413. };
  1414. // GGML_OP_MUL_MAT_ID
  1415. struct test_mul_mat_id : public test_case {
  1416. const ggml_type type_a;
  1417. const ggml_type type_b;
  1418. const int n_mats;
  1419. const int n_used;
  1420. const bool b; // brodcast b matrix
  1421. const int64_t m;
  1422. const int64_t n;
  1423. const int64_t k;
  1424. std::string vars() override {
  1425. return VARS_TO_STR8(type_a, type_b, n_mats, n_used, b, m, n, k);
  1426. }
  1427. double max_nmse_err() override {
  1428. return 5e-4;
  1429. }
  1430. uint64_t op_flops(ggml_tensor * t) override {
  1431. GGML_UNUSED(t);
  1432. return 2 * m * k * n * n_used;
  1433. }
  1434. test_mul_mat_id(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  1435. int n_mats = 8, int n_used = 2, bool b = false,
  1436. int64_t m = 32, int64_t n = 32, int64_t k = 32)
  1437. : type_a(type_a), type_b(type_b), n_mats(n_mats), n_used(n_used), b(b),
  1438. m(m), n(n), k(k) {
  1439. GGML_ASSERT(n_used <= n_mats);
  1440. }
  1441. ggml_tensor * build_graph(ggml_context * ctx) override {
  1442. // C^T = A * B^T: (k, m) * (k, n) => (m, n)
  1443. ggml_tensor * as = ggml_new_tensor_3d(ctx, type_a, k, m, n_mats);
  1444. ggml_set_name(as, "as");
  1445. ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_mats, n);
  1446. ggml_set_name(ids, "ids");
  1447. if (n_used != n_mats) {
  1448. ids = ggml_view_2d(ctx, ids, n_used, n, ids->nb[1], 0);
  1449. ggml_set_name(ids, "view_of_ids");
  1450. }
  1451. ggml_tensor * b = ggml_new_tensor_3d(ctx, type_b, k, this->b ? 1 : n_used, n);
  1452. ggml_set_name(b, "b");
  1453. ggml_tensor * out = ggml_mul_mat_id(ctx, as, b, ids);
  1454. ggml_set_name(out, "out");
  1455. return out;
  1456. }
  1457. void initialize_tensors(ggml_context * ctx) override {
  1458. std::random_device rd;
  1459. std::default_random_engine rng(rd());
  1460. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1461. if (t->type == GGML_TYPE_I32) {
  1462. if (ggml_is_view_op(t->op)) { continue; }
  1463. // ids
  1464. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  1465. std::vector<int32_t> data(t->ne[0]);
  1466. for (int i = 0; i < t->ne[0]; i++) {
  1467. data[i] = i % n_mats;
  1468. }
  1469. std::shuffle(data.begin(), data.end(), rng);
  1470. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
  1471. }
  1472. } else {
  1473. init_tensor_uniform(t);
  1474. }
  1475. }
  1476. }
  1477. };
  1478. // GGML_OP_OUT_PROD
  1479. struct test_out_prod : public test_case {
  1480. const ggml_type type_a;
  1481. const ggml_type type_b;
  1482. const int64_t m;
  1483. const int64_t n;
  1484. const int64_t k;
  1485. const std::array<int64_t, 2> bs; // dims 3 and 4
  1486. const bool trans_b;
  1487. std::string vars() override {
  1488. return VARS_TO_STR7(type_a, type_b, m, n, k, bs, trans_b);
  1489. }
  1490. double max_nmse_err() override {
  1491. return 5e-4;
  1492. }
  1493. test_out_prod(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  1494. int64_t m = 32, int64_t n = 32, int64_t k = 32,
  1495. std::array<int64_t, 2> bs = {10, 10},
  1496. bool trans_b = false)
  1497. : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), trans_b(trans_b) {}
  1498. ggml_tensor * build_graph(ggml_context * ctx) override {
  1499. ggml_tensor * a = ggml_new_tensor_4d(ctx, type_a, m, k, bs[0], bs[1]);
  1500. ggml_set_name(a, "a");
  1501. ggml_tensor * b;
  1502. if (trans_b) {
  1503. b = ggml_new_tensor_4d(ctx, type_b, k, n, bs[0], bs[1]);
  1504. b = ggml_transpose(ctx, b);
  1505. } else {
  1506. b = ggml_new_tensor_4d(ctx, type_b, n, k, bs[0], bs[1]);
  1507. }
  1508. ggml_set_name(b, "b");
  1509. ggml_tensor * out = ggml_out_prod(ctx, a, b);
  1510. ggml_set_name(out, "out");
  1511. return out;
  1512. }
  1513. };
  1514. // GGML_OP_SQR
  1515. struct test_sqr : public test_case {
  1516. const ggml_type type;
  1517. const std::array<int64_t, 4> ne;
  1518. std::string vars() override {
  1519. return VARS_TO_STR2(type, ne);
  1520. }
  1521. test_sqr(ggml_type type = GGML_TYPE_F32,
  1522. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  1523. : type(type), ne(ne) {}
  1524. ggml_tensor * build_graph(ggml_context * ctx) override {
  1525. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1526. ggml_set_param(ctx, a);
  1527. ggml_set_name(a, "a");
  1528. ggml_tensor * out = ggml_sqr(ctx, a);
  1529. ggml_set_name(out, "out");
  1530. return out;
  1531. }
  1532. float grad_eps() override {
  1533. return 0.1f * 0.25f*ne[0]*ne[1]*ne[2]*ne[3]; // 10% of expected value of sum.
  1534. }
  1535. };
  1536. // GGML_OP_SQRT
  1537. struct test_sqrt : public test_case {
  1538. const ggml_type type;
  1539. const std::array<int64_t, 4> ne;
  1540. std::string vars() override {
  1541. return VARS_TO_STR2(type, ne);
  1542. }
  1543. test_sqrt(ggml_type type = GGML_TYPE_F32,
  1544. std::array<int64_t, 4> ne = {10, 3, 3, 2})
  1545. : type(type), ne(ne) {}
  1546. ggml_tensor * build_graph(ggml_context * ctx) override {
  1547. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1548. ggml_set_param(ctx, a);
  1549. ggml_set_name(a, "a");
  1550. ggml_tensor * out = ggml_sqrt(ctx, a);
  1551. ggml_set_name(out, "out");
  1552. return out;
  1553. }
  1554. void initialize_tensors(ggml_context * ctx) override {
  1555. // fill with positive values
  1556. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1557. init_tensor_uniform(t, 50.0f, 100.0f);
  1558. }
  1559. }
  1560. float grad_eps() override {
  1561. return 20.0f;
  1562. }
  1563. bool grad_precise() override {
  1564. return true;
  1565. }
  1566. };
  1567. // GGML_OP_LOG
  1568. struct test_log : public test_case {
  1569. const ggml_type type;
  1570. const std::array<int64_t, 4> ne;
  1571. std::string vars() override {
  1572. return VARS_TO_STR2(type, ne);
  1573. }
  1574. test_log(ggml_type type = GGML_TYPE_F32,
  1575. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  1576. : type(type), ne(ne) {}
  1577. ggml_tensor * build_graph(ggml_context * ctx) override {
  1578. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1579. ggml_set_param(ctx, a);
  1580. ggml_set_name(a, "a");
  1581. ggml_tensor * out = ggml_log(ctx, a);
  1582. ggml_set_name(out, "out");
  1583. return out;
  1584. }
  1585. void initialize_tensors(ggml_context * ctx) override {
  1586. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1587. // log(1) == 0, cluster values there to keep the sum low for better precision in the backward pass:
  1588. init_tensor_uniform(t, 0.9f, 1.1f);
  1589. }
  1590. }
  1591. bool grad_precise() override {
  1592. return true;
  1593. }
  1594. };
  1595. // GGML_OP_SIN
  1596. struct test_sin : public test_case {
  1597. const ggml_type type;
  1598. const std::array<int64_t, 4> ne;
  1599. std::string vars() override {
  1600. return VARS_TO_STR2(type, ne);
  1601. }
  1602. test_sin(ggml_type type = GGML_TYPE_F32,
  1603. std::array<int64_t, 4> ne = {10, 2, 2, 2})
  1604. : type(type), ne(ne) {}
  1605. ggml_tensor * build_graph(ggml_context * ctx) override {
  1606. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1607. ggml_set_param(ctx, a);
  1608. ggml_set_name(a, "a");
  1609. ggml_tensor * out = ggml_sin(ctx, a);
  1610. ggml_set_name(out, "out");
  1611. return out;
  1612. }
  1613. void initialize_tensors(ggml_context * ctx) override {
  1614. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1615. init_tensor_uniform(t, -6.5f, 6.5f); // Covers interval [-2*pi, 2*pi].
  1616. }
  1617. }
  1618. double max_maa_err() override {
  1619. return 1e-3;
  1620. }
  1621. float grad_eps() override {
  1622. return 0.2f;
  1623. }
  1624. bool grad_precise() override {
  1625. return true;
  1626. }
  1627. };
  1628. // GGML_OP_COS
  1629. struct test_cos : public test_case {
  1630. const ggml_type type;
  1631. const std::array<int64_t, 4> ne;
  1632. std::string vars() override {
  1633. return VARS_TO_STR2(type, ne);
  1634. }
  1635. test_cos(ggml_type type = GGML_TYPE_F32,
  1636. std::array<int64_t, 4> ne = {10, 2, 2, 2})
  1637. : type(type), ne(ne) {}
  1638. ggml_tensor * build_graph(ggml_context * ctx) override {
  1639. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1640. ggml_set_param(ctx, a);
  1641. ggml_set_name(a, "a");
  1642. ggml_tensor * out = ggml_cos(ctx, a);
  1643. ggml_set_name(out, "out");
  1644. return out;
  1645. }
  1646. void initialize_tensors(ggml_context * ctx) override {
  1647. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1648. init_tensor_uniform(t, -6.5f, 6.5f); // Covers interval [-2*pi, 2*pi].
  1649. }
  1650. }
  1651. double max_maa_err() override {
  1652. return 1e-3;
  1653. }
  1654. float grad_eps() override {
  1655. return 0.2f;
  1656. }
  1657. bool grad_precise() override {
  1658. return true;
  1659. }
  1660. };
  1661. // GGML_OP_CLAMP
  1662. struct test_clamp : public test_case {
  1663. const ggml_type type;
  1664. const std::array<int64_t, 4> ne;
  1665. float min;
  1666. float max;
  1667. std::string vars() override {
  1668. return VARS_TO_STR4(type, ne, min, max);
  1669. }
  1670. test_clamp(ggml_type type = GGML_TYPE_F32,
  1671. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  1672. float min = -0.5f, float max = 0.5f)
  1673. : type(type), ne(ne), min(min), max(max) {}
  1674. ggml_tensor * build_graph(ggml_context * ctx) override {
  1675. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1676. ggml_set_name(a, "a");
  1677. ggml_tensor * out = ggml_clamp(ctx, a, min, max);
  1678. ggml_set_name(out, "out");
  1679. return out;
  1680. }
  1681. float grad_eps() override {
  1682. return 1e-2f;
  1683. }
  1684. std::vector<float> grad_expect() override {
  1685. return {0.0f, 1.0f};
  1686. }
  1687. };
  1688. // GGML_OP_DIAG_MASK_INF
  1689. struct test_diag_mask_inf : public test_case {
  1690. const ggml_type type;
  1691. const std::array<int64_t, 4> ne;
  1692. const int n_past;
  1693. std::string vars() override {
  1694. return VARS_TO_STR3(type, ne, n_past);
  1695. }
  1696. test_diag_mask_inf(ggml_type type = GGML_TYPE_F32,
  1697. std::array<int64_t, 4> ne = {10, 10, 3, 2},
  1698. int n_past = 5)
  1699. : type(type), ne(ne), n_past(n_past) {}
  1700. ggml_tensor * build_graph(ggml_context * ctx) override {
  1701. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1702. ggml_set_param(ctx, a);
  1703. ggml_set_name(a, "a");
  1704. ggml_tensor * out = ggml_diag_mask_inf(ctx, a, n_past);
  1705. ggml_set_name(out, "out");
  1706. return out;
  1707. }
  1708. };
  1709. // GGML_OP_SOFT_MAX
  1710. struct test_soft_max : public test_case {
  1711. const ggml_type type;
  1712. const std::array<int64_t, 4> ne;
  1713. const bool mask;
  1714. const float scale;
  1715. const float max_bias;
  1716. std::string vars() override {
  1717. return VARS_TO_STR5(type, ne, mask, scale, max_bias);
  1718. }
  1719. // the 1024 test with bias occasionally fails:
  1720. // SOFT_MAX(type=f32,ne=[1024,16,1,1],mask=1,scale=1.000000,max_bias=8.000000): [SOFT_MAX] NMSE = 0.000000103 > 0.000000100 FAIL
  1721. virtual double max_nmse_err() override {
  1722. return 1e-6;
  1723. }
  1724. test_soft_max(ggml_type type = GGML_TYPE_F32,
  1725. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  1726. bool mask = false,
  1727. float scale = 1.0f,
  1728. float max_bias = 0.0f)
  1729. : type(type), ne(ne), mask(mask), scale(scale), max_bias(max_bias) {}
  1730. ggml_tensor * build_graph(ggml_context * ctx) override {
  1731. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1732. ggml_set_param(ctx, a);
  1733. ggml_set_name(a, "a");
  1734. ggml_tensor * mask = nullptr;
  1735. if (this->mask) {
  1736. mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]);
  1737. ggml_set_name(mask, "mask");
  1738. }
  1739. ggml_tensor * out = ggml_soft_max_ext(ctx, a, mask, scale, max_bias);
  1740. ggml_set_name(out, "out");
  1741. return out;
  1742. }
  1743. bool grad_precise() override {
  1744. return true;
  1745. }
  1746. };
  1747. // GGML_OP_ROPE
  1748. struct test_rope : public test_case {
  1749. const ggml_type type;
  1750. const std::array<int64_t, 4> ne_a;
  1751. int n_dims;
  1752. int mode;
  1753. int n_ctx; // used to generate positions
  1754. float fs; // freq_scale
  1755. float ef; // ext_factor
  1756. float af; // attn_factor
  1757. bool ff;
  1758. int v; // view (1 : non-contiguous a)
  1759. std::string vars() override {
  1760. return VARS_TO_STR10(type, ne_a, n_dims, mode, n_ctx, fs, ef, af, ff, v);
  1761. }
  1762. test_rope(ggml_type type = GGML_TYPE_F32,
  1763. std::array<int64_t, 4> ne_a = {10, 5, 3, 1},
  1764. int n_dims = 10, int mode = 0, int n_ctx = 512, float fs = 1.0f, float ef = 0.0f, float af = 0.0f, bool ff = false, int v = 0)
  1765. : type(type), ne_a(ne_a), n_dims(n_dims), mode(mode), n_ctx(n_ctx), fs(fs), ef(ef), af(af), ff(ff), v(v) {}
  1766. ggml_tensor * build_graph(ggml_context * ctx) override {
  1767. ggml_tensor * a;
  1768. if (v & 1) {
  1769. auto ne = ne_a; ne[0] *= 2; ne[1] *= 4; ne[2] *= 3;
  1770. a = ggml_new_tensor(ctx, type, 4, ne.data());
  1771. ggml_set_param(ctx, a);
  1772. ggml_set_name(a, "a");
  1773. a = ggml_view_4d(ctx, a, ne_a[0], ne_a[1], ne_a[2], ne_a[3], a->nb[1], a->nb[2], a->nb[3], 0);
  1774. ggml_set_name(a, "view_of_a");
  1775. } else {
  1776. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1777. ggml_set_param(ctx, a);
  1778. ggml_set_name(a, "a");
  1779. }
  1780. ggml_tensor * pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, ne_a[2]);
  1781. ggml_set_name(pos, "pos");
  1782. ggml_tensor * freq = nullptr;
  1783. if (ff) {
  1784. freq = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_dims/2);
  1785. ggml_set_name(freq, "freq");
  1786. }
  1787. ggml_tensor * out = ggml_rope_ext(ctx, a, pos, freq, n_dims, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  1788. ggml_set_name(out, "out");
  1789. return out;
  1790. }
  1791. void initialize_tensors(ggml_context * ctx) override {
  1792. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1793. if (t->type == GGML_TYPE_I32) {
  1794. // pos
  1795. std::vector<int> data(ne_a[2]);
  1796. for (int i = 0; i < ne_a[2]; i++) {
  1797. data[i] = rand() % n_ctx;
  1798. }
  1799. ggml_backend_tensor_set(t, data.data(), 0, ne_a[2] * sizeof(int));
  1800. } else {
  1801. if (t->ne[0] == n_dims/2) {
  1802. // frequency factors in the range [0.9f, 1.1f]
  1803. init_tensor_uniform(t, 0.9f, 1.1f);
  1804. } else {
  1805. init_tensor_uniform(t);
  1806. }
  1807. }
  1808. }
  1809. }
  1810. double max_maa_err() override {
  1811. return 1e-3;
  1812. }
  1813. bool grad_precise() override {
  1814. return true;
  1815. }
  1816. };
  1817. // GGML_OP_POOL2D
  1818. struct test_pool2d : public test_case {
  1819. enum ggml_op_pool pool_type;
  1820. const ggml_type type_input;
  1821. const std::array<int64_t, 4> ne_input;
  1822. // kernel size
  1823. const int k0;
  1824. const int k1;
  1825. // stride
  1826. const int s0;
  1827. const int s1;
  1828. // padding
  1829. const int p0;
  1830. const int p1;
  1831. std::string vars() override {
  1832. return VARS_TO_STR9(pool_type, type_input, ne_input, k0, k1, s0, s1, p0, p1);
  1833. }
  1834. test_pool2d(ggml_op_pool pool_type = GGML_OP_POOL_AVG,
  1835. ggml_type type_input = GGML_TYPE_F32,
  1836. std::array<int64_t, 4> ne_input = {10, 10, 3, 1}, // [input_width, input_height, input_channels, 1]
  1837. int k0 = 3, int k1 = 3,
  1838. int s0 = 1, int s1 = 1,
  1839. int p0 = 1, int p1 = 1)
  1840. : pool_type(pool_type), type_input(type_input), ne_input(ne_input), k0(k0), k1(k1), s0(s0), s1(s1), p0(p0), p1(p1) {}
  1841. ggml_tensor * build_graph(ggml_context * ctx) override {
  1842. ggml_tensor * input = ggml_new_tensor(ctx, type_input, 4, ne_input.data());
  1843. ggml_set_param(ctx, input);
  1844. ggml_set_name(input, "input");
  1845. ggml_tensor * out = ggml_pool_2d(ctx, input, pool_type, k0, k1, s0, s1, p0, p1);
  1846. ggml_set_name(out, "out");
  1847. return out;
  1848. }
  1849. };
  1850. // GGML_OP_CONV_TRANSPOSE_1D
  1851. struct test_conv_transpose_1d : public test_case {
  1852. const std::array<int64_t, 4> ne_input;
  1853. const std::array<int64_t, 4> ne_kernel;
  1854. const int s0; // stride
  1855. const int p0; // padding
  1856. const int d0; // dilation
  1857. std::string vars() override {
  1858. return VARS_TO_STR5(ne_input, ne_kernel, s0, p0, d0);
  1859. }
  1860. test_conv_transpose_1d(std::array<int64_t, 4> ne_input = {197, 32, 1, 1}, // [input_width, input_height, input_channels, 1]
  1861. std::array<int64_t, 4> ne_kernel = {16, 32, 32, 1}, // [kernel_width, kernel_height, input_channels, 1]
  1862. int s0 = 1, int p0 = 0, int d0 = 1)
  1863. : ne_input(ne_input), ne_kernel(ne_kernel), s0(s0), p0(p0), d0(d0) {}
  1864. ggml_tensor * build_graph(ggml_context * ctx) override {
  1865. ggml_tensor * input = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_input.data());
  1866. ggml_set_name(input, "input");
  1867. ggml_tensor * kernel = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_kernel.data());
  1868. ggml_set_name(kernel, "kernel");
  1869. ggml_tensor * out = ggml_conv_transpose_1d(ctx, kernel, input, s0, p0, d0);
  1870. ggml_set_name(out, "out");
  1871. return out;
  1872. }
  1873. };
  1874. // GGML_OP_IM2COL
  1875. struct test_im2col : public test_case {
  1876. const ggml_type type_input;
  1877. const ggml_type type_kernel;
  1878. const ggml_type dst_type;
  1879. const std::array<int64_t, 4> ne_input;
  1880. const std::array<int64_t, 4> ne_kernel;
  1881. // stride
  1882. const int s0;
  1883. const int s1;
  1884. // padding
  1885. const int p0;
  1886. const int p1;
  1887. // dilation
  1888. const int d0;
  1889. const int d1;
  1890. // mode
  1891. const bool is_2D;
  1892. std::string vars() override {
  1893. return VARS_TO_STR12(type_input, type_kernel, dst_type, ne_input, ne_kernel, s0, s1, p0, p1, d0, d1, is_2D);
  1894. }
  1895. test_im2col(ggml_type type_input = GGML_TYPE_F32, ggml_type type_kernel = GGML_TYPE_F16, ggml_type dst_type = GGML_TYPE_F32,
  1896. std::array<int64_t, 4> ne_input = {10, 10, 3, 1}, // [input_width, input_height, input_channels, 1]
  1897. std::array<int64_t, 4> ne_kernel = {3, 3, 3, 1}, // [kernel_width, kernel_height, input_channels, 1]
  1898. int s0 = 1, int s1 = 1,
  1899. int p0 = 1, int p1 = 1,
  1900. int d0 = 1, int d1 = 1,
  1901. bool is_2D = true)
  1902. : type_input(type_input), type_kernel(type_kernel), dst_type(dst_type), ne_input(ne_input), ne_kernel(ne_kernel), s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), is_2D(is_2D) {}
  1903. ggml_tensor * build_graph(ggml_context * ctx) override {
  1904. ggml_tensor * input = ggml_new_tensor(ctx, type_input, 4, ne_input.data());
  1905. ggml_set_param(ctx, input);
  1906. ggml_set_name(input, "input");
  1907. ggml_tensor * kernel = ggml_new_tensor(ctx, type_kernel, 4, ne_kernel.data());
  1908. ggml_set_name(kernel, "kernel");
  1909. ggml_tensor * out = ggml_im2col(ctx, kernel, input, s0, s1, p0, p1, d0, d1, is_2D, dst_type);
  1910. ggml_set_name(out, "out");
  1911. return out;
  1912. }
  1913. };
  1914. // GGML_OP_CONCAT
  1915. struct test_concat : public test_case {
  1916. const ggml_type type;
  1917. const std::array<int64_t, 4> ne_a;
  1918. const int64_t ne_b_d;
  1919. const int dim;
  1920. const int v; // view (1 << 0: non-cont a, 1 << 1: non-cont b)
  1921. std::string vars() override {
  1922. return VARS_TO_STR5(type, ne_a, ne_b_d, dim, v);
  1923. }
  1924. test_concat(ggml_type type = GGML_TYPE_F32,
  1925. std::array<int64_t, 4> ne_a = {10, 5, 5, 5},
  1926. int64_t ne_b_d = 5,
  1927. int dim = 2, int v = 0)
  1928. : type(type), ne_a(ne_a), ne_b_d(ne_b_d), dim(dim), v(v) {}
  1929. ggml_tensor * build_graph(ggml_context * ctx) override {
  1930. auto ne_b = ne_a;
  1931. ne_b[dim] = ne_b_d;
  1932. ggml_tensor * a;
  1933. if (v & 1) {
  1934. auto ne = ne_a; ne[0] *= 2; ne[1] *= 4; ne[2] *= 3;
  1935. a = ggml_new_tensor(ctx, type, 4, ne.data());
  1936. ggml_set_name(a, "a");
  1937. a = ggml_view_4d(ctx, a, ne_a[0], ne_a[1], ne_a[2], ne_a[3], a->nb[1], a->nb[2], a->nb[3], 0);
  1938. ggml_set_name(a, "view_of_a");
  1939. } else {
  1940. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1941. ggml_set_name(a, "a");
  1942. }
  1943. ggml_tensor * b;
  1944. if (v & 2) {
  1945. auto ne = ne_b; ne[0] *= 3; ne[1] *= 2; ne[2] *= 4;
  1946. b = ggml_new_tensor(ctx, type, 4, ne.data());
  1947. ggml_set_name(b, "b");
  1948. b = ggml_view_4d(ctx, b, ne_b[0], ne_b[1], ne_b[2], ne_b[3], b->nb[1], b->nb[2], b->nb[3], 0);
  1949. ggml_set_name(b, "view_of_b");
  1950. } else {
  1951. b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  1952. ggml_set_name(b, "b");
  1953. }
  1954. ggml_tensor * out = ggml_concat(ctx, a, b, dim);
  1955. ggml_set_name(out, "out");
  1956. return out;
  1957. }
  1958. };
  1959. // GGML_OP_ARGSORT
  1960. struct test_argsort : public test_case {
  1961. const ggml_type type;
  1962. const std::array<int64_t, 4> ne;
  1963. ggml_sort_order order;
  1964. std::string vars() override {
  1965. return VARS_TO_STR3(type, ne, order);
  1966. }
  1967. test_argsort(ggml_type type = GGML_TYPE_F32,
  1968. std::array<int64_t, 4> ne = {16, 10, 10, 10},
  1969. ggml_sort_order order = GGML_SORT_ORDER_ASC)
  1970. : type(type), ne(ne), order(order) {}
  1971. ggml_tensor * build_graph(ggml_context * ctx) override {
  1972. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1973. ggml_set_name(a, "a");
  1974. ggml_tensor * out = ggml_argsort(ctx, a, order);
  1975. ggml_set_name(out, "out");
  1976. return out;
  1977. }
  1978. void initialize_tensors(ggml_context * ctx) override {
  1979. std::random_device rd;
  1980. std::default_random_engine rng(rd());
  1981. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1982. if (t->type == GGML_TYPE_I32) {
  1983. // indices
  1984. std::vector<int> data(ggml_nelements(t));
  1985. for (int i = 0; i < ggml_nelements(t); i++) {
  1986. data[i] = rand();
  1987. }
  1988. std::shuffle(data.begin(), data.end(), rng);
  1989. ggml_backend_tensor_set(t, data.data(), 0, ne[0]*ne[1]*ne[2]*ne[3] * sizeof(int));
  1990. } else if (t->type == GGML_TYPE_F32) {
  1991. // initialize with unique values to avoid ties
  1992. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  1993. std::vector<float> data(t->ne[0]);
  1994. for (int i = 0; i < t->ne[0]; i++) {
  1995. data[i] = i;
  1996. }
  1997. std::shuffle(data.begin(), data.end(), rng);
  1998. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(float));
  1999. }
  2000. } else {
  2001. GGML_ABORT("fatal error");
  2002. }
  2003. }
  2004. }
  2005. };
  2006. // GGML_OP_SUM
  2007. struct test_sum : public test_case {
  2008. const ggml_type type;
  2009. const std::array<int64_t, 4> ne;
  2010. std::string vars() override {
  2011. return VARS_TO_STR2(type, ne);
  2012. }
  2013. test_sum(ggml_type type = GGML_TYPE_F32,
  2014. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2015. : type(type), ne(ne) {}
  2016. ggml_tensor * build_graph(ggml_context * ctx) override {
  2017. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2018. ggml_set_param(ctx, a);
  2019. ggml_set_name(a, "a");
  2020. ggml_tensor * out = ggml_sum(ctx, a);
  2021. ggml_set_name(out, "out");
  2022. return out;
  2023. }
  2024. float grad_eps() override {
  2025. return 0.1f * sqrtf(ne[0]*ne[1]*ne[2]*ne[3]);
  2026. }
  2027. };
  2028. // GGML_OP_SUM_ROWS
  2029. struct test_sum_rows : public test_case {
  2030. const ggml_type type;
  2031. const std::array<int64_t, 4> ne;
  2032. std::string vars() override {
  2033. return VARS_TO_STR2(type, ne);
  2034. }
  2035. test_sum_rows(ggml_type type = GGML_TYPE_F32,
  2036. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2037. : type(type), ne(ne) {}
  2038. ggml_tensor * build_graph(ggml_context * ctx) override {
  2039. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2040. ggml_set_param(ctx, a);
  2041. ggml_set_name(a, "a");
  2042. ggml_tensor * out = ggml_sum_rows(ctx, a);
  2043. ggml_set_name(out, "out");
  2044. return out;
  2045. }
  2046. };
  2047. // GGML_OP_UPSCALE
  2048. struct test_upscale : public test_case {
  2049. const ggml_type type;
  2050. const std::array<int64_t, 4> ne;
  2051. const int32_t scale_factor;
  2052. const bool transpose;
  2053. std::string vars() override {
  2054. return VARS_TO_STR4(type, ne, scale_factor, transpose);
  2055. }
  2056. test_upscale(ggml_type type = GGML_TYPE_F32,
  2057. std::array<int64_t, 4> ne = {512, 512, 3, 1},
  2058. int32_t scale_factor = 2, bool transpose = false)
  2059. : type(type), ne(ne), scale_factor(scale_factor), transpose(transpose) {}
  2060. ggml_tensor * build_graph(ggml_context * ctx) override {
  2061. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2062. ggml_set_name(a, "a");
  2063. if (transpose) {
  2064. a = ggml_transpose(ctx, a);
  2065. ggml_set_name(a, "a_transposed");
  2066. }
  2067. ggml_tensor * out = ggml_upscale(ctx, a, scale_factor);
  2068. ggml_set_name(out, "out");
  2069. return out;
  2070. }
  2071. };
  2072. // GGML_OP_UPSCALE (ext)
  2073. struct test_upscale_ext : public test_case {
  2074. const ggml_type type;
  2075. const std::array<int64_t, 4> ne;
  2076. const std::array<int64_t, 4> ne_tgt;
  2077. std::string vars() override {
  2078. return VARS_TO_STR3(type, ne, ne_tgt);
  2079. }
  2080. test_upscale_ext(ggml_type type = GGML_TYPE_F32,
  2081. std::array<int64_t, 4> ne = {2, 5, 7, 11},
  2082. std::array<int64_t, 4> ne_tgt = {5, 7, 11, 13})
  2083. : type(type), ne(ne), ne_tgt(ne_tgt) {}
  2084. ggml_tensor * build_graph(ggml_context * ctx) override {
  2085. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2086. ggml_set_name(a, "a");
  2087. ggml_tensor * out = ggml_upscale_ext(ctx, a, ne_tgt[0], ne_tgt[1],ne_tgt[2], ne_tgt[3]);
  2088. ggml_set_name(out, "out");
  2089. return out;
  2090. }
  2091. };
  2092. // GGML_OP_GROUP_NORM
  2093. struct test_group_norm : public test_case {
  2094. const ggml_type type;
  2095. const std::array<int64_t, 4> ne;
  2096. const int32_t num_groups;
  2097. const float eps;
  2098. std::string vars() override {
  2099. return VARS_TO_STR3(type, ne, num_groups);
  2100. }
  2101. test_group_norm(ggml_type type = GGML_TYPE_F32,
  2102. std::array<int64_t, 4> ne = {64, 64, 320, 1},
  2103. int32_t num_groups = 32,
  2104. float eps = 1e-6f)
  2105. : type(type), ne(ne), num_groups(num_groups), eps(eps) {}
  2106. ggml_tensor * build_graph(ggml_context * ctx) override {
  2107. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2108. ggml_set_name(a, "a");
  2109. ggml_tensor * out = ggml_group_norm(ctx, a, num_groups, eps);
  2110. ggml_set_name(out, "out");
  2111. return out;
  2112. }
  2113. };
  2114. // GGML_OP_ACC
  2115. struct test_acc : public test_case {
  2116. const ggml_type type;
  2117. const std::array<int64_t, 4> ne_a;
  2118. const std::array<int64_t, 4> ne_b;
  2119. std::string vars() override {
  2120. return VARS_TO_STR3(type, ne_a, ne_b);
  2121. }
  2122. test_acc(ggml_type type = GGML_TYPE_F32,
  2123. std::array<int64_t, 4> ne_a = {256, 17, 1, 1},
  2124. std::array<int64_t, 4> ne_b = {256, 16, 1, 1})
  2125. : type(type), ne_a(ne_a), ne_b(ne_b) {}
  2126. ggml_tensor * build_graph(ggml_context * ctx) override {
  2127. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2128. ggml_set_param(ctx, a);
  2129. ggml_set_name(a, "a");
  2130. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  2131. ggml_set_param(ctx, b);
  2132. ggml_set_name(b, "b");
  2133. ggml_tensor * out = ggml_acc(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], b->nb[1]);
  2134. ggml_set_name(out, "out");
  2135. return out;
  2136. }
  2137. };
  2138. // GGML_OP_PAD
  2139. struct test_pad : public test_case {
  2140. const ggml_type type;
  2141. const std::array<int64_t, 4> ne_a;
  2142. const int pad_0;
  2143. const int pad_1;
  2144. std::string vars() override {
  2145. return VARS_TO_STR4(type, ne_a, pad_0, pad_1);
  2146. }
  2147. test_pad(ggml_type type = GGML_TYPE_F32,
  2148. std::array<int64_t, 4> ne_a = {512, 512, 1, 1},
  2149. int pad_0 = 1, int pad_1 = 1)
  2150. : type(type), ne_a(ne_a), pad_0(pad_0), pad_1(pad_1) {}
  2151. ggml_tensor * build_graph(ggml_context * ctx) override {
  2152. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2153. ggml_set_name(a, "a");
  2154. ggml_tensor * out = ggml_pad(ctx, a, pad_0, pad_1, 0, 0);
  2155. ggml_set_name(out, "out");
  2156. return out;
  2157. }
  2158. };
  2159. // GGML_OP_ARANGE
  2160. struct test_arange : public test_case {
  2161. const ggml_type type;
  2162. const float start;
  2163. const float stop;
  2164. const float step;
  2165. std::string vars() override {
  2166. return VARS_TO_STR4(type, start, stop, step);
  2167. }
  2168. test_arange(ggml_type type = GGML_TYPE_F32,
  2169. float start = 0.f, float stop = 10.f, float step = 1.f)
  2170. : type(type), start(start), stop(stop), step(step) {}
  2171. ggml_tensor * build_graph(ggml_context * ctx) override {
  2172. ggml_tensor * out = ggml_arange(ctx, start, stop, step);
  2173. ggml_set_name(out, "out");
  2174. return out;
  2175. }
  2176. };
  2177. // GGML_OP_TIMESTEP_EMBEDDING
  2178. struct test_timestep_embedding : public test_case {
  2179. const ggml_type type;
  2180. const std::array<int64_t, 4> ne_a;
  2181. const int dim;
  2182. const int max_period;
  2183. std::string vars() override {
  2184. return VARS_TO_STR4(type, ne_a, dim, max_period);
  2185. }
  2186. test_timestep_embedding(ggml_type type = GGML_TYPE_F32,
  2187. std::array<int64_t, 4> ne_a = {2, 1, 1, 1},
  2188. int dim = 320, int max_period=10000)
  2189. : type(type), ne_a(ne_a), dim(dim), max_period(max_period) {}
  2190. ggml_tensor * build_graph(ggml_context * ctx) override {
  2191. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2192. ggml_set_name(a, "a");
  2193. ggml_tensor * out = ggml_timestep_embedding(ctx, a, dim, max_period);
  2194. ggml_set_name(out, "out");
  2195. return out;
  2196. }
  2197. };
  2198. // GGML_OP_LEAKY_RELU
  2199. struct test_leaky_relu : public test_case {
  2200. const ggml_type type;
  2201. const std::array<int64_t, 4> ne_a;
  2202. const float negative_slope;
  2203. std::string vars() override {
  2204. return VARS_TO_STR3(type, ne_a, negative_slope);
  2205. }
  2206. test_leaky_relu(ggml_type type = GGML_TYPE_F32,
  2207. std::array<int64_t, 4> ne_a = {10, 5, 4, 3},
  2208. float negative_slope = 0.1f)
  2209. : type(type), ne_a(ne_a), negative_slope(negative_slope) {}
  2210. ggml_tensor * build_graph(ggml_context * ctx) override {
  2211. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2212. ggml_set_name(a, "a");
  2213. ggml_tensor * out = ggml_leaky_relu(ctx, a, negative_slope, true);
  2214. ggml_set_name(out, "out");
  2215. return out;
  2216. }
  2217. };
  2218. // GGML_OP_FLASH_ATTN_EXT
  2219. struct test_flash_attn_ext : public test_case {
  2220. const int64_t hs; // head size
  2221. const int64_t nh; // num heads
  2222. const int64_t kv; // kv size
  2223. const int64_t nb; // batch size
  2224. const bool mask; // use mask
  2225. const float max_bias; // ALiBi
  2226. const float logit_softcap; // Gemma 2
  2227. const ggml_type type_KV;
  2228. std::string vars() override {
  2229. return VARS_TO_STR8(hs, nh, kv, nb, mask, max_bias, logit_softcap, type_KV);
  2230. }
  2231. double max_nmse_err() override {
  2232. return 5e-4;
  2233. }
  2234. uint64_t op_flops(ggml_tensor * t) override {
  2235. GGML_UNUSED(t);
  2236. // Just counting matmul costs:
  2237. // Q*K^T is nb x hs x kv, P*V is nb x kv x hs, per head
  2238. return 2 * 2 * nh * nb * hs * kv;
  2239. }
  2240. test_flash_attn_ext(int64_t hs = 128, int64_t nh = 32, int64_t kv = 96, int64_t nb = 8,
  2241. bool mask = true, float max_bias = 0.0f, float logit_softcap = 0.0f, ggml_type type_KV = GGML_TYPE_F16)
  2242. : hs(hs), nh(nh), kv(kv), nb(nb), mask(mask), max_bias(max_bias), logit_softcap(logit_softcap), type_KV(type_KV) {}
  2243. ggml_tensor * build_graph(ggml_context * ctx) override {
  2244. const int64_t hs_padded = GGML_PAD(hs, ggml_blck_size(type_KV));
  2245. ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs_padded, nb, nh, 1);
  2246. ggml_set_name(q, "q");
  2247. ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs_padded, kv, nh, 1);
  2248. ggml_set_name(k, "k");
  2249. ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs_padded, kv, nh, 1);
  2250. ggml_set_name(v, "v");
  2251. ggml_tensor * m = nullptr;
  2252. if (mask) {
  2253. m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, GGML_PAD(nb, GGML_KQ_MASK_PAD), 1, 1);
  2254. ggml_set_name(m, "m");
  2255. }
  2256. ggml_tensor * out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/sqrtf(hs), max_bias, logit_softcap);
  2257. ggml_set_name(out, "out");
  2258. return out;
  2259. }
  2260. bool grad_precise() override {
  2261. return true;
  2262. }
  2263. };
  2264. // GGML_OP_CROSS_ENTROPY_LOSS
  2265. struct test_cross_entropy_loss : public test_case {
  2266. const ggml_type type;
  2267. const std::array<int64_t, 4> ne;
  2268. std::string vars() override {
  2269. return VARS_TO_STR2(type, ne);
  2270. }
  2271. test_cross_entropy_loss(ggml_type type = GGML_TYPE_F32,
  2272. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2273. : type(type), ne(ne) {}
  2274. ggml_tensor * build_graph(ggml_context * ctx) override {
  2275. ggml_tensor * logits = ggml_new_tensor(ctx, type, 4, ne.data());
  2276. ggml_set_param(ctx, logits);
  2277. ggml_set_name(logits, "logits");
  2278. ggml_tensor * labels = ggml_new_tensor(ctx, type, 4, ne.data());
  2279. // The labels are assumed to be constant -> no gradients.
  2280. ggml_set_name(labels, "labels");
  2281. // Ensure labels add up to 1:
  2282. labels = ggml_soft_max(ctx, labels);
  2283. ggml_set_name(labels, "labels_normalized");
  2284. ggml_tensor * out = ggml_cross_entropy_loss(ctx, logits, labels);
  2285. ggml_set_name(out, "out");
  2286. return out;
  2287. }
  2288. void initialize_tensors(ggml_context * ctx) override {
  2289. // For larger abs. diffs between logits softmax is more linear, therefore more precise num. gradients.
  2290. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2291. init_tensor_uniform(t, -100.0f, 100.0f);
  2292. }
  2293. }
  2294. float grad_eps() override {
  2295. return 1.0f;
  2296. }
  2297. bool grad_precise() override {
  2298. return true;
  2299. }
  2300. };
  2301. // GGML_OP_OPT_STEP_ADAMW
  2302. struct test_opt_step_adamw : public test_case {
  2303. const ggml_type type;
  2304. const std::array<int64_t, 4> ne;
  2305. const float alpha;
  2306. const float beta1;
  2307. const float beta2;
  2308. const float eps;
  2309. const float wd;
  2310. std::string vars() override {
  2311. return VARS_TO_STR7(type, ne, alpha, beta1, beta2, eps, wd);
  2312. }
  2313. test_opt_step_adamw(ggml_type type = GGML_TYPE_F32,
  2314. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  2315. float alpha = 1e-3f,
  2316. float beta1 = 0.9f,
  2317. float beta2 = 0.999f,
  2318. float eps = 1e-8f,
  2319. float wd = 0.0f)
  2320. : type(type), ne(ne), alpha(alpha), beta1(beta1), beta2(beta2), eps(eps), wd(wd) {}
  2321. ggml_tensor * build_graph(ggml_context * ctx) override {
  2322. ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  2323. ggml_set_param(ctx, a); // Despite tensor a having gradients the output tensor will not.
  2324. ggml_set_name(a, "a");
  2325. ggml_tensor * grad = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  2326. ggml_set_name(grad, "grad");
  2327. ggml_tensor * out = ggml_opt_step_adamw(ctx, a, grad, alpha, beta1, beta2, eps, wd);
  2328. ggml_set_name(out, "out");
  2329. return out;
  2330. }
  2331. void initialize_tensors(ggml_context * ctx) override {
  2332. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2333. init_tensor_uniform(t, 0.0f, 1.0f); // grad_v needs non-negative values.
  2334. }
  2335. }
  2336. bool grad_precise() override {
  2337. return true;
  2338. }
  2339. };
  2340. enum llm_norm_type {
  2341. LLM_NORM,
  2342. LLM_NORM_RMS,
  2343. };
  2344. struct llama_hparams {
  2345. uint32_t n_vocab;
  2346. uint32_t n_embd;
  2347. uint32_t n_head;
  2348. uint32_t n_head_kv;
  2349. static constexpr uint32_t n_layer = 1;
  2350. uint32_t n_rot;
  2351. uint32_t n_embd_head; // dimension of values (d_v)
  2352. uint32_t n_ff;
  2353. float f_norm_eps;
  2354. float f_norm_rms_eps;
  2355. // cparams
  2356. static constexpr uint32_t n_ctx = 512; // user-specified context size
  2357. static constexpr uint32_t n_ctx_orig = n_ctx;
  2358. // batch
  2359. int32_t n_tokens;
  2360. // llm_build_context
  2361. static constexpr int32_t n_kv = 32; // size of KV cache to consider (n_kv <= n_ctx
  2362. static constexpr int32_t kv_head = 1; // index of where we store new KV data in the cache
  2363. uint32_t n_embd_gqa() const { // dimension of key embeddings across all k-v heads
  2364. return n_embd_head * n_head_kv;
  2365. }
  2366. };
  2367. // LLM base class
  2368. struct test_llm : public test_case {
  2369. llama_hparams hp;
  2370. protected:
  2371. test_llm(llama_hparams hp)
  2372. : hp(std::move(hp)) {
  2373. }
  2374. public:
  2375. struct ggml_tensor * llm_build_norm(
  2376. struct ggml_context * ctx,
  2377. struct ggml_tensor * cur,
  2378. struct ggml_tensor * mw,
  2379. struct ggml_tensor * mb,
  2380. llm_norm_type type) {
  2381. switch (type) {
  2382. case LLM_NORM: cur = ggml_norm (ctx, cur, hp.f_norm_eps); break;
  2383. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hp.f_norm_rms_eps); break;
  2384. }
  2385. cur = ggml_mul(ctx, cur, mw);
  2386. if (mb) {
  2387. cur = ggml_add(ctx, cur, mb);
  2388. }
  2389. return cur;
  2390. }
  2391. void llm_build_kv_store(
  2392. struct ggml_context * ctx,
  2393. struct ggml_tensor * k_l,
  2394. struct ggml_tensor * v_l,
  2395. struct ggml_tensor * k_cur,
  2396. struct ggml_tensor * v_cur) {
  2397. // compute the transposed [n_tokens, n_embd] V matrix
  2398. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, hp.n_embd_gqa(), hp.n_tokens));
  2399. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, k_l, hp.n_tokens*hp.n_embd_gqa(),
  2400. (ggml_row_size(k_l->type, hp.n_embd_gqa()))*hp.kv_head);
  2401. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, v_l, hp.n_tokens, hp.n_embd_gqa(),
  2402. ( hp.n_ctx)*ggml_element_size(v_l),
  2403. (hp.kv_head)*ggml_element_size(v_l));
  2404. // important: storing RoPE-ed version of K in the KV cache!
  2405. ggml_cpy(ctx, k_cur, k_cache_view);
  2406. ggml_cpy(ctx, v_cur_t, v_cache_view);
  2407. }
  2408. struct ggml_tensor * llm_build_kqv(
  2409. struct ggml_context * ctx,
  2410. struct ggml_tensor * k_l,
  2411. struct ggml_tensor * v_l,
  2412. struct ggml_tensor * q_cur,
  2413. struct ggml_tensor * kq_mask,
  2414. float kq_scale) {
  2415. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  2416. struct ggml_tensor * k =
  2417. ggml_view_3d(ctx, k_l,
  2418. hp.n_embd_head, hp.n_kv, hp.n_head_kv,
  2419. ggml_row_size(k_l->type, hp.n_embd_gqa()),
  2420. ggml_row_size(k_l->type, hp.n_embd_head),
  2421. 0);
  2422. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  2423. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, 0.0f);
  2424. // split cached v into n_head heads
  2425. struct ggml_tensor * v =
  2426. ggml_view_3d(ctx, v_l,
  2427. hp.n_kv, hp.n_embd_head, hp.n_head_kv,
  2428. ggml_element_size(v_l)*hp.n_ctx,
  2429. ggml_element_size(v_l)*hp.n_ctx*hp.n_embd_head,
  2430. 0);
  2431. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  2432. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  2433. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, hp.n_embd_head*hp.n_head, hp.n_tokens);
  2434. struct ggml_tensor * wo = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd);
  2435. cur = ggml_mul_mat(ctx, wo, cur);
  2436. return cur;
  2437. }
  2438. void initialize_tensors(ggml_context * ctx) override {
  2439. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2440. if (t->type == GGML_TYPE_I32) {
  2441. // pos
  2442. std::vector<int> data(hp.n_tokens);
  2443. for (int i = 0; i < hp.n_tokens; i++) {
  2444. data[i] = rand() % hp.n_ctx;
  2445. }
  2446. ggml_backend_tensor_set(t, data.data(), 0, hp.n_tokens * sizeof(int));
  2447. } else {
  2448. init_tensor_uniform(t);
  2449. }
  2450. }
  2451. }
  2452. };
  2453. // Llama
  2454. struct test_llama : public test_llm {
  2455. static constexpr float freq_base = 10000.0f;
  2456. static constexpr float freq_scale = 1.0f;
  2457. static constexpr float ext_factor = 0.0f;
  2458. static constexpr float attn_factor = 1.0f;
  2459. static constexpr float beta_fast = 32.0f;
  2460. static constexpr float beta_slow = 1.0f;
  2461. std::string op_desc(ggml_tensor * t) override {
  2462. GGML_UNUSED(t);
  2463. return "LLAMA";
  2464. }
  2465. std::string vars() override {
  2466. auto n_tokens = hp.n_tokens;
  2467. return VARS_TO_STR1(n_tokens);
  2468. }
  2469. double max_nmse_err() override {
  2470. return 2e-3;
  2471. }
  2472. test_llama(int n_tokens = 1)
  2473. : test_llm({
  2474. /*n_vocab =*/ 32000,
  2475. /*n_embd =*/ 3200,
  2476. /*n_head =*/ 32,
  2477. /*n_head_kv =*/ 32,
  2478. /*n_rot =*/ 100,
  2479. /*n_embd_head =*/ 100,
  2480. /*n_ff =*/ 8640,
  2481. /*f_norm_eps =*/ 0.f,
  2482. /*f_norm_rms_eps =*/ 1e-5f,
  2483. /*n_tokens =*/ n_tokens,
  2484. }) {
  2485. }
  2486. ggml_tensor * build_graph(ggml_context * ctx) override {
  2487. struct ggml_tensor * cur;
  2488. struct ggml_tensor * inpL;
  2489. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.n_embd, hp.n_tokens);
  2490. // inp_pos - contains the positions
  2491. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, hp.n_tokens);
  2492. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2493. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, hp.n_kv, hp.n_tokens, 1);
  2494. ggml_tensor * k_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  2495. ggml_tensor * v_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  2496. for (uint32_t il = 0; il < hp.n_layer; ++il) {
  2497. struct ggml_tensor * inpSA = inpL;
  2498. // norm
  2499. ggml_tensor * attn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2500. cur = llm_build_norm(ctx, inpL, attn_norm, nullptr, LLM_NORM_RMS);
  2501. // self-attention
  2502. {
  2503. ggml_tensor * wq = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd);
  2504. ggml_tensor * wk = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd_gqa());
  2505. ggml_tensor * wv = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd_gqa());
  2506. // compute Q and K and RoPE them
  2507. struct ggml_tensor * Qcur = ggml_mul_mat(ctx, wq, cur);
  2508. struct ggml_tensor * Kcur = ggml_mul_mat(ctx, wk, cur);
  2509. struct ggml_tensor * Vcur = ggml_mul_mat(ctx, wv, cur);
  2510. Qcur = ggml_rope_ext(
  2511. ctx, ggml_reshape_3d(ctx, Qcur, hp.n_embd_head, hp.n_head, hp.n_tokens), inp_pos, nullptr,
  2512. hp.n_rot, 0, hp.n_ctx_orig, freq_base, freq_scale,
  2513. ext_factor, attn_factor, beta_fast, beta_slow
  2514. );
  2515. Kcur = ggml_rope_ext(
  2516. ctx, ggml_reshape_3d(ctx, Kcur, hp.n_embd_head, hp.n_head_kv, hp.n_tokens), inp_pos, nullptr,
  2517. hp.n_rot, 0, hp.n_ctx_orig, freq_base, freq_scale,
  2518. ext_factor, attn_factor, beta_fast, beta_slow
  2519. );
  2520. llm_build_kv_store(ctx, k_l, v_l, Kcur, Vcur);
  2521. cur = llm_build_kqv(ctx, k_l, v_l, Qcur, KQ_mask, 1.0f/sqrtf(float(hp.n_embd_head)));
  2522. }
  2523. struct ggml_tensor * ffn_inp = ggml_add(ctx, cur, inpSA);
  2524. // feed-forward network
  2525. ggml_tensor * ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2526. cur = llm_build_norm(ctx, ffn_inp, ffn_norm, nullptr, LLM_NORM_RMS);
  2527. ggml_tensor * ffn_gate = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  2528. ggml_tensor * ffn_down = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_ff, hp.n_embd);
  2529. ggml_tensor * ffn_up = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  2530. struct ggml_tensor * tmp = ggml_mul_mat(ctx, ffn_up, cur);
  2531. cur = ggml_mul_mat(ctx, ffn_gate, cur);
  2532. cur = ggml_silu(ctx, cur);
  2533. cur = ggml_mul(ctx, cur, tmp);
  2534. cur = ggml_mul_mat(ctx, ffn_down, cur);
  2535. cur = ggml_add(ctx, cur, ffn_inp);
  2536. // input for next layer
  2537. inpL = cur;
  2538. }
  2539. cur = inpL;
  2540. ggml_tensor * output_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2541. cur = llm_build_norm(ctx, cur, output_norm, nullptr, LLM_NORM_RMS);
  2542. // lm_head
  2543. ggml_tensor * output = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_vocab);
  2544. cur = ggml_mul_mat(ctx, output, cur);
  2545. return cur;
  2546. }
  2547. };
  2548. // Falcon
  2549. struct test_falcon : public test_llm {
  2550. static constexpr float freq_base = 10000.0f;
  2551. static constexpr float freq_scale = 1.0f;
  2552. static constexpr float ext_factor = 0.0f;
  2553. static constexpr float attn_factor = 1.0f;
  2554. static constexpr float beta_fast = 32.0f;
  2555. static constexpr float beta_slow = 1.0f;
  2556. std::string op_desc(ggml_tensor * t) override {
  2557. GGML_UNUSED(t);
  2558. return "FALCON";
  2559. }
  2560. std::string vars() override {
  2561. auto n_tokens = hp.n_tokens;
  2562. return VARS_TO_STR1(n_tokens);
  2563. }
  2564. double max_nmse_err() override {
  2565. return 2e-3;
  2566. }
  2567. test_falcon(int n_tokens = 1)
  2568. : test_llm({
  2569. /*n_vocab =*/ 32000,
  2570. /*n_embd =*/ 3200,
  2571. /*n_head =*/ 50,
  2572. /*n_head_kv =*/ 1,
  2573. /*n_rot =*/ 64,
  2574. /*n_embd_head =*/ 64,
  2575. /*n_ff =*/ 8640,
  2576. /*f_norm_eps =*/ 1e-5f,
  2577. /*f_norm_rms_eps =*/ 0.f,
  2578. /*n_tokens =*/ n_tokens,
  2579. }) {
  2580. }
  2581. ggml_tensor * build_graph(ggml_context * ctx) override {
  2582. struct ggml_tensor * cur;
  2583. struct ggml_tensor * inpL;
  2584. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.n_embd, hp.n_tokens);
  2585. // inp_pos - contains the positions
  2586. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, hp.n_tokens);
  2587. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  2588. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, hp.n_kv, hp.n_tokens, 1);
  2589. ggml_tensor * k_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  2590. ggml_tensor * v_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  2591. for (uint32_t il = 0; il < hp.n_layer; ++il) {
  2592. // norm
  2593. ggml_tensor * attn_norm_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2594. ggml_tensor * attn_norm_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2595. ggml_tensor * attn_norm = llm_build_norm(ctx, inpL, attn_norm_w, attn_norm_b, LLM_NORM);
  2596. // self-attention
  2597. {
  2598. cur = attn_norm;
  2599. ggml_tensor * wqkv = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd + 2*hp.n_embd_gqa());
  2600. cur = ggml_mul_mat(ctx, wqkv, cur);
  2601. struct ggml_tensor * Qcur = ggml_cont(ctx, ggml_view_2d(ctx, cur, hp.n_embd, hp.n_tokens, cur->nb[1], 0*sizeof(float)*(hp.n_embd)));
  2602. struct ggml_tensor * Kcur = ggml_cont(ctx, ggml_view_2d(ctx, cur, hp.n_embd_gqa(), hp.n_tokens, cur->nb[1], 1*sizeof(float)*(hp.n_embd)));
  2603. struct ggml_tensor * Vcur = ggml_cont(ctx, ggml_view_2d(ctx, cur, hp.n_embd_gqa(), hp.n_tokens, cur->nb[1], 1*sizeof(float)*(hp.n_embd + hp.n_embd_gqa())));
  2604. Qcur = ggml_reshape_3d(ctx, Qcur, hp.n_embd_head, hp.n_head, hp.n_tokens);
  2605. Kcur = ggml_reshape_3d(ctx, Kcur, hp.n_embd_head, hp.n_head_kv, hp.n_tokens);
  2606. // using mode = 2 for neox mode
  2607. Qcur = ggml_rope_ext(
  2608. ctx, Qcur, inp_pos, nullptr, hp.n_rot, 2, hp.n_ctx_orig,
  2609. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  2610. );
  2611. Kcur = ggml_rope_ext(
  2612. ctx, Kcur, inp_pos, nullptr, hp.n_rot, 2, hp.n_ctx_orig,
  2613. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  2614. );
  2615. llm_build_kv_store(ctx, k_l, v_l, Kcur, Vcur);
  2616. cur = llm_build_kqv(ctx, k_l, v_l, Qcur, KQ_mask, 1.0f/sqrtf(float(hp.n_embd_head)));
  2617. }
  2618. struct ggml_tensor * ffn_inp = cur;
  2619. // feed forward
  2620. {
  2621. ggml_tensor * ffn_up = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  2622. ggml_tensor * ffn_down = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_ff, hp.n_embd);
  2623. cur = attn_norm;
  2624. cur = ggml_mul_mat(ctx, ffn_up, cur);
  2625. cur = ggml_gelu(ctx, cur);
  2626. cur = ggml_mul_mat(ctx, ffn_down, cur);
  2627. }
  2628. cur = ggml_add(ctx, cur, ffn_inp);
  2629. cur = ggml_add(ctx, cur, inpL);
  2630. // input for next layer
  2631. inpL = cur;
  2632. }
  2633. cur = inpL;
  2634. ggml_tensor * output_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2635. ggml_tensor * output_norm_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  2636. cur = llm_build_norm(ctx, cur, output_norm, output_norm_b, LLM_NORM);
  2637. // lm_head
  2638. ggml_tensor * output = ggml_new_tensor_2d(ctx, GGML_TYPE_Q8_0, hp.n_embd, hp.n_vocab);
  2639. cur = ggml_mul_mat(ctx, output, cur);
  2640. return cur;
  2641. }
  2642. };
  2643. // ###########################################
  2644. // ## Section 3: GGML Op Test Instantiation ##
  2645. // ###########################################
  2646. static const ggml_type all_types[] = {
  2647. GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16,
  2648. GGML_TYPE_Q4_0, GGML_TYPE_Q4_1,
  2649. GGML_TYPE_Q5_0, GGML_TYPE_Q5_1,
  2650. GGML_TYPE_Q8_0,
  2651. GGML_TYPE_Q2_K, GGML_TYPE_Q3_K,
  2652. GGML_TYPE_Q4_K, GGML_TYPE_Q5_K,
  2653. GGML_TYPE_Q6_K,
  2654. // GGML_TYPE_TQ1_0, GGML_TYPE_TQ2_0, // TODO: implement for all backends
  2655. GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S,
  2656. GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M,
  2657. GGML_TYPE_IQ4_NL, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_XS,
  2658. };
  2659. static const ggml_type base_types[] = {
  2660. GGML_TYPE_F32, GGML_TYPE_F16,
  2661. GGML_TYPE_Q4_0,
  2662. GGML_TYPE_Q4_K,
  2663. GGML_TYPE_IQ2_XXS
  2664. };
  2665. static const ggml_type other_types[] = {
  2666. GGML_TYPE_Q4_1,
  2667. GGML_TYPE_Q5_0, GGML_TYPE_Q5_1,
  2668. GGML_TYPE_Q8_0,
  2669. GGML_TYPE_Q2_K, GGML_TYPE_Q3_K,
  2670. GGML_TYPE_Q5_K,
  2671. GGML_TYPE_Q6_K,
  2672. // GGML_TYPE_TQ1_0, GGML_TYPE_TQ2_0, // TODO: implement for all backends
  2673. GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S,
  2674. GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M,
  2675. GGML_TYPE_IQ4_NL, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_XS,
  2676. GGML_TYPE_BF16,
  2677. };
  2678. // Test cases for evaluation: should try to cover edge cases while using small input sizes to keep the runtime low
  2679. static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
  2680. std::vector<std::unique_ptr<test_case>> test_cases;
  2681. std::default_random_engine rng(0);
  2682. // unary ops
  2683. for (int v : {0, 1}) {
  2684. for (int op = 0; op < GGML_UNARY_OP_COUNT; op++) {
  2685. test_cases.emplace_back(new test_unary((ggml_unary_op) op, GGML_TYPE_F32, { 128, 2, 2, 2 }, v));
  2686. test_cases.emplace_back(new test_unary((ggml_unary_op) op, GGML_TYPE_F32, { 5, 7, 11, 13 }, v));
  2687. }
  2688. }
  2689. test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 1, 8, 2, 1, false));
  2690. for (ggml_type type : all_types) {
  2691. for (int b : {1, 7}) {
  2692. for (bool v : {false, true}) {
  2693. test_cases.emplace_back(new test_get_rows(type, 256, 5, 4, b, v));
  2694. }
  2695. }
  2696. }
  2697. for (int b : {1, 7}) {
  2698. for (bool v : {false, true}) {
  2699. test_cases.emplace_back(new test_get_rows(GGML_TYPE_I32, 256, 5, 4, b, v));
  2700. }
  2701. }
  2702. for (ggml_type type_input : {GGML_TYPE_F32}) {
  2703. for (ggml_op_pool pool_type : {GGML_OP_POOL_AVG, GGML_OP_POOL_MAX}) {
  2704. for (int k0 : {1, 3}) {
  2705. for (int k1 : {1, 3}) {
  2706. for (int s0 : {1, 2}) {
  2707. for (int s1 : {1, 2}) {
  2708. for (int p0 : {0, 1}) {
  2709. for (int p1 : {0, 1}) {
  2710. test_cases.emplace_back(new test_pool2d(pool_type, type_input, {10, 10, 3, 1}, k0, k1, s0, s1, p0, p1));
  2711. }
  2712. }
  2713. }
  2714. }
  2715. }
  2716. }
  2717. }
  2718. }
  2719. // im2col 1D
  2720. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32, {3000, 128, 1, 1}, {3, 128, 1280, 1}, 1, 0, 1, 0, 1, 0, false));
  2721. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F32, {3000, 128, 1, 1}, {3, 128, 1280, 1}, 1, 0, 1, 0, 1, 0, false));
  2722. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {3000, 128, 1, 1}, {3, 128, 1280, 1}, 1, 0, 1, 0, 1, 0, false));
  2723. for (int s0 : {1, 3}) {
  2724. for (int p0 : {0, 3}) {
  2725. for (int d0 : {1, 3}) {
  2726. test_cases.emplace_back(new test_im2col(
  2727. GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32, {20, 2, 2, 1}, {3, 2, 2, 1},
  2728. s0, 0, p0, 0, d0, 0, false));
  2729. }
  2730. }
  2731. }
  2732. // im2col 2D
  2733. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32));
  2734. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F32));
  2735. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16));
  2736. for (int s0 : {1, 3}) {
  2737. for (int s1 : {1, 3}) {
  2738. for (int p0 : {0, 3}) {
  2739. for (int p1 : {0, 3}) {
  2740. for (int d0 : {1, 3}) {
  2741. for (int d1 : {1, 3}) {
  2742. test_cases.emplace_back(new test_im2col(
  2743. GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32, {20, 20, 2, 2}, {3, 3, 2, 2},
  2744. s0, s1, p0, p1, d0, d1, true));
  2745. }
  2746. }
  2747. }
  2748. }
  2749. }
  2750. }
  2751. // extra tests for im2col 2D
  2752. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 32}, {3, 3, 1, 32}, 1, 1, 1, 1, 1, 1, true));
  2753. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 32}, {3, 3, 2, 32}, 1, 1, 1, 1, 1, 1, true));
  2754. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 1024}, {3, 3, 1, 1024}, 1, 1, 1, 1, 1, 1, true));
  2755. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 1024}, {3, 3, 2, 1024}, 1, 1, 1, 1, 1, 1, true));
  2756. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 2048}, {3, 3, 1, 2048}, 1, 1, 1, 1, 1, 1, true));
  2757. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 2048}, {3, 3, 2, 2048}, 1, 1, 1, 1, 1, 1, true));
  2758. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 2560}, {3, 3, 1, 2560}, 1, 1, 1, 1, 1, 1, true));
  2759. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 2560}, {3, 3, 2, 2560}, 1, 1, 1, 1, 1, 1, true));
  2760. // sycl backend will limit task global_range < MAX_INT
  2761. // test cases for 2D im2col with large input W and H (occurs in stable-diffusion)
  2762. // however these cases need to alloc more memory which may fail in some devices (Intel Arc770, etc.)
  2763. // these cases are verified (pass) in Intel(R) Data Center GPU Max 1100 (sycl backend) and NV A30 (cuda backend)
  2764. // test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {1024, 1024, 256, 1}, {3, 3, 256, 1}, 1, 1, 1, 1, 1, 1, true));
  2765. // test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F32, {1024, 1024, 256, 1}, {3, 3, 256, 1}, 1, 1, 1, 1, 1, 1, true));
  2766. test_cases.emplace_back(new test_conv_transpose_1d());
  2767. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 3, 0, 1));
  2768. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 2, 0, 1));
  2769. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 1, 0, 1));
  2770. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,2,2,1}, 2, 0, 1));
  2771. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,2,2,1}, 1, 0, 1));
  2772. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,1,2,1}, 1, 0, 1));
  2773. test_cases.emplace_back(new test_conv_transpose_1d({2,1,1,1}, {3,1,1,1}, 1, 0, 1));
  2774. test_cases.emplace_back(new test_argmax());
  2775. test_cases.emplace_back(new test_count_equal());
  2776. for (int ne3 : {1, 3}) { // CUDA backward pass only supports ne3 == 1
  2777. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 1, 1}));
  2778. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {2, 1, 1, 1}));
  2779. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 2, 1, 1}));
  2780. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 2, 1}));
  2781. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 1, 2}));
  2782. test_cases.emplace_back(new test_repeat(GGML_TYPE_I32, {10, 5, 4, ne3}, {2, 1, 1, 1}));
  2783. test_cases.emplace_back(new test_repeat(GGML_TYPE_I16, {10, 5, 4, ne3}, {1, 1, 1, 2}));
  2784. }
  2785. test_cases.emplace_back(new test_dup(GGML_TYPE_F32));
  2786. test_cases.emplace_back(new test_dup(GGML_TYPE_F16));
  2787. test_cases.emplace_back(new test_dup(GGML_TYPE_I32));
  2788. test_cases.emplace_back(new test_dup(GGML_TYPE_I16));
  2789. test_cases.emplace_back(new test_dup(GGML_TYPE_F32, {10, 10, 5, 1}, {0, 2, 1, 3}));
  2790. test_cases.emplace_back(new test_dup(GGML_TYPE_F16, {10, 10, 5, 1}, {0, 2, 1, 3})); // dup by rows
  2791. test_cases.emplace_back(new test_dup(GGML_TYPE_F32, {10, 10, 5, 1}, {1, 0, 2, 3}));
  2792. test_cases.emplace_back(new test_dup(GGML_TYPE_F16, {10, 10, 5, 1}, {1, 0, 2, 3})); // dup dst not-contiguous
  2793. test_cases.emplace_back(new test_dup(GGML_TYPE_I16, {10, 8, 3, 1}, {0, 2, 1, 3}));
  2794. test_cases.emplace_back(new test_dup(GGML_TYPE_I16, {10, 8, 3, 1}, {1, 2, 0, 3}));
  2795. for (int dim = 1; dim < GGML_MAX_DIMS; ++dim) {
  2796. test_cases.emplace_back(new test_set(GGML_TYPE_F32, GGML_TYPE_F32, {6, 5, 4, 3}, dim));
  2797. }
  2798. for (ggml_type type_src : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  2799. for (ggml_type type_dst : all_types) {
  2800. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 4, 4, 4}));
  2801. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 2, 3, 4}, {0, 2, 1, 3})); // cpy by rows
  2802. }
  2803. }
  2804. for (ggml_type type_src : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  2805. for (ggml_type type_dst : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  2806. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 2, 3, 4}, {1, 0, 2, 3})); // cpy not-contiguous
  2807. }
  2808. }
  2809. test_cases.emplace_back(new test_cont());
  2810. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 1, 1 ,1}));
  2811. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 1, 3 ,5}));
  2812. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 3, 5 ,7}));
  2813. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 1, 1 ,1}));
  2814. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 1, 3 ,5}));
  2815. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 3, 5 ,7}));
  2816. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 1, 1 ,1}));
  2817. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 1, 3 ,5}));
  2818. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 3, 5 ,7}));
  2819. auto add_test_bin_bcast = [&](ggml_type type, std::array<int64_t, 4> ne, std::array<int, 4> nr) {
  2820. for (auto op : {ggml_add, ggml_mul, ggml_div}) {
  2821. test_cases.emplace_back(new test_bin_bcast(op, type, ne, nr));
  2822. }
  2823. };
  2824. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 8, 1}, {1, 1, 1, 1});
  2825. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 1, 1}, {32, 1, 1, 1});
  2826. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 320, 320}, {1, 1, 1, 1});
  2827. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 1, 1}, {1, 1, 1, 1});
  2828. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 1}, {1, 1, 1, 1});
  2829. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 1, 1});
  2830. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {2, 1, 1, 1});
  2831. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 2, 1, 1});
  2832. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 2, 1});
  2833. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 1, 2});
  2834. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 2, 2});
  2835. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {1, 2, 2, 2});
  2836. add_test_bin_bcast(GGML_TYPE_F32, {10, 5, 4, 3}, {2, 2, 2, 2});
  2837. // stable diffusion
  2838. add_test_bin_bcast(GGML_TYPE_F32, {1280, 1, 1, 1}, {1, 1, 1, 1});
  2839. add_test_bin_bcast(GGML_TYPE_F32, {1280, 1, 1, 1}, {1, 16, 16, 1});
  2840. add_test_bin_bcast(GGML_TYPE_F32, {1280, 16, 16, 1}, {1, 1, 1, 1});
  2841. add_test_bin_bcast(GGML_TYPE_F32, {1280, 1, 1, 1}, {1, 256, 1, 1});
  2842. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 1280, 1}, {16, 16, 1, 1});
  2843. add_test_bin_bcast(GGML_TYPE_F32, {16, 16, 1280, 1}, {1, 1, 1, 1});
  2844. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 1920, 1}, {16, 16, 1, 1});
  2845. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 2560, 1}, {16, 16, 1, 1});
  2846. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 1280, 1}, {32, 32, 1, 1});
  2847. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 1920, 1}, {32, 32, 1, 1});
  2848. add_test_bin_bcast(GGML_TYPE_F32, {1, 1, 640, 1}, {32, 32, 1, 1});
  2849. add_test_bin_bcast(GGML_TYPE_F32, {5120, 1, 1, 1}, {1, 256, 1, 1});
  2850. add_test_bin_bcast(GGML_TYPE_F32, {640, 1, 1, 1}, {1, 1, 1, 1});
  2851. //add_test_bin_bcast(GGML_TYPE_F32, {3, 3, 2560, 1280}, {1, 1, 1, 1});
  2852. //add_test_bin_bcast(GGML_TYPE_F32, {3, 3, 2560, 1280}, {2, 1, 1, 1});
  2853. test_cases.emplace_back(new test_add1());
  2854. test_cases.emplace_back(new test_scale());
  2855. for (float eps : {1e-6f, 1e-5f, 1e-3f, 1e-1f}) {
  2856. test_cases.emplace_back(new test_norm(GGML_TYPE_F32, {64, 5, 4, 3}, eps));
  2857. test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {64, 5, 4, 3}, eps));
  2858. }
  2859. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, 1536, 1, 1}, {4, 1536, 1, 1}));
  2860. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {8, 1536, 1, 1}, {4, 1536, 1, 1}));
  2861. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, 1536, 4, 1}, {4, 1536, 1, 1}));
  2862. test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 16, 1024, 32, 4));
  2863. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 1, 1));
  2864. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 32, 1));
  2865. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 32, 4));
  2866. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 128, 4));
  2867. #if 1
  2868. for (ggml_type type_a : base_types) {
  2869. for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  2870. // test cases without permutation
  2871. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, { 1, 1}, {1, 1}));
  2872. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 1}, {1, 1}));
  2873. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 1}, {2, 1}));
  2874. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 10}, {1, 1}));
  2875. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 10}, {2, 1}));
  2876. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 10}, {1, 2}));
  2877. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {10, 10}, {2, 2}));
  2878. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, { 1, 1}, {1, 1}));
  2879. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 1}, {1, 1}));
  2880. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 1}, {2, 1}));
  2881. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 10}, {1, 1}));
  2882. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 10}, {2, 1}));
  2883. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 10}, {1, 2}));
  2884. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {10, 10}, {2, 2}));
  2885. // test cases with permutation
  2886. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  2887. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  2888. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  2889. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, 256, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  2890. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, 256, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  2891. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, 256, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  2892. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  2893. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  2894. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 256, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  2895. }
  2896. }
  2897. for (ggml_type type_a : other_types) {
  2898. for (ggml_type type_b : {GGML_TYPE_F32}) {
  2899. if (ggml_blck_size(type_a) != 256) {
  2900. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, ggml_blck_size(type_a), {1, 1}, {1, 1}));
  2901. }
  2902. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {1, 1}, {1, 1}));
  2903. }
  2904. }
  2905. #else
  2906. // m = a rows
  2907. // n = b rows
  2908. // k = cols
  2909. std::uniform_int_distribution<> dist_m(1, 128);
  2910. std::uniform_int_distribution<> dist_n(16, 128);
  2911. std::uniform_int_distribution<> dist_k(1, 16);
  2912. for (int i = 0; i < 1000; i++) {
  2913. for (ggml_type type_a : all_types) {
  2914. for (ggml_type type_b : {GGML_TYPE_F32}) {
  2915. int m = dist_m(rng);
  2916. int n = dist_n(rng);
  2917. int k = dist_k(rng) * ggml_blck_size(type_a);
  2918. test_cases.emplace_back(new test_mul_mat(type_a, type_b, m, n, k, { 1, 1}, {1, 1}));
  2919. }
  2920. }
  2921. }
  2922. #endif
  2923. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 2, 128, { 8, 1}, {1, 1}));
  2924. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 83, 2, 128, { 8, 1}, {4, 1}));
  2925. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 2, 64, { 8, 1}, {4, 1}));
  2926. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 83, 2, 64, { 8, 1}, {4, 1}));
  2927. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 45, 128, { 8, 1}, {4, 1}));
  2928. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 128, 45, 64, { 8, 1}, {4, 1}));
  2929. // sycl backend will limit task global_range < MAX_INT
  2930. // test case for f16-type-convert-to-fp32 kernel with large k under fp32 compute dtype (occurs in stable-diffusion)
  2931. // however this case needs to alloc more memory which may fail in some devices (Intel Arc770, etc.)
  2932. // this case is verified (pass) in Intel(R) Data Center GPU Max 1100 (sycl backend) and NV A30 (cuda backend)
  2933. // test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F16, 512, 262144, 9216, {1, 1}, {1, 1}));
  2934. for (ggml_type type_a : base_types) {
  2935. for (ggml_type type_b : {GGML_TYPE_F32 /*, GGML_TYPE_F16 */}) {
  2936. for (int n_mats : {4, 8}) {
  2937. for (int n_used : {1, 2, 4}) {
  2938. for (bool b : {false, true}) {
  2939. for (int n : {1, 32}) {
  2940. int m = 512;
  2941. int k = 256;
  2942. test_cases.emplace_back(new test_mul_mat_id(type_a, type_b, n_mats, n_used, b, m, n, k));
  2943. }
  2944. }
  2945. }
  2946. }
  2947. }
  2948. }
  2949. for (ggml_type type_a : other_types) {
  2950. for (ggml_type type_b : {GGML_TYPE_F32 /*, GGML_TYPE_F16 */}) {
  2951. for (int n_mats : {4}) {
  2952. for (int n_used : {2}) {
  2953. for (bool b : {false}) {
  2954. for (int n : {1, 32}) {
  2955. int m = 512;
  2956. int k = 256;
  2957. test_cases.emplace_back(new test_mul_mat_id(type_a, type_b, n_mats, n_used, b, m, n, k));
  2958. }
  2959. }
  2960. }
  2961. }
  2962. }
  2963. }
  2964. for (ggml_type type_a : base_types) {
  2965. for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  2966. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, { 1, 1}));
  2967. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 1}));
  2968. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 1}));
  2969. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 10}));
  2970. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 10}));
  2971. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 10}));
  2972. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 1, 16, {10, 10}));
  2973. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, { 1, 1}));
  2974. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, { 1, 1}, true));
  2975. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 1}));
  2976. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 1}));
  2977. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 10}));
  2978. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 10}));
  2979. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 10}));
  2980. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, 16, 16, {10, 10}));
  2981. }
  2982. }
  2983. test_cases.emplace_back(new test_sqr());
  2984. test_cases.emplace_back(new test_sqrt());
  2985. test_cases.emplace_back(new test_log());
  2986. test_cases.emplace_back(new test_sin());
  2987. test_cases.emplace_back(new test_cos());
  2988. test_cases.emplace_back(new test_clamp());
  2989. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 1, 1}, 5));
  2990. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 1}, 5));
  2991. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 2}, 5));
  2992. #if 0
  2993. std::uniform_int_distribution<> dist_ne1(1, 50);
  2994. int exponent = 1;
  2995. while (exponent < (1 << 17)) {
  2996. std::uniform_int_distribution<> dist_ne0(exponent, 2*exponent);
  2997. for (int n = 0; n < 10; ++n) {
  2998. int64_t ne0 = dist_ne0(rng);
  2999. int64_t ne1 = dist_ne1(rng);
  3000. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, GGML_TYPE_F32, {ne0, ne1, 1, 1}, n/2 == 0, 0.1f, ne0 < 1000 ? 4.0f : 0.0f));
  3001. }
  3002. exponent <<= 1;
  3003. }
  3004. #endif
  3005. for (bool mask : {false, true}) {
  3006. for (float max_bias : {0.0f, 8.0f}) {
  3007. if (!mask && max_bias > 0.0f) continue;
  3008. for (float scale : {1.0f, 0.1f}) {
  3009. for (int64_t ne0 : {16, 1024}) {
  3010. for (int64_t ne1 : {16, 1024}) {
  3011. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0, ne1, 1, 1}, mask, scale, max_bias));
  3012. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0-1, ne1-1, 1, 1}, mask, scale, max_bias));
  3013. }
  3014. }
  3015. }
  3016. }
  3017. }
  3018. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 2, 32, 1}, true, 0.1f, 0.0f));
  3019. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 2, 32, 1}, false, 0.1f, 0.0f));
  3020. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, 0.1f, 0.0f));
  3021. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, 0.1f, 8.0f));
  3022. {
  3023. bool all = true;
  3024. for (float v : { 0, 1 }) {
  3025. for (float fs : { 1.0f, 1.4245f }) {
  3026. for (float ef : { 0.0f, 0.7465f }) {
  3027. for (float af : { 1.0f, 1.4245f }) {
  3028. for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  3029. for (bool ff : {false, true}) { // freq_factors
  3030. test_cases.emplace_back(new test_rope(type, {128, 32, 2, 1}, 128, 0, 512, fs, ef, af, ff, v)); // llama 7B
  3031. if (all) {
  3032. test_cases.emplace_back(new test_rope(type, {128, 40, 2, 1}, 128, 0, 512, fs, ef, af, ff, v)); // llama 13B
  3033. test_cases.emplace_back(new test_rope(type, {128, 52, 2, 1}, 128, 0, 512, fs, ef, af, ff, v)); // llama 30B
  3034. test_cases.emplace_back(new test_rope(type, {128, 64, 2, 1}, 128, 0, 512, fs, ef, af, ff, v)); // llama 65B
  3035. }
  3036. if (all) {
  3037. test_cases.emplace_back(new test_rope(type, { 64, 1, 2, 1}, 64, 2, 512, fs, ef, af, ff, v)); // neox (falcon 7B)
  3038. test_cases.emplace_back(new test_rope(type, { 64, 71, 2, 1}, 64, 2, 512, fs, ef, af, ff, v)); // neox (falcon 7B)
  3039. test_cases.emplace_back(new test_rope(type, { 64, 8, 2, 1}, 64, 2, 512, fs, ef, af, ff, v)); // neox (falcon 40B)
  3040. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 20, 2, 512, fs, ef, af, ff, v)); // neox (stablelm)
  3041. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 32, 2, 512, fs, ef, af, ff, v)); // neox (phi-2)
  3042. }
  3043. test_cases.emplace_back(new test_rope(type, { 64, 128, 2, 1}, 64, 2, 512, fs, ef, af, ff, v)); // neox (falcon 40B)
  3044. }
  3045. }
  3046. all = false;
  3047. }
  3048. }
  3049. }
  3050. }
  3051. }
  3052. for (int v : { 0, 1, 2, 3 }) {
  3053. for (int dim : { 0, 1, 2, 3, }) {
  3054. test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {11, 12, 13, 14}, 7, dim, v));
  3055. test_cases.emplace_back(new test_concat(GGML_TYPE_I32, {11, 12, 13, 14}, 7, dim, v));
  3056. }
  3057. }
  3058. for (ggml_sort_order order : {GGML_SORT_ORDER_ASC, GGML_SORT_ORDER_DESC}) {
  3059. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {8, 1, 1, 1}, order));
  3060. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {16, 10, 10, 10}, order));
  3061. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {60, 10, 10, 10}, order)); // qwen
  3062. }
  3063. test_cases.emplace_back(new test_sum());
  3064. test_cases.emplace_back(new test_sum_rows());
  3065. test_cases.emplace_back(new test_upscale());
  3066. test_cases.emplace_back(new test_upscale(GGML_TYPE_F32, { 512, 512, 3, 1 }, 2, true));
  3067. test_cases.emplace_back(new test_upscale_ext());
  3068. test_cases.emplace_back(new test_group_norm());
  3069. test_cases.emplace_back(new test_acc());
  3070. test_cases.emplace_back(new test_pad());
  3071. test_cases.emplace_back(new test_arange());
  3072. test_cases.emplace_back(new test_timestep_embedding());
  3073. test_cases.emplace_back(new test_leaky_relu());
  3074. for (int hs : { 64, 80, 128, 256, }) {
  3075. for (bool mask : { true, false } ) {
  3076. for (float max_bias : { 0.0f, 8.0f }) {
  3077. if (!mask && max_bias > 0.0f) continue;
  3078. for (float logit_softcap : {0.0f, 10.0f}) {
  3079. if (hs != 128 && logit_softcap != 0.0f) continue;
  3080. for (int nh : { 32, }) {
  3081. for (int kv : { 512, 1024, }) {
  3082. for (int nb : { 1, 3, 32, 35, }) {
  3083. for (ggml_type type_KV : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
  3084. test_cases.emplace_back(new test_flash_attn_ext(hs, nh, kv, nb, mask, max_bias, logit_softcap, type_KV));
  3085. }
  3086. }
  3087. }
  3088. }
  3089. }
  3090. }
  3091. }
  3092. }
  3093. test_cases.emplace_back(new test_cross_entropy_loss());
  3094. for (float wd : {0.0f, 1e-2f}) {
  3095. test_cases.emplace_back(new test_opt_step_adamw(GGML_TYPE_F32, {10, 5, 4, 3}, 1.0f, 1e-3f, 0.9f, 0.999f, wd));
  3096. }
  3097. // these tests are disabled to save execution time, but they can be handy for debugging
  3098. #if 0
  3099. test_cases.emplace_back(new test_llama(1));
  3100. test_cases.emplace_back(new test_llama(2));
  3101. test_cases.emplace_back(new test_falcon(1));
  3102. test_cases.emplace_back(new test_falcon(2));
  3103. #endif
  3104. return test_cases;
  3105. }
  3106. // Test cases for performance evaluation: should be representative of real-world use cases
  3107. static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
  3108. std::vector<std::unique_ptr<test_case>> test_cases;
  3109. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {4096, 1, 1, 1}, {1, 1, 1, 1}));
  3110. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {4096, 1, 1, 1}, {1, 512, 1, 1}));
  3111. test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F16, {512, 3072, 1, 1}));
  3112. for (int bs : {1, 512}) {
  3113. for (ggml_type type_a : all_types) {
  3114. for (ggml_type type_b : {GGML_TYPE_F32}) {
  3115. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 4096, bs, 14336, {1, 1}, {1, 1}));
  3116. }
  3117. }
  3118. }
  3119. return test_cases;
  3120. }
  3121. static bool test_backend(ggml_backend_t backend, test_mode mode, const char * op_name) {
  3122. if (mode == MODE_TEST) {
  3123. auto test_cases = make_test_cases_eval();
  3124. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  3125. size_t n_ok = 0;
  3126. for (auto & test : test_cases) {
  3127. if (test->eval(backend, backend_cpu, op_name)) {
  3128. n_ok++;
  3129. }
  3130. }
  3131. printf(" %zu/%zu tests passed\n", n_ok, test_cases.size());
  3132. ggml_backend_free(backend_cpu);
  3133. return n_ok == test_cases.size();
  3134. }
  3135. if (mode == MODE_GRAD) {
  3136. auto test_cases = make_test_cases_eval();
  3137. size_t n_ok = 0;
  3138. for (auto & test : test_cases) {
  3139. if (test->eval_grad(backend, op_name)) {
  3140. n_ok++;
  3141. }
  3142. }
  3143. printf(" %zu/%zu tests passed\n", n_ok, test_cases.size());
  3144. return n_ok == test_cases.size();
  3145. }
  3146. if (mode == MODE_PERF) {
  3147. auto test_cases = make_test_cases_perf();
  3148. for (auto & test : test_cases) {
  3149. test->eval_perf(backend, op_name);
  3150. }
  3151. return true;
  3152. }
  3153. GGML_ABORT("fatal error");
  3154. }
  3155. static void usage(char ** argv) {
  3156. printf("Usage: %s [mode] [-o op] [-b backend]\n", argv[0]);
  3157. printf(" valid modes:\n");
  3158. printf(" - test (default, compare with CPU backend for correctness)\n");
  3159. printf(" - grad (compare gradients from backpropagation with method of finite differences)\n");
  3160. printf(" - perf (performance evaluation)\n");
  3161. printf(" op names for -o are as given by ggml_op_desc() (e.g. ADD, MUL_MAT, etc)\n");
  3162. }
  3163. int main(int argc, char ** argv) {
  3164. test_mode mode = MODE_TEST;
  3165. const char * op_name_filter = NULL;
  3166. const char * backend_filter = NULL;
  3167. for (int i = 1; i < argc; i++) {
  3168. if (strcmp(argv[i], "test") == 0) {
  3169. mode = MODE_TEST;
  3170. } else if (strcmp(argv[i], "perf") == 0) {
  3171. mode = MODE_PERF;
  3172. } else if (strcmp(argv[i], "grad") == 0) {
  3173. mode = MODE_GRAD;
  3174. } else if (strcmp(argv[i], "-o") == 0) {
  3175. if (i + 1 < argc) {
  3176. op_name_filter = argv[++i];
  3177. } else {
  3178. usage(argv);
  3179. return 1;
  3180. }
  3181. } else if (strcmp(argv[i], "-b") == 0) {
  3182. if (i + 1 < argc) {
  3183. backend_filter = argv[++i];
  3184. } else {
  3185. usage(argv);
  3186. return 1;
  3187. }
  3188. } else {
  3189. usage(argv);
  3190. return 1;
  3191. }
  3192. }
  3193. // enumerate backends
  3194. printf("Testing %zu devices\n\n", ggml_backend_dev_count());
  3195. size_t n_ok = 0;
  3196. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  3197. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  3198. printf("Backend %zu/%zu: %s\n", i + 1, ggml_backend_dev_count(), ggml_backend_dev_name(dev));
  3199. if (backend_filter != NULL && strcmp(backend_filter, ggml_backend_dev_name(dev)) != 0) {
  3200. printf(" Skipping\n");
  3201. n_ok++;
  3202. continue;
  3203. }
  3204. ggml_backend_t backend = ggml_backend_dev_init(dev, NULL);
  3205. GGML_ASSERT(backend != NULL);
  3206. if (backend_filter == NULL && ggml_backend_is_cpu(backend) && mode != MODE_GRAD) {
  3207. printf(" Skipping CPU backend\n");
  3208. ggml_backend_free(backend);
  3209. n_ok++;
  3210. continue;
  3211. }
  3212. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  3213. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  3214. if (ggml_backend_set_n_threads_fn) {
  3215. // TODO: better value for n_threads
  3216. ggml_backend_set_n_threads_fn(backend, std::thread::hardware_concurrency());
  3217. }
  3218. printf(" Device description: %s\n", ggml_backend_dev_description(dev));
  3219. size_t free, total; // NOLINT
  3220. ggml_backend_dev_memory(dev, &free, &total);
  3221. printf(" Device memory: %zu MB (%zu MB free)\n", total / 1024 / 1024, free / 1024 / 1024);
  3222. printf("\n");
  3223. bool ok = test_backend(backend, mode, op_name_filter);
  3224. printf(" Backend %s: ", ggml_backend_name(backend));
  3225. if (ok) {
  3226. printf("\033[1;32mOK\033[0m\n");
  3227. n_ok++;
  3228. } else {
  3229. printf("\033[1;31mFAIL\033[0m\n");
  3230. }
  3231. printf("\n");
  3232. ggml_backend_free(backend);
  3233. }
  3234. printf("%zu/%zu backends passed\n", n_ok, ggml_backend_dev_count());
  3235. if (n_ok != ggml_backend_dev_count()) {
  3236. printf("\033[1;31mFAIL\033[0m\n");
  3237. return 1;
  3238. }
  3239. ggml_quantize_free();
  3240. printf("\033[1;32mOK\033[0m\n");
  3241. return 0;
  3242. }