test-backend-ops.cpp 137 KB

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