test-backend-ops.cpp 133 KB

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