test-backend-ops.cpp 133 KB

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