test-backend-ops.cpp 140 KB

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