test-backend-ops.cpp 228 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138
  1. // This file defines tests for various GGML ops and backends.
  2. // For the forward pass it asserts that the results of multiple backends computing the same GGML ops are consistent.
  3. // For the backward pass it asserts that the gradients from backpropagation are consistent
  4. // with the gradients obtained via the method of finite differences ("grad" mode, this is optional).
  5. // It is also possible to check the performance ("perf" mode).
  6. //
  7. // this file has three sections: Section 1 does general setup, section 2 defines the GGML ops to be tested,
  8. // and section 3 defines which tests to run.
  9. // Quick start for adding a new GGML op: Go to section 2 and create a struct that inherits from test_case,
  10. // then go to section 3 and add an instantiation of your struct.
  11. // ##############################
  12. // ## Section 1: General Setup ##
  13. // ##############################
  14. #include <ggml.h>
  15. #include <ggml-alloc.h>
  16. #include <ggml-backend.h>
  17. #include <ggml-cpp.h>
  18. #include <algorithm>
  19. #include <array>
  20. #include <cfloat>
  21. #include <cinttypes>
  22. #include <cstdarg>
  23. #include <cstdint>
  24. #include <cstdio>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <ctime>
  28. #include <future>
  29. #include <memory>
  30. #include <random>
  31. #include <regex>
  32. #include <string>
  33. #include <thread>
  34. #include <vector>
  35. static void init_tensor_uniform(ggml_tensor * tensor, float min = -1.0f, float max = 1.0f) {
  36. size_t nels = ggml_nelements(tensor);
  37. std::vector<float> data(nels);
  38. {
  39. // parallel initialization
  40. static const size_t n_threads = std::thread::hardware_concurrency();
  41. // static RNG initialization (revisit if n_threads stops being constant)
  42. static std::vector<std::default_random_engine> generators = []() {
  43. std::random_device rd;
  44. std::vector<std::default_random_engine> vec;
  45. vec.reserve(n_threads);
  46. //for (size_t i = 0; i < n_threads; i++) { vec.emplace_back(1234 + i); } // fixed seed
  47. for (size_t i = 0; i < n_threads; i++) { vec.emplace_back(rd()); }
  48. return vec;
  49. }();
  50. auto init_thread = [&](size_t ith, size_t start, size_t end) {
  51. std::uniform_real_distribution<float> distribution(min, max);
  52. auto & gen = generators[ith];
  53. for (size_t i = start; i < end; i++) {
  54. data[i] = distribution(gen);
  55. }
  56. };
  57. std::vector<std::future<void>> tasks;
  58. tasks.reserve(n_threads);
  59. for (size_t i = 0; i < n_threads; i++) {
  60. size_t start = i*nels/n_threads;
  61. size_t end = (i+1)*nels/n_threads;
  62. tasks.push_back(std::async(std::launch::async, init_thread, i, start, end));
  63. }
  64. for (auto & t : tasks) {
  65. t.get();
  66. }
  67. }
  68. if (tensor->type == GGML_TYPE_F32 || tensor->type == GGML_TYPE_I32) {
  69. ggml_backend_tensor_set(tensor, data.data(), 0, nels * sizeof(float));
  70. } else if (ggml_is_quantized(tensor->type) || tensor->type == GGML_TYPE_F16 || tensor->type == GGML_TYPE_BF16) {
  71. GGML_ASSERT(nels % ggml_blck_size(tensor->type) == 0);
  72. // dummy importance matrix
  73. std::vector<float> imatrix(tensor->ne[0], 1.0f);
  74. const float * im = imatrix.data();
  75. if (!ggml_quantize_requires_imatrix(tensor->type)) {
  76. // when the imatrix is optional, we want to test both quantization with and without imatrix
  77. // use one of the random numbers to decide
  78. if (data[0] > 0.5f*(min + max)) {
  79. im = nullptr;
  80. }
  81. }
  82. std::vector<uint8_t> dataq(ggml_row_size(tensor->type, nels));
  83. {
  84. // parallel quantization by block
  85. size_t blck_size = ggml_blck_size(tensor->type);
  86. size_t n_blocks = nels / blck_size;
  87. auto quantize_thread = [&](size_t start, size_t end) {
  88. ggml_quantize_chunk(tensor->type, data.data(), dataq.data(),
  89. start * blck_size, end - start, blck_size, im);
  90. };
  91. const size_t min_blocks_per_thread = 1;
  92. const size_t n_threads = std::min<size_t>(std::thread::hardware_concurrency()/2,
  93. std::max<size_t>(1, n_blocks / min_blocks_per_thread));
  94. std::vector<std::future<void>> tasks;
  95. tasks.reserve(n_threads);
  96. for (size_t i = 0; i < n_threads; i++) {
  97. size_t start = i*n_blocks/n_threads;
  98. size_t end = (i+1)*n_blocks/n_threads;
  99. tasks.push_back(std::async(std::launch::async, quantize_thread, start, end));
  100. }
  101. for (auto & t : tasks) {
  102. t.get();
  103. }
  104. }
  105. ggml_backend_tensor_set(tensor, dataq.data(), 0, dataq.size());
  106. } else if (tensor->type == GGML_TYPE_I8 || tensor->type == GGML_TYPE_I16 || tensor->type == GGML_TYPE_I32) {
  107. // This is going to create some weird integers though.
  108. ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor));
  109. } else if (tensor->type == GGML_TYPE_I64) {
  110. // Integers with a size of 8 bytes can be set by mirroring the float data, the specific values are again not really meaningful.
  111. const size_t nbytes_half = ggml_nbytes(tensor)/2;
  112. ggml_backend_tensor_set(tensor, data.data(), 0*nbytes_half, nbytes_half);
  113. ggml_backend_tensor_set(tensor, data.data(), 1*nbytes_half, nbytes_half);
  114. } else {
  115. GGML_ABORT("fatal error");
  116. }
  117. }
  118. static std::vector<float> tensor_to_float(const ggml_tensor * t) {
  119. std::vector<float> tv;
  120. tv.reserve(ggml_nelements(t));
  121. std::vector<uint8_t> buf(ggml_nbytes(t));
  122. ggml_backend_tensor_get(t, buf.data(), 0, ggml_nbytes(t));
  123. const auto * tt = ggml_get_type_traits(t->type);
  124. size_t bs = ggml_blck_size(t->type);
  125. std::vector<float> vq(ggml_blck_size(t->type));
  126. bool quantized = ggml_is_quantized(t->type);
  127. // access elements by index to avoid gaps in views
  128. for (int64_t i3 = 0; i3 < t->ne[3]; i3++) {
  129. for (int64_t i2 = 0; i2 < t->ne[2]; i2++) {
  130. for (int64_t i1 = 0; i1 < t->ne[1]; i1++) {
  131. for (int64_t i0 = 0; i0 < t->ne[0]; i0 += bs) {
  132. size_t i = i3*t->nb[3] + i2*t->nb[2] + i1*t->nb[1] + i0/bs*t->nb[0];
  133. if (t->type == GGML_TYPE_F16) {
  134. tv.push_back(ggml_fp16_to_fp32(*(ggml_fp16_t*)&buf[i]));
  135. } else if (t->type == GGML_TYPE_BF16) {
  136. tv.push_back(ggml_bf16_to_fp32(*(ggml_bf16_t*)&buf[i]));
  137. } else if (t->type == GGML_TYPE_F32) {
  138. tv.push_back(*(float *) &buf[i]);
  139. } else if (t->type == GGML_TYPE_I64) {
  140. tv.push_back((float)*(int64_t *) &buf[i]);
  141. } else if (t->type == GGML_TYPE_I32) {
  142. tv.push_back((float)*(int32_t *) &buf[i]);
  143. } else if (t->type == GGML_TYPE_I16) {
  144. tv.push_back((float)*(int16_t *) &buf[i]);
  145. } else if (t->type == GGML_TYPE_I8) {
  146. tv.push_back((float)*(int8_t *) &buf[i]);
  147. } else if (quantized) {
  148. tt->to_float(&buf[i], vq.data(), bs);
  149. tv.insert(tv.end(), vq.begin(), vq.end());
  150. } else {
  151. GGML_ABORT("fatal error");
  152. }
  153. }
  154. }
  155. }
  156. }
  157. return tv;
  158. }
  159. // normalized mean squared error = mse(a, b) / mse(a, 0)
  160. static double nmse(const float * a, const float * b, size_t n) {
  161. double mse_a_b = 0.0;
  162. double mse_a_0 = 0.0;
  163. for (size_t i = 0; i < n; i++) {
  164. float a_i = a[i];
  165. float b_i = b[i];
  166. mse_a_b += (a_i - b_i) * (a_i - b_i);
  167. mse_a_0 += a_i * a_i;
  168. }
  169. return mse_a_b / mse_a_0;
  170. }
  171. // maximum absolute asymmetry between a and b
  172. // asymmetry: (a - b) / (a + b)
  173. // This is more stable than relative error if one of the values fluctuates towards zero.
  174. // n: number of values to compare.
  175. // expected_vals: optional vector of expected values for a. If expected_vals is not empty, filter out all comparisons where
  176. // a does not match any of the expected values. Needed for noncontinuous gradients where the numerical calculation can fail.
  177. static double mean_abs_asymm(const float * a, const float * b, const size_t n, const std::vector<float> & expected_vals) {
  178. double sum = 0.0f;
  179. size_t nvalid = 0;
  180. for (size_t i = 0; i < n; i++) {
  181. if (!expected_vals.empty()) {
  182. bool matches_any = false;
  183. for (const float & ev : expected_vals) {
  184. if (fabsf(a[i] - ev) < 1e-3f) {
  185. matches_any = true;
  186. break;
  187. }
  188. }
  189. if (!matches_any) {
  190. continue;
  191. }
  192. }
  193. const float asymm = (a[i] - b[i]) / (a[i] + b[i]);
  194. sum += fabsf(asymm);
  195. nvalid++;
  196. }
  197. return sum/nvalid;
  198. }
  199. // utils for printing the variables of the test cases
  200. template<typename T>
  201. static std::string var_to_str(const T & x) {
  202. return std::to_string(x);
  203. }
  204. template<typename T, size_t N>
  205. static std::string var_to_str(const T (&x)[N]) {
  206. std::string s = "[";
  207. for (size_t i = 0; i < N; i++) {
  208. if (i > 0) {
  209. s += ",";
  210. }
  211. s += var_to_str(x[i]);
  212. }
  213. s += "]";
  214. return s;
  215. }
  216. template<typename T, size_t N>
  217. static std::string var_to_str(const std::array<T, N> & x) {
  218. std::string s = "[";
  219. for (size_t i = 0; i < N; i++) {
  220. if (i > 0) {
  221. s += ",";
  222. }
  223. s += var_to_str(x[i]);
  224. }
  225. s += "]";
  226. return s;
  227. }
  228. static std::string var_to_str(ggml_type type) {
  229. return ggml_type_name(type);
  230. }
  231. static std::string var_to_str(ggml_prec prec) {
  232. return prec == GGML_PREC_F32 ? "f32" : "def";
  233. }
  234. static std::string var_to_str(ggml_op_pool pool) {
  235. switch (pool) {
  236. case GGML_OP_POOL_AVG: return "avg";
  237. case GGML_OP_POOL_MAX: return "max";
  238. default: return std::to_string(pool);
  239. }
  240. }
  241. static std::string var_to_str(ggml_scale_mode mode) {
  242. switch (mode) {
  243. case GGML_SCALE_MODE_NEAREST: return "nearest";
  244. case GGML_SCALE_MODE_BILINEAR: return "bilinear";
  245. default: return std::to_string(mode);
  246. }
  247. }
  248. #define VAR_TO_STR(x) (#x "=" + var_to_str(x))
  249. #define VARS_TO_STR1(a) VAR_TO_STR(a)
  250. #define VARS_TO_STR2(a, b) VAR_TO_STR(a) + "," + VAR_TO_STR(b)
  251. #define VARS_TO_STR3(a, b, c) VAR_TO_STR(a) + "," + VARS_TO_STR2(b, c)
  252. #define VARS_TO_STR4(a, b, c, d) VAR_TO_STR(a) + "," + VARS_TO_STR3(b, c, d)
  253. #define VARS_TO_STR5(a, b, c, d, e) VAR_TO_STR(a) + "," + VARS_TO_STR4(b, c, d, e)
  254. #define VARS_TO_STR6(a, b, c, d, e, f) VAR_TO_STR(a) + "," + VARS_TO_STR5(b, c, d, e, f)
  255. #define VARS_TO_STR7(a, b, c, d, e, f, g) VAR_TO_STR(a) + "," + VARS_TO_STR6(b, c, d, e, f, g)
  256. #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)
  257. #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)
  258. #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)
  259. #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)
  260. #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)
  261. #ifdef GGML_USE_SYCL
  262. static bool inline _isinf(float f) {
  263. return (*(uint32_t *)&f & 0x7fffffff) == 0x7f800000;
  264. }
  265. #else
  266. static bool inline _isinf(float f) { return std::isinf(f); }
  267. #endif
  268. // accept FLT_MAX as infinity
  269. static bool isinf_or_max(float f) {
  270. return _isinf(f) || f == FLT_MAX || f == -FLT_MAX;
  271. }
  272. static bool ggml_is_view_op(enum ggml_op op) {
  273. return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE;
  274. }
  275. enum test_mode {
  276. MODE_TEST,
  277. MODE_PERF,
  278. MODE_GRAD,
  279. MODE_SUPPORT,
  280. };
  281. // Output format support similar to llama-bench
  282. enum output_formats { CONSOLE, SQL, CSV };
  283. static const char * output_format_str(output_formats format) {
  284. switch (format) {
  285. case CONSOLE:
  286. return "console";
  287. case SQL:
  288. return "sql";
  289. case CSV:
  290. return "csv";
  291. default:
  292. GGML_ABORT("invalid output format");
  293. }
  294. }
  295. static bool output_format_from_str(const std::string & s, output_formats & format) {
  296. if (s == "console") {
  297. format = CONSOLE;
  298. } else if (s == "sql") {
  299. format = SQL;
  300. } else if (s == "csv") {
  301. format = CSV;
  302. } else {
  303. return false;
  304. }
  305. return true;
  306. }
  307. // Test result structure for SQL output
  308. struct test_result {
  309. std::string test_time;
  310. std::string build_commit;
  311. std::string backend_name;
  312. std::string op_name;
  313. std::string op_params;
  314. std::string test_mode;
  315. bool supported;
  316. bool passed;
  317. std::string error_message;
  318. double time_us;
  319. double flops;
  320. double bandwidth_gb_s;
  321. size_t memory_kb;
  322. int n_runs;
  323. std::string device_description;
  324. std::string backend_reg_name;
  325. test_result() {
  326. // Initialize with default values
  327. time_us = 0.0;
  328. flops = 0.0;
  329. bandwidth_gb_s = 0.0;
  330. memory_kb = 0;
  331. n_runs = 0;
  332. supported = false;
  333. passed = false;
  334. // Set test time
  335. time_t t = time(NULL);
  336. char buf[32];
  337. std::strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&t));
  338. test_time = buf;
  339. // Set build info
  340. build_commit = ggml_commit();
  341. }
  342. test_result(const std::string & backend_name, const std::string & op_name, const std::string & op_params,
  343. const std::string & test_mode, bool supported, bool passed, const std::string & error_message = "",
  344. double time_us = 0.0, double flops = 0.0, double bandwidth_gb_s = 0.0, size_t memory_kb = 0,
  345. int n_runs = 0, const std::string & device_description = "", const std::string & backend_reg_name = "") :
  346. backend_name(backend_name),
  347. op_name(op_name),
  348. op_params(op_params),
  349. test_mode(test_mode),
  350. supported(supported),
  351. passed(passed),
  352. error_message(error_message),
  353. time_us(time_us),
  354. flops(flops),
  355. bandwidth_gb_s(bandwidth_gb_s),
  356. memory_kb(memory_kb),
  357. n_runs(n_runs),
  358. device_description(device_description),
  359. backend_reg_name(backend_reg_name) {
  360. // Set test time
  361. time_t t = time(NULL);
  362. char buf[32];
  363. std::strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&t));
  364. test_time = buf;
  365. // Set build info
  366. build_commit = ggml_commit();
  367. }
  368. static const std::vector<std::string> & get_fields() {
  369. static const std::vector<std::string> fields = {
  370. "test_time", "build_commit", "backend_name", "op_name", "op_params", "test_mode", "supported",
  371. "passed", "error_message", "time_us", "flops", "bandwidth_gb_s", "memory_kb", "n_runs",
  372. "device_description", "backend_reg_name"
  373. };
  374. return fields;
  375. }
  376. enum field_type { STRING, BOOL, INT, FLOAT };
  377. static field_type get_field_type(const std::string & field) {
  378. if (field == "supported" || field == "passed") {
  379. return BOOL;
  380. }
  381. if (field == "memory_kb" || field == "n_runs") {
  382. return INT;
  383. }
  384. if (field == "time_us" || field == "flops" || field == "bandwidth_gb_s") {
  385. return FLOAT;
  386. }
  387. return STRING;
  388. }
  389. std::vector<std::string> get_values() const {
  390. return { test_time,
  391. build_commit,
  392. backend_name,
  393. op_name,
  394. op_params,
  395. test_mode,
  396. std::to_string(supported),
  397. std::to_string(passed),
  398. error_message,
  399. std::to_string(time_us),
  400. std::to_string(flops),
  401. std::to_string(bandwidth_gb_s),
  402. std::to_string(memory_kb),
  403. std::to_string(n_runs),
  404. device_description,
  405. backend_reg_name };
  406. }
  407. };
  408. // Printer classes for different output formats
  409. enum class test_status_t { NOT_SUPPORTED, OK, FAIL };
  410. struct test_operation_info {
  411. std::string op_name;
  412. std::string op_params;
  413. std::string backend_name;
  414. test_status_t status = test_status_t::OK;
  415. std::string failure_reason;
  416. // Additional information fields that were previously in separate structs
  417. std::string error_component;
  418. std::string error_details;
  419. // Gradient info
  420. int64_t gradient_index = -1;
  421. std::string gradient_param_name;
  422. float gradient_value = 0.0f;
  423. // MAA error info
  424. double maa_error = 0.0;
  425. double maa_threshold = 0.0;
  426. // Flags for different types of information
  427. bool has_error = false;
  428. bool has_gradient_info = false;
  429. bool has_maa_error = false;
  430. bool is_compare_failure = false;
  431. bool is_large_tensor_skip = false;
  432. test_operation_info() = default;
  433. test_operation_info(const std::string & op_name, const std::string & op_params, const std::string & backend_name,
  434. test_status_t status = test_status_t::OK, const std::string & failure_reason = "") :
  435. op_name(op_name),
  436. op_params(op_params),
  437. backend_name(backend_name),
  438. status(status),
  439. failure_reason(failure_reason) {}
  440. // Set error information
  441. void set_error(const std::string & component, const std::string & details) {
  442. has_error = true;
  443. error_component = component;
  444. error_details = details;
  445. if (status == test_status_t::OK) {
  446. status = test_status_t::FAIL;
  447. }
  448. }
  449. // Set gradient information
  450. void set_gradient_info(int64_t index, const std::string & param_name, float value) {
  451. has_gradient_info = true;
  452. gradient_index = index;
  453. gradient_param_name = param_name;
  454. gradient_value = value;
  455. if (status == test_status_t::OK) {
  456. status = test_status_t::FAIL;
  457. }
  458. }
  459. // Set MAA error information
  460. void set_maa_error(double error, double threshold) {
  461. has_maa_error = true;
  462. maa_error = error;
  463. maa_threshold = threshold;
  464. if (status == test_status_t::OK) {
  465. status = test_status_t::FAIL;
  466. }
  467. }
  468. // Set compare failure
  469. void set_compare_failure() {
  470. is_compare_failure = true;
  471. if (status == test_status_t::OK) {
  472. status = test_status_t::FAIL;
  473. }
  474. }
  475. // Set large tensor skip
  476. void set_large_tensor_skip() { is_large_tensor_skip = true; }
  477. };
  478. struct test_summary_info {
  479. size_t tests_passed;
  480. size_t tests_total;
  481. bool is_backend_summary = false; // true for backend summary, false for test summary
  482. test_summary_info() = default;
  483. test_summary_info(size_t tests_passed, size_t tests_total, bool is_backend_summary = false) :
  484. tests_passed(tests_passed),
  485. tests_total(tests_total),
  486. is_backend_summary(is_backend_summary) {}
  487. };
  488. struct testing_start_info {
  489. size_t device_count;
  490. testing_start_info() = default;
  491. testing_start_info(size_t device_count) : device_count(device_count) {}
  492. };
  493. struct backend_init_info {
  494. size_t device_index;
  495. size_t total_devices;
  496. std::string device_name;
  497. bool skipped = false;
  498. std::string skip_reason;
  499. std::string description;
  500. size_t memory_total_mb = 0;
  501. size_t memory_free_mb = 0;
  502. bool has_memory_info = false;
  503. backend_init_info() = default;
  504. backend_init_info(size_t device_index, size_t total_devices, const std::string & device_name, bool skipped = false,
  505. const std::string & skip_reason = "", const std::string & description = "",
  506. size_t memory_total_mb = 0, size_t memory_free_mb = 0, bool has_memory_info = false) :
  507. device_index(device_index),
  508. total_devices(total_devices),
  509. device_name(device_name),
  510. skipped(skipped),
  511. skip_reason(skip_reason),
  512. description(description),
  513. memory_total_mb(memory_total_mb),
  514. memory_free_mb(memory_free_mb),
  515. has_memory_info(has_memory_info) {}
  516. };
  517. struct backend_status_info {
  518. std::string backend_name;
  519. test_status_t status;
  520. backend_status_info() = default;
  521. backend_status_info(const std::string & backend_name, test_status_t status) :
  522. backend_name(backend_name),
  523. status(status) {}
  524. };
  525. struct overall_summary_info {
  526. size_t backends_passed;
  527. size_t backends_total;
  528. bool all_passed;
  529. overall_summary_info() = default;
  530. overall_summary_info(size_t backends_passed, size_t backends_total, bool all_passed) :
  531. backends_passed(backends_passed),
  532. backends_total(backends_total),
  533. all_passed(all_passed) {}
  534. };
  535. struct printer {
  536. virtual ~printer() {}
  537. FILE * fout = stdout;
  538. virtual void print_header() {}
  539. virtual void print_test_result(const test_result & result) = 0;
  540. virtual void print_footer() {}
  541. virtual void print_operation(const test_operation_info & info) { (void) info; }
  542. virtual void print_summary(const test_summary_info & info) { (void) info; }
  543. virtual void print_testing_start(const testing_start_info & info) { (void) info; }
  544. virtual void print_backend_init(const backend_init_info & info) { (void) info; }
  545. virtual void print_backend_status(const backend_status_info & info) { (void) info; }
  546. virtual void print_overall_summary(const overall_summary_info & info) { (void) info; }
  547. };
  548. struct console_printer : public printer {
  549. void print_test_result(const test_result & result) override {
  550. if (result.test_mode == "test") {
  551. print_test_console(result);
  552. } else if (result.test_mode == "perf") {
  553. print_perf_console(result);
  554. } else if (result.test_mode == "support") {
  555. print_support_console(result);
  556. }
  557. }
  558. void print_operation(const test_operation_info & info) override {
  559. printf(" %s(%s): ", info.op_name.c_str(), info.op_params.c_str());
  560. fflush(stdout);
  561. // Handle large tensor skip first
  562. if (info.is_large_tensor_skip) {
  563. printf("skipping large tensors for speed \n");
  564. return;
  565. }
  566. // Handle not supported status
  567. if (info.status == test_status_t::NOT_SUPPORTED) {
  568. if (!info.failure_reason.empty()) {
  569. printf("not supported [%s]\n", info.failure_reason.c_str());
  570. } else {
  571. printf("not supported [%s]\n", info.backend_name.c_str());
  572. }
  573. return;
  574. }
  575. // Handle errors and additional information
  576. if (info.has_error) {
  577. if (info.error_component == "allocation") {
  578. fprintf(stderr, "failed to allocate tensors [%s] ", info.backend_name.c_str());
  579. } else if (info.error_component == "backend") {
  580. fprintf(stderr, " Failed to initialize %s backend\n", info.backend_name.c_str());
  581. } else {
  582. fprintf(stderr, "Error in %s: %s\n", info.error_component.c_str(), info.error_details.c_str());
  583. }
  584. }
  585. // Handle gradient info
  586. if (info.has_gradient_info) {
  587. printf("[%s] nonfinite gradient at index %" PRId64 " (%s=%f) ", info.op_name.c_str(), info.gradient_index,
  588. info.gradient_param_name.c_str(), info.gradient_value);
  589. }
  590. // Handle MAA error
  591. if (info.has_maa_error) {
  592. printf("[%s] MAA = %.9f > %.9f ", info.op_name.c_str(), info.maa_error, info.maa_threshold);
  593. }
  594. // Handle compare failure
  595. if (info.is_compare_failure) {
  596. printf("compare failed ");
  597. }
  598. // Print final status
  599. if (info.status == test_status_t::OK) {
  600. printf("\033[1;32mOK\033[0m\n");
  601. } else {
  602. printf("\033[1;31mFAIL\033[0m\n");
  603. }
  604. }
  605. void print_summary(const test_summary_info & info) override {
  606. if (info.is_backend_summary) {
  607. printf("%zu/%zu backends passed\n", info.tests_passed, info.tests_total);
  608. } else {
  609. printf(" %zu/%zu tests passed\n", info.tests_passed, info.tests_total);
  610. }
  611. }
  612. void print_backend_status(const backend_status_info & info) override {
  613. printf(" Backend %s: ", info.backend_name.c_str());
  614. if (info.status == test_status_t::OK) {
  615. printf("\033[1;32mOK\033[0m\n");
  616. } else {
  617. printf("\033[1;31mFAIL\033[0m\n");
  618. }
  619. }
  620. void print_testing_start(const testing_start_info & info) override {
  621. printf("Testing %zu devices\n\n", info.device_count);
  622. }
  623. void print_backend_init(const backend_init_info & info) override {
  624. printf("Backend %zu/%zu: %s\n", info.device_index + 1, info.total_devices, info.device_name.c_str());
  625. if (info.skipped) {
  626. printf(" %s\n", info.skip_reason.c_str());
  627. return;
  628. }
  629. if (!info.description.empty()) {
  630. printf(" Device description: %s\n", info.description.c_str());
  631. }
  632. if (info.has_memory_info) {
  633. printf(" Device memory: %zu MB (%zu MB free)\n", info.memory_total_mb, info.memory_free_mb);
  634. }
  635. printf("\n");
  636. }
  637. void print_overall_summary(const overall_summary_info & info) override {
  638. printf("%zu/%zu backends passed\n", info.backends_passed, info.backends_total);
  639. if (info.all_passed) {
  640. printf("\033[1;32mOK\033[0m\n");
  641. } else {
  642. printf("\033[1;31mFAIL\033[0m\n");
  643. }
  644. }
  645. private:
  646. void print_test_console(const test_result & result) {
  647. printf(" %s(%s): ", result.op_name.c_str(), result.op_params.c_str());
  648. fflush(stdout);
  649. if (!result.supported) {
  650. printf("not supported [%s] ", result.backend_name.c_str());
  651. printf("\n");
  652. return;
  653. }
  654. if (result.passed) {
  655. printf("\033[1;32mOK\033[0m\n");
  656. } else {
  657. printf("\033[1;31mFAIL\033[0m\n");
  658. }
  659. }
  660. void print_perf_console(const test_result & result) {
  661. int len = printf(" %s(%s): ", result.op_name.c_str(), result.op_params.c_str());
  662. fflush(stdout);
  663. if (!result.supported) {
  664. printf("not supported\n");
  665. return;
  666. }
  667. // align while also leaving some margin for variations in parameters
  668. int align = 8;
  669. int last = (len + align - 1) / align * align;
  670. if (last - len < 5) {
  671. last += align;
  672. }
  673. printf("%*s", last - len, "");
  674. printf(" %8d runs - %8.2f us/run - ", result.n_runs, result.time_us);
  675. if (result.flops > 0) {
  676. auto format_flops = [](double flops) -> std::string {
  677. char buf[256];
  678. if (flops >= 1e12) {
  679. snprintf(buf, sizeof(buf), "%6.2f TFLOP", flops / 1e12);
  680. } else if (flops >= 1e9) {
  681. snprintf(buf, sizeof(buf), "%6.2f GFLOP", flops / 1e9);
  682. } else if (flops >= 1e6) {
  683. snprintf(buf, sizeof(buf), "%6.2f MFLOP", flops / 1e6);
  684. } else {
  685. snprintf(buf, sizeof(buf), "%6.2f kFLOP", flops / 1e3);
  686. }
  687. return buf;
  688. };
  689. uint64_t op_flops_per_run = result.flops * result.time_us / 1e6;
  690. printf("%s/run - \033[1;34m%sS\033[0m", format_flops(op_flops_per_run).c_str(),
  691. format_flops(result.flops).c_str());
  692. } else {
  693. printf("%8zu kB/run - \033[1;34m%7.2f GB/s\033[0m", result.memory_kb, result.bandwidth_gb_s);
  694. }
  695. printf("\n");
  696. }
  697. void print_support_console(const test_result & result) {
  698. printf(" %s(%s): ", result.op_name.c_str(), result.op_params.c_str());
  699. fflush(stdout);
  700. if (result.supported) {
  701. printf("\033[1;32mSUPPORTED\033[0m\n");
  702. } else {
  703. printf("\033[1;31mNOT SUPPORTED\033[0m\n");
  704. }
  705. }
  706. };
  707. struct sql_printer : public printer {
  708. static std::string get_sql_field_type(const std::string & field) {
  709. switch (test_result::get_field_type(field)) {
  710. case test_result::STRING:
  711. return "TEXT";
  712. case test_result::BOOL:
  713. case test_result::INT:
  714. return "INTEGER";
  715. case test_result::FLOAT:
  716. return "REAL";
  717. default:
  718. GGML_ABORT("invalid field type");
  719. }
  720. }
  721. void print_header() override {
  722. std::vector<std::string> fields = test_result::get_fields();
  723. fprintf(fout, "CREATE TABLE IF NOT EXISTS test_backend_ops (\n");
  724. for (size_t i = 0; i < fields.size(); i++) {
  725. fprintf(fout, " %s %s%s\n", fields[i].c_str(), get_sql_field_type(fields[i]).c_str(),
  726. i < fields.size() - 1 ? "," : "");
  727. }
  728. fprintf(fout, ");\n\n");
  729. }
  730. void print_test_result(const test_result & result) override {
  731. fprintf(fout, "INSERT INTO test_backend_ops (");
  732. std::vector<std::string> fields = test_result::get_fields();
  733. for (size_t i = 0; i < fields.size(); i++) {
  734. fprintf(fout, "%s%s", fields[i].c_str(), i < fields.size() - 1 ? ", " : "");
  735. }
  736. fprintf(fout, ") VALUES (");
  737. std::vector<std::string> values = result.get_values();
  738. for (size_t i = 0; i < values.size(); i++) {
  739. fprintf(fout, "'%s'%s", values[i].c_str(), i < values.size() - 1 ? ", " : "");
  740. }
  741. fprintf(fout, ");\n");
  742. }
  743. };
  744. struct csv_printer : public printer {
  745. void print_header() override {
  746. std::vector<std::string> fields = test_result::get_fields();
  747. std::vector<std::string> fields_csv = get_fields_csv();
  748. for (size_t i = 0; i < fields.size(); i++) {
  749. if (std::find(std::begin(fields_csv), std::end(fields_csv), fields[i]) == std::end(fields_csv)) {
  750. continue;
  751. }
  752. printf("\"%s\"%s", fields[i].c_str(), i < fields.size() - 1 ? "," : "");
  753. }
  754. printf("\n");
  755. }
  756. void print_test_result(const test_result & result) override {
  757. std::vector<std::string> values = result.get_values();
  758. std::vector<std::string> fields = test_result::get_fields();
  759. std::vector<std::string> fields_csv = get_fields_csv();
  760. for (size_t i = 0; i < values.size(); i++) {
  761. if (std::find(std::begin(fields_csv), std::end(fields_csv), fields[i]) == std::end(fields_csv)) {
  762. continue;
  763. }
  764. // Escape quotes and wrap in quotes for CSV
  765. std::string escaped_value = values[i];
  766. size_t pos = 0;
  767. while ((pos = escaped_value.find("\"", pos)) != std::string::npos) {
  768. escaped_value.replace(pos, 1, "\"\"");
  769. pos += 2;
  770. }
  771. printf("\"%s\"%s", escaped_value.c_str(), i < values.size() - 1 ? "," : "");
  772. }
  773. printf("\n");
  774. }
  775. static std::vector<std::string> get_fields_csv() {
  776. return {
  777. "op_name",
  778. "op_params",
  779. "supported",
  780. "error_message",
  781. "test_mode",
  782. "backend_reg_name",
  783. "backend_name",
  784. };
  785. }
  786. };
  787. static std::unique_ptr<printer> create_printer(output_formats format) {
  788. switch (format) {
  789. case CONSOLE:
  790. return std::make_unique<console_printer>();
  791. case SQL:
  792. return std::make_unique<sql_printer>();
  793. case CSV:
  794. return std::make_unique<csv_printer>();
  795. }
  796. GGML_ABORT("invalid output format");
  797. }
  798. struct test_case {
  799. virtual ~test_case() {}
  800. virtual std::string op_desc(ggml_tensor * t) {
  801. return ggml_op_desc(t);
  802. }
  803. virtual std::string vars() {
  804. return "";
  805. }
  806. virtual ggml_tensor * build_graph(ggml_context * ctx) = 0;
  807. virtual double max_nmse_err() {
  808. return 1e-7;
  809. }
  810. virtual double max_maa_err() {
  811. return 1e-4;
  812. }
  813. virtual float grad_eps() {
  814. return 1e-1f;
  815. }
  816. // If false, estimate gradient with 2 points, neglects 3rd order derivative and higher.
  817. // If true, estimate gradient with 4 points, neglects 5th order derivative and higher.
  818. virtual bool grad_precise() {
  819. return false;
  820. }
  821. // Skip gradient checks if total number of gradients to be checked is larger than this (to speed up the tests).
  822. virtual int64_t grad_nmax() {
  823. return 10000;
  824. }
  825. // No effect if empty.
  826. // If not empty, skip all gradient checks where the numerical result does not match any of the values.
  827. // Needed for dealing with noncontinuous gradients (e.g. ReLU) where estimation using finite differences is unreliable.
  828. virtual std::vector<float> grad_expect() {
  829. return {};
  830. }
  831. virtual void initialize_tensors(ggml_context * ctx) {
  832. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) {
  833. init_tensor_uniform(t);
  834. }
  835. }
  836. virtual size_t op_size(ggml_tensor * t) {
  837. size_t size = ggml_nbytes(t);
  838. // add source tensors
  839. for (int i = 0; i < GGML_MAX_SRC; i++) {
  840. if (t->src[i] != NULL) {
  841. size += ggml_nbytes(t->src[i]);
  842. }
  843. }
  844. return size;
  845. }
  846. virtual uint64_t op_flops(ggml_tensor * t) {
  847. GGML_UNUSED(t);
  848. return 0;
  849. }
  850. virtual bool run_whole_graph() { return false; }
  851. ggml_cgraph * gf = nullptr;
  852. ggml_cgraph * gb = nullptr;
  853. static const int sentinel_size = 1024;
  854. test_mode mode;
  855. std::vector<ggml_tensor *> sentinels;
  856. void add_sentinel(ggml_context * ctx) {
  857. if (mode == MODE_PERF || mode == MODE_GRAD || mode == MODE_SUPPORT) {
  858. return;
  859. }
  860. ggml_tensor * sentinel = ::ggml_new_tensor_1d(ctx, GGML_TYPE_F32, sentinel_size);
  861. ggml_format_name(sentinel, "sent_%zu", sentinels.size());
  862. sentinels.push_back(sentinel);
  863. }
  864. // hijack ggml_new_tensor to add sentinels after each tensor to check for overflows in the backend
  865. ggml_tensor * ggml_new_tensor(ggml_context * ctx, ggml_type type, int n_dims, const int64_t * ne) {
  866. ggml_tensor * t = ::ggml_new_tensor(ctx, type, n_dims, ne);
  867. add_sentinel(ctx);
  868. return t;
  869. }
  870. ggml_tensor * ggml_new_tensor_1d(ggml_context * ctx, ggml_type type, int64_t ne0) {
  871. ggml_tensor * t = ::ggml_new_tensor_1d(ctx, type, ne0);
  872. add_sentinel(ctx);
  873. return t;
  874. }
  875. ggml_tensor * ggml_new_tensor_2d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1) {
  876. ggml_tensor * t = ::ggml_new_tensor_2d(ctx, type, ne0, ne1);
  877. add_sentinel(ctx);
  878. return t;
  879. }
  880. ggml_tensor * ggml_new_tensor_3d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1, int64_t ne2) {
  881. ggml_tensor * t = ::ggml_new_tensor_3d(ctx, type, ne0, ne1, ne2);
  882. add_sentinel(ctx);
  883. return t;
  884. }
  885. ggml_tensor * ggml_new_tensor_4d(ggml_context * ctx, ggml_type type, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
  886. ggml_tensor * t = ::ggml_new_tensor_4d(ctx, type, ne0, ne1, ne2, ne3);
  887. add_sentinel(ctx);
  888. return t;
  889. }
  890. bool eval(ggml_backend_t backend1, ggml_backend_t backend2, const char * op_name, printer * output_printer) {
  891. mode = MODE_TEST;
  892. ggml_init_params params = {
  893. /* .mem_size = */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  894. /* .mem_base = */ NULL,
  895. /* .no_alloc = */ true,
  896. };
  897. ggml_context * ctx = ggml_init(params);
  898. GGML_ASSERT(ctx);
  899. gf = ggml_new_graph(ctx);
  900. // pre-graph sentinel
  901. add_sentinel(ctx);
  902. ggml_tensor * out = build_graph(ctx);
  903. std::string current_op_name = op_desc(out);
  904. if (op_name != nullptr && current_op_name != op_name) {
  905. //printf(" %s: skipping\n", op_desc(out).c_str());
  906. ggml_free(ctx);
  907. return true;
  908. }
  909. // check if the backends support the ops
  910. bool supported = true;
  911. for (ggml_backend_t backend : {backend1, backend2}) {
  912. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  913. if (!ggml_backend_supports_op(backend, t)) {
  914. supported = false;
  915. break;
  916. }
  917. }
  918. }
  919. if (!supported) {
  920. // Create test result for unsupported operation
  921. test_result result(ggml_backend_name(backend1), current_op_name, vars(), "test",
  922. false, false, "not supported");
  923. if (output_printer) {
  924. output_printer->print_test_result(result);
  925. }
  926. ggml_free(ctx);
  927. return true;
  928. }
  929. // post-graph sentinel
  930. add_sentinel(ctx);
  931. // allocate
  932. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backend1);
  933. if (buf == NULL) {
  934. printf("failed to allocate tensors [%s] ", ggml_backend_name(backend1));
  935. ggml_free(ctx);
  936. return false;
  937. }
  938. // build graph
  939. ggml_build_forward_expand(gf, out);
  940. // add sentinels as graph nodes so that they are checked in the callback
  941. for (ggml_tensor * sentinel : sentinels) {
  942. ggml_graph_add_node(gf, sentinel);
  943. }
  944. // randomize tensors
  945. initialize_tensors(ctx);
  946. // compare
  947. struct callback_userdata {
  948. bool ok;
  949. double max_err;
  950. ggml_backend_t backend1;
  951. ggml_backend_t backend2;
  952. };
  953. callback_userdata ud {
  954. true,
  955. max_nmse_err(),
  956. backend1,
  957. backend2
  958. };
  959. auto callback = [](int index, ggml_tensor * t1, ggml_tensor * t2, void * user_data) -> bool {
  960. callback_userdata * ud = (callback_userdata *) user_data;
  961. const char * bn1 = ggml_backend_name(ud->backend1);
  962. const char * bn2 = ggml_backend_name(ud->backend2);
  963. if (t1->op == GGML_OP_NONE) {
  964. // sentinels must be unchanged
  965. std::vector<uint8_t> t1_data(ggml_nbytes(t1));
  966. std::vector<uint8_t> t2_data(ggml_nbytes(t2));
  967. ggml_backend_tensor_get(t1, t1_data.data(), 0, ggml_nbytes(t1));
  968. ggml_backend_tensor_get(t2, t2_data.data(), 0, ggml_nbytes(t2));
  969. if (memcmp(t1_data.data(), t2_data.data(), ggml_nbytes(t1)) != 0) {
  970. printf("sentinel mismatch: %s ", t1->name);
  971. ud->ok = false;
  972. return true;
  973. }
  974. }
  975. std::vector<float> f1 = tensor_to_float(t1);
  976. std::vector<float> f2 = tensor_to_float(t2);
  977. for (size_t i = 0; i < f1.size(); i++) {
  978. // check for nans
  979. if (std::isnan(f1[i]) || std::isnan(f2[i])) {
  980. printf("[%s] NaN at index %zu (%s=%f %s=%f) ", ggml_op_desc(t1), i, bn1, f1[i], bn2, f2[i]);
  981. ud->ok = false;
  982. return true;
  983. }
  984. // check for infs: both must be inf of the same sign, or both must be finite
  985. if (isinf_or_max(f1[i]) || isinf_or_max(f2[i])) {
  986. if (isinf_or_max(f1[i]) && isinf_or_max(f2[i])) {
  987. if (std::signbit(f1[i]) != std::signbit(f2[i])) {
  988. printf("[%s] inf sign mismatch: %s=%f %s=%f ", ggml_op_desc(t1), bn1, f1[i], bn2, f2[i]);
  989. ud->ok = false;
  990. return true;
  991. }
  992. } else {
  993. printf("[%s] inf mismatch: %s=%f %s=%f ", ggml_op_desc(t1), bn1, f1[i], bn2, f2[i]);
  994. ud->ok = false;
  995. return true;
  996. }
  997. }
  998. }
  999. double err = nmse(f1.data(), f2.data(), f1.size());
  1000. if (err > ud->max_err) {
  1001. printf("[%s] NMSE = %.9f > %.9f ", ggml_op_desc(t1), err, ud->max_err);
  1002. //for (int i = 0; i < (int) f1.size(); i++) {
  1003. // printf("%5d %9.6f %9.6f, diff = %9.6f\n", i, f1[i], f2[i], f1[i] - f2[i]);
  1004. //}
  1005. //printf("\n");
  1006. //exit(1);
  1007. ud->ok = false;
  1008. }
  1009. return true;
  1010. GGML_UNUSED(index);
  1011. };
  1012. const bool cmp_ok = ggml_backend_compare_graph_backend(backend1, backend2, gf, callback, &ud, run_whole_graph() ? out : nullptr);
  1013. ggml_backend_buffer_free(buf);
  1014. ggml_free(ctx);
  1015. // Create test result
  1016. bool test_passed = ud.ok && cmp_ok;
  1017. std::string error_msg = test_passed ? "" : (!cmp_ok ? "compare failed" : "test failed");
  1018. test_result result(ggml_backend_name(backend1), current_op_name, vars(), "test", supported, test_passed,
  1019. error_msg);
  1020. if (output_printer) {
  1021. output_printer->print_test_result(result);
  1022. }
  1023. return test_passed;
  1024. }
  1025. bool eval_perf(ggml_backend_t backend, const char * op_name, printer * output_printer) {
  1026. mode = MODE_PERF;
  1027. static const size_t graph_nodes = 8192;
  1028. ggml_init_params params = {
  1029. /* .mem_size = */ ggml_tensor_overhead()*128 + ggml_graph_overhead_custom(graph_nodes, false),
  1030. /* .mem_base = */ NULL,
  1031. /* .no_alloc = */ true,
  1032. };
  1033. ggml_context_ptr ctx(ggml_init(params)); // smart ptr
  1034. GGML_ASSERT(ctx);
  1035. ggml_tensor * out = build_graph(ctx.get());
  1036. std::string current_op_name = op_desc(out);
  1037. if (op_name != nullptr && current_op_name != op_name) {
  1038. //printf(" %s: skipping\n", op_desc(out).c_str());
  1039. return true;
  1040. }
  1041. if (!ggml_backend_supports_op(backend, out)) {
  1042. // Create test result for unsupported performance test
  1043. test_result result(ggml_backend_name(backend), current_op_name, vars(), "perf", false, false,
  1044. "not supported");
  1045. output_printer->print_test_result(result);
  1046. return true;
  1047. }
  1048. // allocate
  1049. ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors(ctx.get(), backend)); // smart ptr
  1050. if (buf == NULL) {
  1051. printf("failed to allocate tensors\n");
  1052. return false;
  1053. }
  1054. // randomize tensors
  1055. initialize_tensors(ctx.get());
  1056. // build graph
  1057. ggml_cgraph * gf = ggml_new_graph_custom(ctx.get(), graph_nodes, false);
  1058. ggml_build_forward_expand(gf, out);
  1059. // warmup run
  1060. ggml_status status = ggml_backend_graph_compute(backend, gf);
  1061. if (status != GGML_STATUS_SUCCESS) {
  1062. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1063. return false;
  1064. }
  1065. // determine number of runs
  1066. int n_runs;
  1067. bool is_cpu = ggml_backend_dev_type(ggml_backend_get_device(backend)) == GGML_BACKEND_DEVICE_TYPE_CPU;
  1068. if (op_flops(out) > 0) {
  1069. // based on flops
  1070. const uint64_t GFLOP = 1000 * 1000 * 1000;
  1071. const uint64_t target_flops_cpu = 8ULL * GFLOP;
  1072. const uint64_t target_flops_gpu = 100ULL * GFLOP;
  1073. uint64_t target_flops = is_cpu ? target_flops_cpu : target_flops_gpu;
  1074. n_runs = std::min<int>(ggml_graph_size(gf) - ggml_graph_n_nodes(gf), target_flops / op_flops(out)) + 1;
  1075. } else {
  1076. // based on memory size
  1077. const size_t GB = 1ULL << 30;
  1078. const size_t target_size_cpu = 8 * GB;
  1079. const size_t target_size_gpu = 32 * GB;
  1080. size_t target_size = is_cpu ? target_size_cpu : target_size_gpu;
  1081. n_runs = std::min<int>(ggml_graph_size(gf) - ggml_graph_n_nodes(gf), target_size / op_size(out)) + 1;
  1082. }
  1083. // duplicate the op
  1084. for (int i = 1; i < n_runs; i++) {
  1085. ggml_graph_add_node(gf, out);
  1086. }
  1087. // calculate memory
  1088. size_t mem = n_runs * op_size(out);
  1089. auto tensor_op_size = [](ggml_tensor * t) {
  1090. size_t size = ggml_nbytes(t);
  1091. // add source tensors
  1092. for (int i = 0; i < GGML_MAX_SRC; i++) {
  1093. if (t->src[i] != NULL) {
  1094. size += ggml_nbytes(t->src[i]);
  1095. }
  1096. }
  1097. return size;
  1098. };
  1099. for (int i = 0; i < ggml_graph_n_nodes(gf); ++i) {
  1100. if (ggml_is_view_op(ggml_graph_node(gf, i)->op) || ggml_graph_node(gf, i) == out) {
  1101. continue;
  1102. }
  1103. mem += tensor_op_size(ggml_graph_node(gf, i));
  1104. }
  1105. // run
  1106. int64_t total_time_us = 0;
  1107. int64_t total_mem = 0;
  1108. int total_runs = 0;
  1109. do {
  1110. int64_t start_time = ggml_time_us();
  1111. ggml_status status = ggml_backend_graph_compute(backend, gf);
  1112. if (status != GGML_STATUS_SUCCESS) {
  1113. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1114. return false;
  1115. }
  1116. int64_t end_time = ggml_time_us();
  1117. total_time_us += end_time - start_time;
  1118. total_mem += mem;
  1119. total_runs += n_runs;
  1120. } while (total_time_us < 1000*1000); // run for at least 1 second
  1121. // Create test result
  1122. double avg_time_us = (double) total_time_us / total_runs;
  1123. double calculated_flops = (op_flops(out) > 0) ? (op_flops(out) * total_runs) / (total_time_us / 1e6) : 0.0;
  1124. double calculated_bandwidth =
  1125. (op_flops(out) == 0) ? total_mem / (total_time_us / 1e6) / 1024.0 / 1024.0 / 1024.0 : 0.0;
  1126. size_t calculated_memory_kb = op_size(out) / 1024;
  1127. test_result result(ggml_backend_name(backend), current_op_name, vars(), "perf", true, true, "", avg_time_us,
  1128. calculated_flops, calculated_bandwidth, calculated_memory_kb, total_runs);
  1129. if (output_printer) {
  1130. output_printer->print_test_result(result);
  1131. }
  1132. return true;
  1133. }
  1134. bool eval_support(ggml_backend_t backend, const char * op_name, printer * output_printer) {
  1135. mode = MODE_SUPPORT;
  1136. static const size_t graph_nodes = 8192;
  1137. ggml_init_params params = {
  1138. /* .mem_size = */ ggml_tensor_overhead()*128 + ggml_graph_overhead_custom(graph_nodes, false),
  1139. /* .mem_base = */ NULL,
  1140. /* .no_alloc = */ true,
  1141. };
  1142. ggml_context_ptr ctx(ggml_init(params)); // smart ptr
  1143. GGML_ASSERT(ctx);
  1144. ggml_tensor * out = build_graph(ctx.get());
  1145. std::string current_op_name = op_desc(out);
  1146. if (op_name != nullptr && current_op_name != op_name) {
  1147. return true;
  1148. }
  1149. bool supported = ggml_backend_supports_op(backend, out);
  1150. std::string device_desc = ggml_backend_dev_description(ggml_backend_get_device(backend));
  1151. std::string backend_reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)));
  1152. test_result result(ggml_backend_name(backend), current_op_name, vars(), "support", supported, supported,
  1153. supported ? "yes" : "no", 0.0, 0.0, 0.0, 0, 0, device_desc, backend_reg_name);
  1154. output_printer->print_test_result(result);
  1155. return true;
  1156. }
  1157. bool eval_grad(ggml_backend_t backend, const char * op_name, printer * output_printer) {
  1158. mode = MODE_GRAD;
  1159. const std::vector<float> expect = grad_expect();
  1160. ggml_init_params params = {
  1161. /* .mem_size = */ ggml_tensor_overhead()*128 + 2*ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, true),
  1162. /* .mem_base = */ NULL,
  1163. /* .no_alloc = */ true,
  1164. };
  1165. ggml_context_ptr ctx(ggml_init(params)); // smart ptr
  1166. GGML_ASSERT(ctx);
  1167. gf = ggml_new_graph_custom(ctx.get(), GGML_DEFAULT_GRAPH_SIZE, true);
  1168. gb = ggml_new_graph_custom(ctx.get(), GGML_DEFAULT_GRAPH_SIZE, true);
  1169. ggml_tensor * out = build_graph(ctx.get());
  1170. if ((op_name != nullptr && op_desc(out) != op_name) || out->op == GGML_OP_OPT_STEP_ADAMW) {
  1171. return true;
  1172. }
  1173. if (out->type != GGML_TYPE_F32) {
  1174. output_printer->print_operation(test_operation_info(op_desc(out), vars(), ggml_backend_name(backend),
  1175. test_status_t::NOT_SUPPORTED,
  1176. out->name + std::string("->type != FP32")));
  1177. return true;
  1178. }
  1179. // Print operation info first
  1180. output_printer->print_operation(test_operation_info(op_desc(out), vars(), ggml_backend_name(backend)));
  1181. // check if the backend supports the ops
  1182. bool supported = true;
  1183. bool any_params = false;
  1184. std::string failure_reason;
  1185. for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != NULL; t = ggml_get_next_tensor(ctx.get(), t)) {
  1186. if (!ggml_backend_supports_op(backend, t)) {
  1187. supported = false;
  1188. failure_reason = ggml_backend_name(backend);
  1189. break;
  1190. }
  1191. if ((t->flags & GGML_TENSOR_FLAG_PARAM)) {
  1192. any_params = true;
  1193. if (t->type != GGML_TYPE_F32) {
  1194. supported = false;
  1195. failure_reason = std::string(t->name) + "->type != FP32";
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. if (!any_params) {
  1201. supported = false;
  1202. failure_reason = op_desc(out);
  1203. }
  1204. if (!supported) {
  1205. output_printer->print_operation(test_operation_info(op_desc(out), vars(), ggml_backend_name(backend),
  1206. test_status_t::NOT_SUPPORTED, failure_reason));
  1207. return true;
  1208. }
  1209. int64_t ngrads = 0;
  1210. for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != NULL; t = ggml_get_next_tensor(ctx.get(), t)) {
  1211. if (t->flags & GGML_TENSOR_FLAG_PARAM) {
  1212. ngrads += ggml_nelements(t);
  1213. }
  1214. }
  1215. if (ngrads > grad_nmax()) {
  1216. test_operation_info info(op_desc(out), vars(), ggml_backend_name(backend));
  1217. info.set_large_tensor_skip();
  1218. output_printer->print_operation(info);
  1219. return true;
  1220. }
  1221. if (!ggml_is_scalar(out)) {
  1222. out = ggml_sum(ctx.get(), out);
  1223. ggml_set_name(out, "sum_of_out");
  1224. }
  1225. ggml_set_loss(out);
  1226. ggml_build_forward_expand(gf, out);
  1227. ggml_graph_cpy(gf, gb);
  1228. ggml_build_backward_expand(ctx.get(), gb, nullptr);
  1229. if (expect.size() != 1 || expect[0] != 0.0f) {
  1230. GGML_ASSERT(ggml_graph_n_nodes(gb) > ggml_graph_n_nodes(gf));
  1231. for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != NULL; t = ggml_get_next_tensor(ctx.get(), t)) {
  1232. GGML_ASSERT(!(t->flags & GGML_TENSOR_FLAG_PARAM) || ggml_graph_get_grad(gb, t)->op != GGML_OP_NONE);
  1233. }
  1234. }
  1235. for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != NULL; t = ggml_get_next_tensor(ctx.get(), t)) {
  1236. if (!ggml_backend_supports_op(backend, t)) {
  1237. output_printer->print_operation(test_operation_info(op_desc(out), vars(), ggml_backend_name(backend),
  1238. test_status_t::NOT_SUPPORTED,
  1239. ggml_backend_name(backend)));
  1240. supported = false;
  1241. break;
  1242. }
  1243. if ((t->flags & GGML_TENSOR_FLAG_PARAM) && t->type != GGML_TYPE_F32) {
  1244. output_printer->print_operation(test_operation_info(op_desc(out), vars(), ggml_backend_name(backend),
  1245. test_status_t::NOT_SUPPORTED,
  1246. std::string(t->name) + "->type != FP32"));
  1247. supported = false;
  1248. break;
  1249. }
  1250. }
  1251. if (!supported) {
  1252. return true;
  1253. }
  1254. // allocate
  1255. ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors(ctx.get(), backend)); // smart ptr
  1256. if (buf == NULL) {
  1257. test_operation_info info(op_desc(out), vars(), ggml_backend_name(backend));
  1258. info.set_error("allocation", "");
  1259. output_printer->print_operation(info);
  1260. return false;
  1261. }
  1262. initialize_tensors(ctx.get()); // Randomizes all tensors (including gradients).
  1263. ggml_graph_reset(gb); // Sets gradients to 1 if loss, 0 otherwise.
  1264. ggml_status status = ggml_backend_graph_compute(backend, gf);
  1265. if (status != GGML_STATUS_SUCCESS) {
  1266. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1267. return false;
  1268. }
  1269. status = ggml_backend_graph_compute(backend, gb);
  1270. if (status != GGML_STATUS_SUCCESS) {
  1271. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1272. return false;
  1273. }
  1274. bool ok = true;
  1275. for (struct ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != nullptr; t = ggml_get_next_tensor(ctx.get(), t)) {
  1276. if (!(t->flags & GGML_TENSOR_FLAG_PARAM)) {
  1277. continue;
  1278. }
  1279. const char * bn = ggml_backend_name(backend);
  1280. const int64_t ne = ggml_nelements(t);
  1281. std::vector<float> ga;
  1282. struct ggml_tensor * grad = ggml_graph_get_grad(gb, t);
  1283. if (grad) {
  1284. ga = tensor_to_float(grad);
  1285. } else {
  1286. ga.resize(ne); // default value is 0.0f
  1287. }
  1288. for (int64_t i = 0; i < ne; ++i) { // gradient algebraic
  1289. // check for nans
  1290. if (!std::isfinite(ga[i])) {
  1291. test_operation_info info(op_desc(out), vars(), ggml_backend_name(backend));
  1292. info.set_gradient_info(i, bn, ga[i]);
  1293. output_printer->print_operation(info);
  1294. ok = false;
  1295. break;
  1296. }
  1297. }
  1298. if (!ok) {
  1299. break;
  1300. }
  1301. std::vector<float> gn(ne); // gradient numeric
  1302. GGML_ASSERT(ga.size() == gn.size());
  1303. std::vector<float> x0 = tensor_to_float(t); // original t data
  1304. GGML_ASSERT(ggml_is_scalar(out));
  1305. GGML_ASSERT(out->type == GGML_TYPE_F32);
  1306. const float eps = grad_eps();
  1307. for (int64_t i = 0; i < ne; ++i) {
  1308. const float xiu = x0[i] + 1.0f*eps; // x, index i, up
  1309. const float xiuh = x0[i] + 0.5f*eps; // x, index i, up half
  1310. const float xidh = x0[i] - 0.5f*eps; // x, index i, down half
  1311. const float xid = x0[i] - 1.0f*eps; // x, index i, down
  1312. float fu, fuh, fdh, fd; // output values for xiu, xiuh, xid, xidh
  1313. ggml_backend_tensor_set(t, &xiu, i*sizeof(float), sizeof(float));
  1314. status = ggml_backend_graph_compute(backend, gf);
  1315. if (status != GGML_STATUS_SUCCESS) {
  1316. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1317. return false;
  1318. }
  1319. ggml_backend_tensor_get(out, &fu, 0, ggml_nbytes(out));
  1320. ggml_backend_tensor_set(t, &xid, i*sizeof(float), sizeof(float));
  1321. status = ggml_backend_graph_compute(backend, gf);
  1322. if (status != GGML_STATUS_SUCCESS) {
  1323. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1324. return false;
  1325. }
  1326. ggml_backend_tensor_get(out, &fd, 0, ggml_nbytes(out));
  1327. if (grad_precise()) {
  1328. ggml_backend_tensor_set(t, &xiuh, i*sizeof(float), sizeof(float));
  1329. status = ggml_backend_graph_compute(backend, gf);
  1330. if (status != GGML_STATUS_SUCCESS) {
  1331. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1332. return false;
  1333. }
  1334. ggml_backend_tensor_get(out, &fuh, 0, ggml_nbytes(out));
  1335. ggml_backend_tensor_set(t, &xidh, i*sizeof(float), sizeof(float));
  1336. status = ggml_backend_graph_compute(backend, gf);
  1337. if (status != GGML_STATUS_SUCCESS) {
  1338. fprintf(stderr, "%s: ggml_backend_graph_compute failed. status=%s \n", __func__, ggml_status_to_string(status));
  1339. return false;
  1340. }
  1341. ggml_backend_tensor_get(out, &fdh, 0, ggml_nbytes(out));
  1342. gn[i] = (8.0*(double)fuh + (double)fd - (8.0*(double)fdh + (double)fu)) / (6.0*(double)eps);
  1343. } else {
  1344. gn[i] = (fu - fd) / (2.0f*eps);
  1345. }
  1346. ggml_backend_tensor_set(t, x0.data(), 0, ggml_nbytes(t));
  1347. }
  1348. const double err = mean_abs_asymm(gn.data(), ga.data(), gn.size(), expect);
  1349. if (err > max_maa_err()) {
  1350. test_operation_info info(op_desc(out), vars(), ggml_backend_name(backend));
  1351. info.set_maa_error(err, max_maa_err());
  1352. output_printer->print_operation(info);
  1353. ok = false;
  1354. break;
  1355. }
  1356. if (!ok) {
  1357. break;
  1358. }
  1359. }
  1360. // Create final test result
  1361. test_operation_info final_info(op_desc(out), vars(), ggml_backend_name(backend));
  1362. if (!ok) {
  1363. final_info.set_compare_failure();
  1364. }
  1365. final_info.status = ok ? test_status_t::OK : test_status_t::FAIL;
  1366. output_printer->print_operation(final_info);
  1367. if (ok) {
  1368. return true;
  1369. }
  1370. return false;
  1371. }
  1372. };
  1373. // ###################################
  1374. // ## Section 2: GGML Op Defintions ##
  1375. // ###################################
  1376. // The following is an example showing the bare minimum for creating a test for a GGML op.
  1377. // GGML_OP_EXAMPLE
  1378. struct test_example : public test_case {
  1379. // Always define these 2 or variants thereof:
  1380. const ggml_type type; // The type of the input tensors.
  1381. const std::array<int64_t, 4> ne; // The shape of the input tensors.
  1382. // For some ops it's necessary to define multiple types or shapes for the inputs.
  1383. // Or they may need additional parameters.
  1384. // Put all parameters needed to fully define the test into one of the VARS_TO_STR macros.
  1385. // In most cases these are just the properties of the struct that you defined above.
  1386. // This is needed for info prints.
  1387. std::string vars() override {
  1388. return VARS_TO_STR2(type, ne);
  1389. }
  1390. // Define a constructor for the struct.
  1391. // In most cases it will be sufficient to have the same arguments as the struct has properties
  1392. // and just use initializer lists.
  1393. test_example(ggml_type type = GGML_TYPE_F32,
  1394. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  1395. : type(type), ne(ne) {}
  1396. // Define how a simple GGML compute graph can be constructed for the new GGML op.
  1397. ggml_tensor * build_graph(ggml_context * ctx) override {
  1398. // Step 1: create input tensors that don't depend on any other tensors:
  1399. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1400. ggml_set_name(a, "a"); // Setting names is optional but it's useful for debugging.
  1401. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  1402. ggml_set_name(b, "b");
  1403. // Step 2: use the op that you want to test in the GGML compute graph.
  1404. ggml_tensor * out = ggml_add(ctx, a, b); // For this example we're just doing a simple addition.
  1405. ggml_set_name(out, "out");
  1406. // Step 3: return the output tensor.
  1407. return out;
  1408. }
  1409. // In order to also check the gradients for your op, add calls like ggml_set_param(a)
  1410. // immediately after you create the tensors.
  1411. // This is optional and only makes sense if a backward pass has actually been implemented for the new op.
  1412. };
  1413. // GGML_OP_UNARY
  1414. struct test_unary : public test_case {
  1415. const ggml_unary_op op;
  1416. const ggml_type type;
  1417. const std::array<int64_t, 4> ne_a;
  1418. int v; // view (1 : non-contiguous a)
  1419. std::string vars() override {
  1420. return VARS_TO_STR3(type, ne_a, v);
  1421. }
  1422. test_unary(ggml_unary_op op,
  1423. ggml_type type = GGML_TYPE_F32,
  1424. std::array<int64_t, 4> ne_a = {128, 2, 2, 2},
  1425. int v = 0)
  1426. : op(op), type(type), ne_a(ne_a), v(v) {}
  1427. ggml_tensor * build_graph(ggml_context * ctx) override {
  1428. const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG ||
  1429. op == GGML_UNARY_OP_STEP || op == GGML_UNARY_OP_RELU || op == GGML_UNARY_OP_SILU;
  1430. ggml_tensor * a;
  1431. if (v & 1) {
  1432. auto ne = ne_a; ne[0] *= 3;
  1433. a = ggml_new_tensor(ctx, type, 4, ne.data());
  1434. if (grad_supported) {
  1435. ggml_set_param(a);
  1436. }
  1437. ggml_set_name(a, "a");
  1438. 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);
  1439. ggml_set_name(a, "view_of_a");
  1440. } else {
  1441. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1442. if (grad_supported) {
  1443. ggml_set_param(a);
  1444. }
  1445. ggml_set_name(a, "a");
  1446. }
  1447. ggml_tensor * out = ggml_unary(ctx, a, op);
  1448. ggml_set_name(out, "out");
  1449. return out;
  1450. }
  1451. void initialize_tensors(ggml_context * ctx) override {
  1452. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1453. // test extended range of values to check for NaNs in GELU
  1454. init_tensor_uniform(t, -150.f, 150.f);
  1455. }
  1456. }
  1457. float grad_eps() override {
  1458. return 15.0f;
  1459. }
  1460. std::vector<float> grad_expect() override {
  1461. if (op == GGML_UNARY_OP_ABS) {
  1462. return {-1.0f, 1.0f};
  1463. }
  1464. if (op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_STEP) {
  1465. return {0.0f};
  1466. }
  1467. if (op == GGML_UNARY_OP_RELU) {
  1468. return {0.0f, 1.0f};
  1469. }
  1470. return {};
  1471. }
  1472. };
  1473. // GGML_OP_GLU
  1474. struct test_glu : public test_case {
  1475. const ggml_glu_op op;
  1476. const ggml_type type;
  1477. const std::array<int64_t, 4> ne_a;
  1478. int v; // view (1 : non-contiguous a)
  1479. bool swapped;
  1480. std::string vars() override {
  1481. return VARS_TO_STR4(type, ne_a, v, swapped);
  1482. }
  1483. test_glu(ggml_glu_op op,
  1484. ggml_type type = GGML_TYPE_F32,
  1485. std::array<int64_t, 4> ne_a = {128, 2, 2, 2},
  1486. int v = 0,
  1487. bool swapped = false)
  1488. : op(op), type(type), ne_a(ne_a), v(v), swapped(swapped) {}
  1489. ggml_tensor * build_graph(ggml_context * ctx) override {
  1490. ggml_tensor * a;
  1491. if (v & 1) {
  1492. auto ne = ne_a; ne[0] *= 3;
  1493. a = ggml_new_tensor(ctx, type, 4, ne.data());
  1494. ggml_set_name(a, "a");
  1495. 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);
  1496. ggml_set_name(a, "view_of_a");
  1497. } else {
  1498. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1499. ggml_set_name(a, "a");
  1500. }
  1501. ggml_tensor * out = ggml_glu(ctx, a, op, swapped);
  1502. ggml_set_name(out, "out");
  1503. return out;
  1504. }
  1505. void initialize_tensors(ggml_context * ctx) override {
  1506. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1507. // test extended range of values to check for NaNs in GELU
  1508. init_tensor_uniform(t, -150.f, 150.f);
  1509. }
  1510. }
  1511. };
  1512. struct test_glu_split : public test_case {
  1513. const ggml_glu_op op;
  1514. const ggml_type type;
  1515. const std::array<int64_t, 4> ne_a;
  1516. int v; // view (1 : non-contiguous a)
  1517. std::string vars() override {
  1518. return VARS_TO_STR3(type, ne_a, v) + ",split";
  1519. }
  1520. test_glu_split(ggml_glu_op op,
  1521. ggml_type type = GGML_TYPE_F32,
  1522. std::array<int64_t, 4> ne_a = {128, 2, 2, 2},
  1523. int v = 0)
  1524. : op(op), type(type), ne_a(ne_a), v(v) {}
  1525. ggml_tensor * build_graph(ggml_context * ctx) override {
  1526. ggml_tensor * a;
  1527. ggml_tensor * b;
  1528. if (v & 1) {
  1529. auto ne = ne_a; ne[0] *= 3;
  1530. a = ggml_new_tensor(ctx, type, 4, ne.data());
  1531. ggml_set_param(a);
  1532. ggml_set_name(a, "a");
  1533. 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);
  1534. ggml_set_name(a, "view_of_a");
  1535. b = ggml_new_tensor(ctx, type, 4, ne.data());
  1536. ggml_set_param(b);
  1537. ggml_set_name(b, "b");
  1538. b = ggml_view_4d(ctx, b, ne_a[0], ne_a[1], ne_a[2], ne_a[3], b->nb[1], b->nb[2], b->nb[3], 0);
  1539. ggml_set_name(a, "view_of_b");
  1540. } else {
  1541. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1542. ggml_set_param(a);
  1543. ggml_set_name(a, "a");
  1544. b = ggml_new_tensor(ctx, type, 4, ne_a.data());
  1545. ggml_set_param(b);
  1546. ggml_set_name(b, "b");
  1547. }
  1548. ggml_tensor * out = ggml_glu_split(ctx, a, b, op);
  1549. ggml_set_name(out, "out");
  1550. return out;
  1551. }
  1552. void initialize_tensors(ggml_context * ctx) override {
  1553. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1554. // test extended range of values to check for NaNs in GELU
  1555. init_tensor_uniform(t, -150.f, 150.f);
  1556. }
  1557. }
  1558. };
  1559. // GGML_OP_GET_ROWS
  1560. struct test_get_rows : public test_case {
  1561. const ggml_type type;
  1562. const int n; // cols
  1563. const int m; // rows
  1564. const int r; // rows to get
  1565. const int b; // batch size
  1566. const bool v; // view (non-contiguous src1)
  1567. std::string vars() override {
  1568. return VARS_TO_STR6(type, n, m, r, b, v);
  1569. }
  1570. test_get_rows(ggml_type type = GGML_TYPE_F32, int n = 10, int m = 5, int r = 3, int b = 1, bool v = false)
  1571. : type(type), n(n), m(m), r(r), b(b), v(v) {}
  1572. ggml_tensor * build_graph(ggml_context * ctx) override {
  1573. ggml_tensor * in = ggml_new_tensor_3d(ctx, type, n, m, b);
  1574. ggml_set_name(in, "in");
  1575. ggml_tensor * rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, r, b);
  1576. ggml_set_name(rows, "rows");
  1577. if (v) {
  1578. rows = ggml_view_2d(ctx, rows, r/2, b, rows->nb[1], 0);
  1579. ggml_set_name(rows, "view_of_rows");
  1580. }
  1581. const bool grad_supported = ggml_is_matrix(in) && ggml_is_vector(rows);
  1582. if (grad_supported) {
  1583. ggml_set_param(in);
  1584. // rows is a constant input -> no gradients
  1585. }
  1586. ggml_tensor * out = ggml_get_rows(ctx, in, rows);
  1587. ggml_set_name(out, "out");
  1588. return out;
  1589. }
  1590. void initialize_tensors(ggml_context * ctx) override {
  1591. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1592. if (t->type == GGML_TYPE_I32) {
  1593. if (ggml_is_view_op(t->op)) { continue; }
  1594. // rows
  1595. std::vector<int> data(r*b);
  1596. for (int i = 0; i < r*b; i++) {
  1597. data[i] = rand() % m;
  1598. }
  1599. ggml_backend_tensor_set(t, data.data(), 0, r * b * sizeof(int));
  1600. } else {
  1601. init_tensor_uniform(t);
  1602. }
  1603. }
  1604. }
  1605. };
  1606. // GGML_OP_GET_ROWS_BACK
  1607. struct test_get_rows_back : public test_case {
  1608. const ggml_type type;
  1609. const int n; // cols
  1610. const int m; // rows
  1611. const int r; // rows to get
  1612. const int b; // batch size
  1613. const bool v; // view (non-contiguous src1)
  1614. std::string vars() override {
  1615. return VARS_TO_STR6(type, n, m, r, b, v);
  1616. }
  1617. test_get_rows_back(ggml_type type = GGML_TYPE_F32, int n = 10, int m = 5, int r = 3, int b = 1, bool v = false)
  1618. : type(type), n(n), m(m), r(r), b(b), v(v) {}
  1619. ggml_tensor * build_graph(ggml_context * ctx) override {
  1620. ggml_tensor * in_forward = ggml_new_tensor_3d(ctx, type, n, m, b);
  1621. ggml_set_name(in_forward, "in_forward");
  1622. ggml_tensor * rows = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, r, b);
  1623. ggml_set_name(rows, "rows");
  1624. if (v) {
  1625. rows = ggml_view_2d(ctx, rows, r/2, b, rows->nb[1], 0);
  1626. ggml_set_name(rows, "view_of_rows");
  1627. }
  1628. ggml_tensor * grad = ggml_new_tensor_3d(ctx, type, n, r, b);
  1629. ggml_set_name(grad, "grad");
  1630. ggml_tensor * out = ggml_get_rows_back(ctx, grad, rows, in_forward);
  1631. ggml_set_name(out, "out");
  1632. return out;
  1633. }
  1634. void initialize_tensors(ggml_context * ctx) override {
  1635. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1636. if (t->type == GGML_TYPE_I32) {
  1637. if (ggml_is_view_op(t->op)) { continue; }
  1638. // rows
  1639. std::vector<int> data(r*b);
  1640. for (int i = 0; i < r*b; i++) {
  1641. data[i] = rand() % m;
  1642. }
  1643. ggml_backend_tensor_set(t, data.data(), 0, r * b * sizeof(int));
  1644. } else {
  1645. init_tensor_uniform(t);
  1646. }
  1647. }
  1648. }
  1649. };
  1650. // GGML_OP_SET_ROWS
  1651. struct test_set_rows : public test_case {
  1652. const ggml_type type;
  1653. const std::array<int64_t, 4> ne;
  1654. const std::array<int, 2> nr23; // broadcast only dims 2 and 3
  1655. const int r; // rows to set
  1656. const bool v; // view (non-contiguous src1)
  1657. std::string vars() override {
  1658. return VARS_TO_STR5(type, ne, nr23, r, v);
  1659. }
  1660. test_set_rows(ggml_type type,
  1661. std::array<int64_t, 4> ne,
  1662. std::array<int, 2> nr23,
  1663. int r, bool v = false)
  1664. : type(type), ne(ne), nr23(nr23), r(r), v(v) {}
  1665. ggml_tensor * build_graph(ggml_context * ctx) override {
  1666. ggml_tensor * dst = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2]*nr23[0], ne[3]*nr23[1]);
  1667. ggml_set_name(dst, "dst");
  1668. ggml_tensor * src = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne[0], r, ne[2]*nr23[0], ne[3]*nr23[1]);
  1669. ggml_set_name(src, "src");
  1670. ggml_tensor * row_idxs = ggml_new_tensor_3d(ctx, GGML_TYPE_I64, r, ne[2], ne[3]);
  1671. ggml_set_name(row_idxs, "row_idxs");
  1672. if (v) {
  1673. src = ggml_view_4d(ctx, src, ne[0], r/2, ne[2]*nr23[0], ne[3]*nr23[1], src->nb[1], src->nb[2], src->nb[3], 0);
  1674. row_idxs = ggml_view_3d(ctx, row_idxs, r/2, ne[2], ne[3], row_idxs->nb[1], row_idxs->nb[2], 0);
  1675. ggml_set_name(row_idxs, "view_of_rows");
  1676. }
  1677. ggml_tensor * out = ggml_set_rows(ctx, dst, src, row_idxs);
  1678. ggml_set_name(out, "out");
  1679. return out;
  1680. }
  1681. void initialize_tensors(ggml_context * ctx) override {
  1682. std::random_device rd;
  1683. std::default_random_engine rng(rd());
  1684. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1685. if (t->type == GGML_TYPE_I64) {
  1686. if (ggml_is_view_op(t->op)) {
  1687. continue;
  1688. }
  1689. for (int i2 = 0; i2 < t->ne[2]; i2++) {
  1690. for (int i1 = 0; i1 < t->ne[1]; i1++) {
  1691. // generate a shuffled subset of row indices
  1692. std::vector<int64_t> data(ne[1]);
  1693. for (int i = 0; i < ne[1]; i++) {
  1694. data[i] = i;
  1695. }
  1696. std::shuffle(data.begin(), data.end(), rng);
  1697. data.resize(t->ne[0]);
  1698. const size_t offs = i1*t->nb[1] + i2*t->nb[2];
  1699. ggml_backend_tensor_set(t, data.data(), offs, t->ne[0]*sizeof(int64_t));
  1700. }
  1701. }
  1702. } else {
  1703. init_tensor_uniform(t);
  1704. }
  1705. }
  1706. }
  1707. };
  1708. // GGML_OP_ARGMAX
  1709. struct test_argmax : public test_case {
  1710. const ggml_type type;
  1711. const std::array<int64_t, 4> ne;
  1712. std::string vars() override {
  1713. return VARS_TO_STR2(type, ne);
  1714. }
  1715. test_argmax(ggml_type type = GGML_TYPE_F32,
  1716. std::array<int64_t, 4> ne = {10, 100, 1, 1})
  1717. : type(type), ne(ne) {}
  1718. ggml_tensor * build_graph(ggml_context * ctx) override {
  1719. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1720. ggml_set_name(a, "a");
  1721. ggml_tensor * out = ggml_argmax(ctx, a);
  1722. ggml_set_name(out, "out");
  1723. return out;
  1724. }
  1725. void initialize_tensors(ggml_context * ctx) override {
  1726. std::random_device rd;
  1727. std::default_random_engine rng(rd());
  1728. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  1729. if (t->type == GGML_TYPE_F32) {
  1730. // initialize with unique values to avoid ties
  1731. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  1732. std::vector<float> data(t->ne[0]);
  1733. for (int i = 0; i < t->ne[0]; i++) {
  1734. data[i] = i;
  1735. }
  1736. std::shuffle(data.begin(), data.end(), rng);
  1737. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(float));
  1738. }
  1739. } else {
  1740. init_tensor_uniform(t);
  1741. }
  1742. }
  1743. }
  1744. double max_nmse_err() override {
  1745. return 0.0;
  1746. }
  1747. };
  1748. // GGML_OP_COUNT_EQUAL
  1749. struct test_count_equal : public test_case {
  1750. const ggml_type type;
  1751. const std::array<int64_t, 4> ne;
  1752. std::string vars() override {
  1753. return VARS_TO_STR2(type, ne);
  1754. }
  1755. test_count_equal(ggml_type type = GGML_TYPE_F32,
  1756. std::array<int64_t, 4> ne = {4, 500, 1, 1})
  1757. : type(type), ne(ne) {}
  1758. ggml_tensor * build_graph(ggml_context * ctx) override {
  1759. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  1760. ggml_set_name(a, "a");
  1761. ggml_tensor * a_argmax = ggml_argmax(ctx, a);
  1762. ggml_set_name(a_argmax, "a_argmax");
  1763. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  1764. ggml_set_name(b, "b");
  1765. ggml_tensor * b_argmax = ggml_argmax(ctx, b);
  1766. ggml_set_name(b_argmax, "b_argmax");
  1767. ggml_tensor * out = ggml_count_equal(ctx, a_argmax, b_argmax);
  1768. ggml_set_name(out, "out");
  1769. return out;
  1770. }
  1771. double max_nmse_err() override {
  1772. return 0.0;
  1773. }
  1774. };
  1775. // GGML_OP_REPEAT
  1776. struct test_repeat : public test_case {
  1777. const ggml_type type;
  1778. const std::array<int64_t, 4> ne;
  1779. const std::array<int, 4> nr;
  1780. std::string vars() override {
  1781. return VARS_TO_STR3(type, ne, nr);
  1782. }
  1783. size_t op_size(ggml_tensor * t) override {
  1784. return ggml_nbytes(t) * 2;
  1785. }
  1786. test_repeat(ggml_type type = GGML_TYPE_F32,
  1787. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  1788. std::array<int, 4> nr = {2, 2, 2, 2})
  1789. : type(type), ne(ne), nr(nr) {}
  1790. ggml_tensor * build_graph(ggml_context * ctx) override {
  1791. 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]);
  1792. ggml_set_name(target, "target");
  1793. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1794. ggml_set_param(src);
  1795. ggml_set_name(src, "src");
  1796. ggml_tensor * out = ggml_repeat(ctx, src, target);
  1797. ggml_set_name(out, "out");
  1798. return out;
  1799. }
  1800. };
  1801. // GGML_OP_REPEAT_BACK
  1802. struct test_repeat_back : public test_case {
  1803. const ggml_type type;
  1804. const std::array<int64_t, 4> ne;
  1805. const std::array<int, 4> nr;
  1806. const bool v; // whether src is a noncontiguous view
  1807. std::string vars() override {
  1808. return VARS_TO_STR4(type, ne, nr, v);
  1809. }
  1810. size_t op_size(ggml_tensor * t) override {
  1811. return ggml_nbytes(t) * 2;
  1812. }
  1813. test_repeat_back(ggml_type type = GGML_TYPE_F32,
  1814. std::array<int64_t, 4> ne = {8, 6, 4, 2},
  1815. std::array<int, 4> nr = {2, 2, 2, 2},
  1816. bool v = false)
  1817. : type(type), ne(ne), nr(nr), v(v) {}
  1818. ggml_tensor * build_graph(ggml_context * ctx) override {
  1819. ggml_tensor * src = ggml_new_tensor_4d(ctx, type, ne[0]*nr[0], ne[1]*nr[1], ne[2]*nr[2], ne[3]*nr[3]);
  1820. ggml_set_name(src, "src");
  1821. if (v) {
  1822. GGML_ASSERT(ne[0] % 2 == 0);
  1823. GGML_ASSERT(ne[1] % 2 == 0);
  1824. GGML_ASSERT(ne[2] % 2 == 0);
  1825. GGML_ASSERT(ne[3] % 2 == 0);
  1826. GGML_ASSERT(nr[0] % 2 == 0 || nr[0] == 1);
  1827. GGML_ASSERT(nr[1] % 2 == 0 || nr[1] == 1);
  1828. GGML_ASSERT(nr[2] % 2 == 0 || nr[2] == 1);
  1829. GGML_ASSERT(nr[3] % 2 == 0 || nr[3] == 1);
  1830. const int64_t ne00 = nr[0] == 1 ? src->ne[0] : src->ne[0] / 2;
  1831. const int64_t ne01 = nr[1] == 1 ? src->ne[1] : src->ne[1] / 2;
  1832. const int64_t ne02 = nr[2] == 1 ? src->ne[2] : src->ne[2] / 2;
  1833. const int64_t ne03 = nr[3] == 1 ? src->ne[3] : src->ne[3] / 2;
  1834. src = ggml_view_4d(ctx, src, ne00, ne01, ne02, ne03, src->nb[1], src->nb[2], src->nb[3], 0);
  1835. }
  1836. ggml_tensor * target = ggml_new_tensor(ctx, type, 4, ne.data());
  1837. ggml_set_name(target, "target");
  1838. ggml_tensor * out = ggml_repeat_back(ctx, src, target);
  1839. ggml_set_name(out, "out");
  1840. return out;
  1841. }
  1842. };
  1843. // GGML_OP_DUP
  1844. struct test_dup : public test_case {
  1845. const ggml_type type;
  1846. const std::array<int64_t, 4> ne;
  1847. const std::array<int64_t, 4> permute;
  1848. bool _use_permute;
  1849. std::string vars() override {
  1850. std::string v = VARS_TO_STR2(type, ne);
  1851. if (_use_permute) v += "," + VAR_TO_STR(permute);
  1852. return v;
  1853. }
  1854. test_dup(ggml_type type = GGML_TYPE_F32,
  1855. std::array<int64_t, 4> ne = {10, 10, 20, 1},
  1856. std::array<int64_t, 4> permute = {0, 0, 0, 0})
  1857. : type(type), ne(ne), permute(permute),
  1858. _use_permute(permute[0] + permute[1] + permute[2] + permute[3] > 0) {}
  1859. ggml_tensor * build_graph(ggml_context * ctx) override {
  1860. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1861. ggml_set_param(src);
  1862. ggml_set_name(src, "src");
  1863. if (_use_permute) {
  1864. src = ggml_permute(ctx, src, permute[0], permute[1], permute[2], permute[3]);
  1865. ggml_set_name(src, "src_permuted");
  1866. }
  1867. ggml_tensor * out = ggml_dup(ctx, src);
  1868. ggml_set_name(out, "out");
  1869. return out;
  1870. }
  1871. };
  1872. // GGML_OP_SET
  1873. struct test_set : public test_case {
  1874. const ggml_type type_src;
  1875. const ggml_type type_dst;
  1876. const std::array<int64_t, 4> ne;
  1877. const int dim;
  1878. std::string vars() override {
  1879. return VARS_TO_STR4(type_src, type_dst, ne, dim);
  1880. }
  1881. size_t op_size(ggml_tensor * t) override {
  1882. return ggml_nbytes(t) + ggml_nbytes(t->src[0]);
  1883. }
  1884. test_set(ggml_type type_src = GGML_TYPE_F32, ggml_type type_dst = GGML_TYPE_F32,
  1885. std::array<int64_t, 4> ne = {6, 5, 4, 3}, int dim = 1)
  1886. : type_src(type_src), type_dst(type_dst), ne(ne), dim(dim) {}
  1887. ggml_tensor * build_graph(ggml_context * ctx) override {
  1888. ggml_tensor * src = ggml_new_tensor(ctx, type_src, 4, ne.data());
  1889. ggml_set_param(src);
  1890. ggml_set_name(src, "src");
  1891. auto ne_dst = ne;
  1892. for (int i = 0; i < dim; ++i) {
  1893. ne_dst[i] *= 2;
  1894. }
  1895. ggml_tensor* dst = ggml_new_tensor(ctx, type_dst, 4, ne_dst.data());
  1896. ggml_set_param(dst);
  1897. ggml_set_name(dst, "dst");
  1898. size_t offset = 0;
  1899. for (int i = 0; i < dim; ++i) {
  1900. offset += ((ne_dst[i] - ne[i])/2)*dst->nb[i];
  1901. }
  1902. ggml_tensor * out = ggml_set(ctx, dst, src,
  1903. // The backward pass requires setting a contiguous region:
  1904. src->nb[1], src->nb[2], src->nb[3], offset);
  1905. ggml_set_name(out, "out");
  1906. return out;
  1907. }
  1908. };
  1909. // GGML_OP_CPY
  1910. struct test_cpy : public test_case {
  1911. const ggml_type type_src;
  1912. const ggml_type type_dst;
  1913. const std::array<int64_t, 4> ne;
  1914. const std::array<int64_t, 4> permute_src;
  1915. const std::array<int64_t, 4> permute_dst;
  1916. bool _src_use_permute;
  1917. bool _dst_use_permute;
  1918. std::string vars() override {
  1919. return VARS_TO_STR5(type_src, type_dst, ne, permute_src, permute_dst);
  1920. }
  1921. double max_nmse_err() override {
  1922. return 1e-6;
  1923. }
  1924. size_t op_size(ggml_tensor * t) override {
  1925. return ggml_nbytes(t) + ggml_nbytes(t->src[0]);
  1926. }
  1927. test_cpy(ggml_type type_src = GGML_TYPE_F32, ggml_type type_dst = GGML_TYPE_F32,
  1928. std::array<int64_t, 4> ne = {10, 10, 10, 1},
  1929. std::array<int64_t, 4> permute_src = {0, 0, 0, 0},
  1930. std::array<int64_t, 4> permute_dst = {0, 0, 0, 0})
  1931. : type_src(type_src), type_dst(type_dst), ne(ne), permute_src(permute_src), permute_dst(permute_dst),
  1932. _src_use_permute(permute_src[0] + permute_src[1] + permute_src[2] + permute_src[3] > 0),
  1933. _dst_use_permute(permute_dst[0] + permute_dst[1] + permute_dst[2] + permute_dst[3] > 0) {}
  1934. ggml_tensor * build_graph(ggml_context * ctx) override {
  1935. ggml_tensor * src = ggml_new_tensor(ctx, type_src, 4, ne.data());
  1936. ggml_set_param(src);
  1937. ggml_set_name(src, "src");
  1938. if (_src_use_permute) {
  1939. src = ggml_permute(ctx, src, permute_src[0], permute_src[1], permute_src[2], permute_src[3]);
  1940. ggml_set_name(src, "src_permuted");
  1941. }
  1942. ggml_tensor * dst = ggml_new_tensor(ctx, type_dst, 4, src->ne);
  1943. ggml_set_name(dst, "dst");
  1944. if (_dst_use_permute) {
  1945. dst = ggml_permute(ctx, dst, permute_dst[0], permute_dst[1], permute_dst[2], permute_dst[3]);
  1946. ggml_set_name(dst, "dst_permuted");
  1947. }
  1948. ggml_tensor * out = ggml_cpy(ctx, src, dst);
  1949. ggml_set_name(out, "out");
  1950. return out;
  1951. }
  1952. };
  1953. // GGML_OP_CONT
  1954. struct test_cont : public test_case {
  1955. const ggml_type type;
  1956. const std::array<int64_t, 4> ne;
  1957. std::string vars() override {
  1958. return VARS_TO_STR2(type, ne);
  1959. }
  1960. test_cont(ggml_type type = GGML_TYPE_F32,
  1961. std::array<int64_t, 4> ne = {10, 10, 10, 1})
  1962. : type(type), ne(ne) {}
  1963. ggml_tensor * build_graph(ggml_context * ctx) override {
  1964. ggml_tensor * src = ggml_new_tensor(ctx, type, 4, ne.data());
  1965. ggml_set_param(src);
  1966. ggml_set_name(src, "src");
  1967. src = ggml_transpose(ctx, src);
  1968. ggml_set_name(src, "src_transposed");
  1969. ggml_tensor * out = ggml_cont(ctx, src);
  1970. ggml_set_name(out, "out");
  1971. return out;
  1972. }
  1973. };
  1974. // GGML_OP_ADD
  1975. // GGML_OP_SUB
  1976. // GGML_OP_MUL
  1977. // GGML_OP_DIV
  1978. struct test_bin_bcast : public test_case {
  1979. using op_t = ggml_tensor * (*) (ggml_context *, ggml_tensor *, ggml_tensor *);
  1980. op_t op;
  1981. const ggml_type type;
  1982. const std::array<int64_t, 4> ne;
  1983. const std::array<int, 4> nr;
  1984. int nf; // number of fused ops, nf == 1 -> single op (no fusion)
  1985. bool run_whole_graph() override { return true; }
  1986. std::string vars() override {
  1987. return VARS_TO_STR4(type, ne, nr, nf);
  1988. }
  1989. size_t op_size(ggml_tensor * t) override {
  1990. return ggml_nbytes(t) * 3;
  1991. }
  1992. test_bin_bcast(op_t op, ggml_type type = GGML_TYPE_F32,
  1993. std::array<int64_t, 4> ne = {10, 10, 1, 1},
  1994. std::array<int, 4> nr = {1, 2, 1, 1},
  1995. int nf = 1)
  1996. : op(op), type(type), ne(ne), nr(nr), nf(nf) {}
  1997. ggml_tensor * build_graph(ggml_context * ctx) override {
  1998. GGML_ASSERT(nf <= 8);
  1999. 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]);
  2000. ggml_set_name(a, "a");
  2001. ggml_tensor * b[8];
  2002. for (int i = 0; i < nf; ++i) {
  2003. b[i] = ggml_new_tensor(ctx, type, 4, ne.data());
  2004. ggml_set_name(b[i], (std::string("b") + std::to_string(i)).c_str());
  2005. }
  2006. // The backward pass supports broadcasting only for GGML_ADD:
  2007. const bool grad_supported = op == ggml_add && ggml_are_same_shape(a, b[0]) && nf == 1;
  2008. if (grad_supported) {
  2009. ggml_set_param(a);
  2010. ggml_set_param(b[0]);
  2011. }
  2012. ggml_tensor * out = a;
  2013. for (int i = 0; i < nf; ++i) {
  2014. out = op(ctx, out, b[i]);
  2015. }
  2016. ggml_set_name(out, "out");
  2017. return out;
  2018. }
  2019. void initialize_tensors(ggml_context * ctx) override {
  2020. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2021. if (op == ggml_mul || op == ggml_div) {
  2022. // MUL and DIV have numerical issues around zero:
  2023. init_tensor_uniform(t, 0.9f, 1.1f);
  2024. } else {
  2025. init_tensor_uniform(t);
  2026. }
  2027. }
  2028. }
  2029. float grad_eps() override {
  2030. return 0.1f * (op == ggml_mul ? ne[0]*ne[1]*ne[2]*ne[3] : 1);
  2031. }
  2032. bool grad_precise() override {
  2033. return op == ggml_div;
  2034. }
  2035. double max_maa_err() override {
  2036. return op == ggml_add ? 1e-4 : 1e-3;
  2037. }
  2038. };
  2039. // GGML_OP_ADD1
  2040. struct test_add1 : public test_case {
  2041. const ggml_type type;
  2042. const std::array<int64_t, 4> ne;
  2043. std::string vars() override {
  2044. return VARS_TO_STR2(type, ne);
  2045. }
  2046. test_add1(ggml_type type = GGML_TYPE_F32,
  2047. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2048. : type(type), ne(ne) {}
  2049. ggml_tensor * build_graph(ggml_context * ctx) override {
  2050. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2051. ggml_set_param(a);
  2052. ggml_set_name(a, "a");
  2053. ggml_tensor * b = ggml_new_tensor_1d(ctx, type, 1);
  2054. // ggml_set_param(b); // TODO: implement
  2055. ggml_set_name(b, "b");
  2056. ggml_tensor * out = ggml_add1(ctx, a, b);
  2057. ggml_set_name(out, "out");
  2058. return out;
  2059. }
  2060. float grad_eps() override {
  2061. return 0.1f * ne[0]*ne[1]*ne[2]*ne[3];
  2062. }
  2063. };
  2064. // GGML_OP_SCALE
  2065. struct test_scale : public test_case {
  2066. const ggml_type type;
  2067. const std::array<int64_t, 4> ne;
  2068. float scale;
  2069. float bias;
  2070. std::string vars() override {
  2071. return VARS_TO_STR4(type, ne, scale, bias);
  2072. }
  2073. test_scale(ggml_type type = GGML_TYPE_F32,
  2074. std::array<int64_t, 4> ne = {10, 10, 10, 10},
  2075. float scale = 2.0f,
  2076. float bias = 0.0f)
  2077. : type(type), ne(ne), scale(scale), bias(bias) {}
  2078. ggml_tensor * build_graph(ggml_context * ctx) override {
  2079. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2080. ggml_set_param(a);
  2081. ggml_set_name(a, "a");
  2082. ggml_tensor * out = ggml_scale_bias(ctx, a, scale, bias);
  2083. ggml_set_name(out, "out");
  2084. return out;
  2085. }
  2086. };
  2087. // GGML_OP_SILU_BACK
  2088. struct test_silu_back : public test_case {
  2089. const ggml_type type;
  2090. const std::array<int64_t, 4> ne;
  2091. float eps;
  2092. std::string vars() override {
  2093. return VARS_TO_STR3(type, ne, eps);
  2094. }
  2095. test_silu_back(ggml_type type = GGML_TYPE_F32,
  2096. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  2097. float eps = 1e-6f)
  2098. : type(type), ne(ne), eps(eps) {}
  2099. ggml_tensor * build_graph(ggml_context * ctx) override {
  2100. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2101. ggml_set_name(a, "a");
  2102. ggml_tensor * grad = ggml_new_tensor(ctx, type, 4, ne.data());
  2103. ggml_set_name(grad, "grad");
  2104. ggml_tensor * out = ggml_silu_back(ctx, a, grad);
  2105. ggml_set_name(out, "out");
  2106. return out;
  2107. }
  2108. bool grad_precise() override {
  2109. return true;
  2110. }
  2111. };
  2112. // GGML_OP_NORM
  2113. struct test_norm : public test_case {
  2114. const ggml_type type;
  2115. const std::array<int64_t, 4> ne;
  2116. const bool v; // whether a is a non-contiguous view
  2117. const float eps;
  2118. std::string vars() override {
  2119. return VARS_TO_STR4(type, ne, v, eps);
  2120. }
  2121. test_norm(ggml_type type = GGML_TYPE_F32,
  2122. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  2123. bool v = false,
  2124. float eps = 1e-6f)
  2125. : type(type), ne(ne), v(v), eps(eps) {}
  2126. ggml_tensor * build_graph(ggml_context * ctx) override {
  2127. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2128. ggml_set_name(a, "a");
  2129. if (v) {
  2130. a = ggml_view_4d(ctx, a, a->ne[0]/2, a->ne[1]/2, a->ne[2]/2, a->ne[3]/2, a->nb[1], a->nb[2], a->nb[3], 0);
  2131. ggml_set_name(a, "view of a");
  2132. }
  2133. ggml_tensor * out = ggml_norm(ctx, a, eps);
  2134. ggml_set_name(out, "out");
  2135. return out;
  2136. }
  2137. };
  2138. // GGML_OP_RMS_NORM
  2139. struct test_rms_norm : public test_case {
  2140. const ggml_type type;
  2141. const std::array<int64_t, 4> ne;
  2142. const bool v; // whether a is a non-contiguous view
  2143. const float eps;
  2144. std::string vars() override {
  2145. return VARS_TO_STR4(type, ne, v, eps);
  2146. }
  2147. test_rms_norm(ggml_type type = GGML_TYPE_F32,
  2148. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  2149. bool v = false,
  2150. float eps = 1e-6f)
  2151. : type(type), ne(ne), v(v), eps(eps) {}
  2152. ggml_tensor * build_graph(ggml_context * ctx) override {
  2153. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2154. ggml_set_param(a);
  2155. ggml_set_name(a, "a");
  2156. if (v) {
  2157. a = ggml_view_4d(ctx, a, a->ne[0]/2, a->ne[1]/2, a->ne[2]/2, a->ne[3]/2, a->nb[1], a->nb[2], a->nb[3], 0);
  2158. ggml_set_name(a, "view of a");
  2159. }
  2160. ggml_tensor * out = ggml_rms_norm(ctx, a, eps);
  2161. ggml_set_name(out, "out");
  2162. return out;
  2163. }
  2164. void initialize_tensors(ggml_context * ctx) override {
  2165. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2166. init_tensor_uniform(t, -10.f, 10.f);
  2167. }
  2168. }
  2169. float grad_eps() override {
  2170. return 1.0f;
  2171. }
  2172. bool grad_precise() override {
  2173. return true;
  2174. }
  2175. };
  2176. // GGML_OP_RMS_NORM_BACK
  2177. struct test_rms_norm_back : public test_case {
  2178. const ggml_type type;
  2179. const std::array<int64_t, 4> ne;
  2180. const float eps;
  2181. std::string vars() override {
  2182. return VARS_TO_STR3(type, ne, eps);
  2183. }
  2184. test_rms_norm_back(ggml_type type = GGML_TYPE_F32,
  2185. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  2186. float eps = 1e-6f)
  2187. : type(type), ne(ne), eps(eps) {}
  2188. ggml_tensor * build_graph(ggml_context * ctx) override {
  2189. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2190. ggml_set_name(a, "a");
  2191. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  2192. ggml_set_name(b, "b");
  2193. ggml_tensor * out = ggml_rms_norm_back(ctx, a, b, eps);
  2194. ggml_set_name(out, "out");
  2195. return out;
  2196. }
  2197. void initialize_tensors(ggml_context * ctx) override {
  2198. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2199. init_tensor_uniform(t, -10.f, 10.f);
  2200. }
  2201. }
  2202. };
  2203. // GGML_OP_RMS_NORM + GGML_OP_MUL + GGML_OP_ADD
  2204. struct test_rms_norm_mul_add : public test_case {
  2205. const ggml_type type;
  2206. const std::array<int64_t, 4> ne;
  2207. const float eps;
  2208. const bool broadcast;
  2209. std::string op_desc(ggml_tensor * t) override {
  2210. GGML_UNUSED(t);
  2211. return "RMS_NORM_MUL_ADD";
  2212. }
  2213. bool run_whole_graph() override { return true; }
  2214. std::string vars() override {
  2215. return VARS_TO_STR4(type, ne, eps, broadcast);
  2216. }
  2217. test_rms_norm_mul_add(ggml_type type = GGML_TYPE_F32,
  2218. std::array<int64_t, 4> ne = {64, 5, 4, 3},
  2219. float eps = 1e-6f, bool broadcast = false)
  2220. : type(type), ne(ne), eps(eps), broadcast(broadcast) {}
  2221. ggml_tensor * build_graph(ggml_context * ctx) override {
  2222. std::array<int64_t, 4> broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4};
  2223. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, broadcast ? broadcast_dims.data() : ne.data());
  2224. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  2225. ggml_tensor * c = ggml_new_tensor(ctx, type, 4, ne.data());
  2226. ggml_set_param(a);
  2227. ggml_set_name(a, "a");
  2228. ggml_set_param(b);
  2229. ggml_set_name(b, "b");
  2230. ggml_set_param(c);
  2231. ggml_set_name(c, "c");
  2232. // Use a, b and c early, so we don't end up with an OP_NONE between rms_norm and mul
  2233. a = ggml_add(ctx, ggml_add(ctx, a, b), c);
  2234. ggml_tensor * out = ggml_add(ctx, ggml_mul(ctx, ggml_rms_norm(ctx, a, eps), b), c);
  2235. ggml_set_name(out, "out");
  2236. return out;
  2237. }
  2238. void initialize_tensors(ggml_context * ctx) override {
  2239. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2240. init_tensor_uniform(t, -10.f, 10.f);
  2241. }
  2242. }
  2243. float grad_eps() override {
  2244. return 1.0f;
  2245. }
  2246. bool grad_precise() override {
  2247. return true;
  2248. }
  2249. };
  2250. // GGML_OP_SSM_CONV
  2251. struct test_ssm_conv : public test_case {
  2252. const ggml_type type;
  2253. const std::array<int64_t, 4> ne_a;
  2254. const std::array<int64_t, 4> ne_b;
  2255. std::string vars() override {
  2256. return VARS_TO_STR3(type, ne_a, ne_b);
  2257. }
  2258. test_ssm_conv(ggml_type type = GGML_TYPE_F32,
  2259. std::array<int64_t, 4> ne_a = {10, 10, 10, 1},
  2260. std::array<int64_t, 4> ne_b = {3, 3, 1, 1})
  2261. : type(type), ne_a(ne_a), ne_b(ne_b) {}
  2262. ggml_tensor * build_graph(ggml_context * ctx) override {
  2263. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2264. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  2265. ggml_tensor * out = ggml_ssm_conv(ctx, a, b);
  2266. return out;
  2267. }
  2268. };
  2269. // GGML_OP_SSM_SCAN
  2270. struct test_ssm_scan : public test_case {
  2271. const ggml_type type;
  2272. const int64_t d_state;
  2273. const int64_t head_dim;
  2274. const int64_t n_head;
  2275. const int64_t n_group;
  2276. const int64_t n_seq_tokens;
  2277. const int64_t n_seqs;
  2278. std::string vars() override {
  2279. return VARS_TO_STR7(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs);
  2280. }
  2281. test_ssm_scan(ggml_type type = GGML_TYPE_F32,
  2282. int64_t d_state = 32,
  2283. int64_t head_dim = 1, // non-zero for Mamba-2
  2284. int64_t n_head = 32,
  2285. int64_t n_group = 1,
  2286. int64_t n_seq_tokens = 32,
  2287. int64_t n_seqs = 32)
  2288. : type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  2289. ggml_tensor * build_graph(ggml_context * ctx) override {
  2290. ggml_tensor * s = ggml_new_tensor_4d(ctx, type, d_state, head_dim, n_head, n_seqs);
  2291. ggml_tensor * x = ggml_new_tensor_4d(ctx, type, head_dim, n_head, n_seq_tokens, n_seqs);
  2292. ggml_tensor * dt = ggml_new_tensor_3d(ctx, type, n_head, n_seq_tokens, n_seqs);
  2293. ggml_tensor * A = ggml_new_tensor_2d(ctx, type, (head_dim > 1) ? 1 : d_state, n_head);
  2294. ggml_tensor * B = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
  2295. ggml_tensor * C = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
  2296. ggml_tensor * ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
  2297. ggml_tensor * out = ggml_ssm_scan(ctx, s, x, dt, A, B, C, ids);
  2298. return out;
  2299. }
  2300. // similar to test_mul_mat_id
  2301. void initialize_tensors(ggml_context * ctx) override {
  2302. std::random_device rd;
  2303. std::default_random_engine rng(rd());
  2304. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2305. if (t->type == GGML_TYPE_I32) {
  2306. if (ggml_is_view_op(t->op)) { continue; }
  2307. // ids
  2308. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  2309. std::vector<int32_t> data(t->ne[0]);
  2310. for (int i = 0; i < t->ne[0]; i++) {
  2311. data[i] = i;
  2312. }
  2313. std::shuffle(data.begin(), data.end(), rng);
  2314. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
  2315. }
  2316. } else {
  2317. init_tensor_uniform(t);
  2318. }
  2319. }
  2320. }
  2321. };
  2322. // GGML_OP_RWKV_WKV6
  2323. struct test_rwkv_wkv6 : public test_case {
  2324. const ggml_type type;
  2325. const int64_t head_count;
  2326. const int64_t head_size;
  2327. const int64_t n_seq_tokens;
  2328. const int64_t n_seqs;
  2329. std::string vars() override {
  2330. return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
  2331. }
  2332. test_rwkv_wkv6(ggml_type type = GGML_TYPE_F32,
  2333. int64_t head_count = 32, int64_t head_size = 64, int64_t n_seq_tokens = 32, int64_t n_seqs = 32)
  2334. : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  2335. ggml_tensor * build_graph(ggml_context * ctx) override {
  2336. const int64_t n_tokens = n_seq_tokens * n_seqs;
  2337. ggml_tensor * r = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2338. ggml_tensor * k = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2339. ggml_tensor * v = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2340. ggml_tensor * tf = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size, head_count }.data());
  2341. ggml_tensor * td = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2342. ggml_tensor * s = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size * head_size * head_count, n_seqs }.data());
  2343. ggml_tensor * out = ggml_rwkv_wkv6(ctx, k, v, r, tf, td, s);
  2344. return out;
  2345. }
  2346. };
  2347. // GGML_OP_GATED_LINEAR_ATTN
  2348. struct test_gla : public test_case {
  2349. const ggml_type type;
  2350. const int64_t head_count;
  2351. const int64_t head_size;
  2352. const int64_t n_seq_tokens;
  2353. const int64_t n_seqs;
  2354. std::string vars() override {
  2355. return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
  2356. }
  2357. test_gla(ggml_type type = GGML_TYPE_F32,
  2358. int64_t head_count = 32, int64_t head_size = 64, int64_t n_seq_tokens = 32, int64_t n_seqs = 32)
  2359. : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  2360. ggml_tensor * build_graph(ggml_context * ctx) override {
  2361. const int64_t n_tokens = n_seq_tokens * n_seqs;
  2362. ggml_tensor * q = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2363. ggml_tensor * k = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2364. ggml_tensor * v = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2365. ggml_tensor * g = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2366. ggml_tensor * s = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size * head_size * head_count, n_seqs }.data());
  2367. ggml_tensor * out = ggml_gated_linear_attn(ctx, k, v, q, g, s, pow(head_size, -0.5));
  2368. return out;
  2369. }
  2370. };
  2371. // GGML_OP_RWKV_WKV7
  2372. struct test_rwkv_wkv7 : public test_case {
  2373. const ggml_type type;
  2374. const int64_t head_count;
  2375. const int64_t head_size;
  2376. const int64_t n_seq_tokens;
  2377. const int64_t n_seqs;
  2378. std::string vars() override {
  2379. return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs);
  2380. }
  2381. test_rwkv_wkv7(ggml_type type = GGML_TYPE_F32,
  2382. int64_t head_count = 32, int64_t head_size = 64, int64_t n_seq_tokens = 32, int64_t n_seqs = 32)
  2383. : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {}
  2384. ggml_tensor * build_graph(ggml_context * ctx) override {
  2385. const int64_t n_tokens = n_seq_tokens * n_seqs;
  2386. ggml_tensor * r = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2387. ggml_tensor * w = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2388. ggml_tensor * k = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2389. ggml_tensor * v = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2390. ggml_tensor * a = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2391. ggml_tensor * b = ggml_new_tensor(ctx, type, 3, std::vector<int64_t>{ head_size, head_count, n_tokens }.data());
  2392. // Outputs may become NaN with long seqlen without these normalization
  2393. a = ggml_l2_norm(ctx, a, 1e-7F);
  2394. b = ggml_l2_norm(ctx, b, 1e-7F);
  2395. ggml_tensor * s = ggml_new_tensor(ctx, type, 2, std::vector<int64_t>{ head_size * head_size * head_count, n_seqs }.data());
  2396. ggml_tensor * out = ggml_rwkv_wkv7(ctx, r, w, k, v, a, b, s);
  2397. return out;
  2398. }
  2399. };
  2400. // GGML_OP_MUL_MAT
  2401. struct test_mul_mat : public test_case {
  2402. const ggml_type type_a;
  2403. const ggml_type type_b;
  2404. const int64_t m;
  2405. const int64_t n;
  2406. const int64_t k;
  2407. const std::array<int64_t, 2> bs; // dims 3 and 4
  2408. const std::array<int64_t, 2> nr; // repeat in dims 3 and 4
  2409. const std::array<int64_t, 4> per; // permutation of dimensions
  2410. const bool v; // whether a and b are non-contiguous views
  2411. std::string vars() override {
  2412. return VARS_TO_STR9(type_a, type_b, m, n, k, bs, nr, per, v);
  2413. }
  2414. double max_nmse_err() override {
  2415. return 5e-4;
  2416. }
  2417. int64_t grad_nmax() override {
  2418. return 20000;
  2419. }
  2420. uint64_t op_flops(ggml_tensor * t) override {
  2421. GGML_UNUSED(t);
  2422. return 2 * m * n * k * bs[0] * nr[0] * bs[1] * nr[1];
  2423. }
  2424. test_mul_mat(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  2425. int64_t m = 32, int64_t n = 32, int64_t k = 32,
  2426. std::array<int64_t, 2> bs = {10, 10},
  2427. std::array<int64_t, 2> nr = {2, 2},
  2428. std::array<int64_t, 4> per = {0, 1, 2, 3},
  2429. bool v = false)
  2430. : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), nr(nr), per(per), v(v) {}
  2431. ggml_tensor * build_graph(ggml_context * ctx) override {
  2432. // C^T = A * B^T: (k, m) * (k, n) => (m, n)
  2433. ggml_tensor * a;
  2434. ggml_tensor * b;
  2435. const int npermuted = (per[0] != 0) + (per[1] != 1) + (per[2] != 2) + (per[3] != 3);
  2436. if (npermuted > 0) {
  2437. GGML_ASSERT(npermuted == 2);
  2438. GGML_ASSERT(!v); // not handled
  2439. GGML_ASSERT(!ggml_is_quantized(type_a) || per[0] == 0);
  2440. GGML_ASSERT(!ggml_is_quantized(type_b) || per[0] == 0);
  2441. // Create tensors with the permuted dimensions, then permute them back to the dimensions given by m,n,k.
  2442. const int64_t ne_a[4] = {k, m, bs[0], bs[1]};
  2443. const int64_t ne_b[4] = {k, n, bs[0]*nr[0], bs[1]*nr[1]};
  2444. a = ggml_new_tensor_4d(ctx, type_a, ne_a[per[0]], ne_a[per[1]], ne_a[per[2]], ne_a[per[3]]);
  2445. b = ggml_new_tensor_4d(ctx, type_b, ne_b[per[0]], ne_b[per[1]], ne_b[per[2]], ne_b[per[3]]);
  2446. if (!ggml_is_quantized(type_a)) {
  2447. if (bs[1] == 1 && nr[1] == 1) {
  2448. ggml_set_param(a);
  2449. }
  2450. ggml_set_param(b);
  2451. }
  2452. ggml_set_name(a, "a");
  2453. ggml_set_name(b, "b");
  2454. a = ggml_permute(ctx, a, per[0], per[1], per[2], per[3]);
  2455. b = ggml_permute(ctx, b, per[0], per[1], per[2], per[3]);
  2456. ggml_set_name(a, "a_permuted");
  2457. ggml_set_name(b, "b_permuted");
  2458. } else {
  2459. if (v) {
  2460. a = ggml_new_tensor_4d(ctx, type_a, k*2, m, bs[0], bs[1]);
  2461. b = ggml_new_tensor_4d(ctx, type_b, k*2, n, bs[0]*nr[0], bs[1]*nr[1]);
  2462. if (!ggml_is_quantized(type_a)) {
  2463. if (bs[1] == 1 && nr[1] == 1) {
  2464. ggml_set_param(a);
  2465. }
  2466. ggml_set_param(b);
  2467. }
  2468. a = ggml_view_4d(ctx, a, k, m, bs[0], bs[1], a->nb[1], a->nb[2], a->nb[3], 0);
  2469. b = ggml_view_4d(ctx, b, k, n, bs[0]*nr[0], bs[1]*nr[1], b->nb[1], b->nb[2], b->nb[3], 0);
  2470. } else {
  2471. a = ggml_new_tensor_4d(ctx, type_a, k, m, bs[0], bs[1]);
  2472. b = ggml_new_tensor_4d(ctx, type_b, k, n, bs[0]*nr[0], bs[1]*nr[1]);
  2473. if (!ggml_is_quantized(type_a)) {
  2474. if (bs[1] == 1 && nr[1] == 1) {
  2475. ggml_set_param(a);
  2476. }
  2477. ggml_set_param(b);
  2478. }
  2479. }
  2480. ggml_set_name(a, "a");
  2481. ggml_set_name(b, "b");
  2482. }
  2483. ggml_tensor * out = ggml_mul_mat(ctx, a, b);
  2484. ggml_set_name(out, "out");
  2485. return out;
  2486. }
  2487. };
  2488. // GGML_OP_MUL_MAT_ID
  2489. struct test_mul_mat_id : public test_case {
  2490. const ggml_type type_a;
  2491. const ggml_type type_b;
  2492. const int n_mats;
  2493. const int n_used;
  2494. const bool b; // broadcast b matrix
  2495. const int64_t m;
  2496. const int64_t n;
  2497. const int64_t k;
  2498. std::string vars() override {
  2499. return VARS_TO_STR8(type_a, type_b, n_mats, n_used, b, m, n, k);
  2500. }
  2501. double max_nmse_err() override {
  2502. return 5e-4;
  2503. }
  2504. uint64_t op_flops(ggml_tensor * t) override {
  2505. GGML_UNUSED(t);
  2506. return 2 * m * k * n * n_used;
  2507. }
  2508. test_mul_mat_id(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  2509. int n_mats = 8, int n_used = 2, bool b = false,
  2510. int64_t m = 32, int64_t n = 32, int64_t k = 32)
  2511. : type_a(type_a), type_b(type_b), n_mats(n_mats), n_used(n_used), b(b),
  2512. m(m), n(n), k(k) {
  2513. GGML_ASSERT(n_used <= n_mats);
  2514. }
  2515. ggml_tensor * build_graph(ggml_context * ctx) override {
  2516. // C^T = A * B^T: (k, m) * (k, n) => (m, n)
  2517. ggml_tensor * as = ggml_new_tensor_3d(ctx, type_a, k, m, n_mats);
  2518. ggml_set_name(as, "as");
  2519. ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_mats, n);
  2520. ggml_set_name(ids, "ids");
  2521. if (n_used != n_mats) {
  2522. ids = ggml_view_2d(ctx, ids, n_used, n, ids->nb[1], 0);
  2523. ggml_set_name(ids, "view_of_ids");
  2524. }
  2525. ggml_tensor * b = ggml_new_tensor_3d(ctx, type_b, k, this->b ? 1 : n_used, n);
  2526. ggml_set_name(b, "b");
  2527. ggml_tensor * out = ggml_mul_mat_id(ctx, as, b, ids);
  2528. ggml_set_name(out, "out");
  2529. return out;
  2530. }
  2531. void initialize_tensors(ggml_context * ctx) override {
  2532. std::random_device rd;
  2533. std::default_random_engine rng(rd());
  2534. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2535. if (t->type == GGML_TYPE_I32) {
  2536. if (ggml_is_view_op(t->op)) { continue; }
  2537. // ids
  2538. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  2539. std::vector<int32_t> data(t->ne[0]);
  2540. for (int i = 0; i < t->ne[0]; i++) {
  2541. data[i] = i % n_mats;
  2542. }
  2543. std::shuffle(data.begin(), data.end(), rng);
  2544. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
  2545. }
  2546. } else {
  2547. init_tensor_uniform(t);
  2548. }
  2549. }
  2550. }
  2551. };
  2552. // GGML_OP_OUT_PROD
  2553. struct test_out_prod : public test_case {
  2554. const ggml_type type_a;
  2555. const ggml_type type_b;
  2556. const int64_t m;
  2557. const int64_t n;
  2558. const int64_t k;
  2559. const std::array<int64_t, 2> bs; // dims 3 and 4
  2560. const std::array<int64_t, 2> nr; // repeat in dims 3 and 4
  2561. const bool trans_b;
  2562. std::string vars() override {
  2563. return VARS_TO_STR8(type_a, type_b, m, n, k, bs, nr, trans_b);
  2564. }
  2565. double max_nmse_err() override {
  2566. return 5e-4;
  2567. }
  2568. test_out_prod(ggml_type type_a = GGML_TYPE_F32, ggml_type type_b = GGML_TYPE_F32,
  2569. int64_t m = 32, int64_t n = 32, int64_t k = 32,
  2570. std::array<int64_t, 2> bs = {10, 10},
  2571. std::array<int64_t, 2> nr = {2, 2},
  2572. bool trans_b = false)
  2573. : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), nr(nr), trans_b(trans_b) {}
  2574. ggml_tensor * build_graph(ggml_context * ctx) override {
  2575. ggml_tensor * a = ggml_new_tensor_4d(ctx, type_a, m, k, bs[0], bs[1]);
  2576. ggml_set_name(a, "a");
  2577. ggml_tensor * b;
  2578. if (trans_b) {
  2579. b = ggml_new_tensor_4d(ctx, type_b, k, n, bs[0]*nr[0], bs[1]*nr[1]);
  2580. b = ggml_transpose(ctx, b);
  2581. } else {
  2582. b = ggml_new_tensor_4d(ctx, type_b, n, k, bs[0]*nr[0], bs[1]*nr[1]);
  2583. }
  2584. ggml_set_name(b, "b");
  2585. ggml_tensor * out = ggml_out_prod(ctx, a, b);
  2586. ggml_set_name(out, "out");
  2587. return out;
  2588. }
  2589. };
  2590. // GGML_OP_SQR
  2591. struct test_sqr : public test_case {
  2592. const ggml_type type;
  2593. const std::array<int64_t, 4> ne;
  2594. std::string vars() override {
  2595. return VARS_TO_STR2(type, ne);
  2596. }
  2597. test_sqr(ggml_type type = GGML_TYPE_F32,
  2598. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2599. : type(type), ne(ne) {}
  2600. ggml_tensor * build_graph(ggml_context * ctx) override {
  2601. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2602. ggml_set_param(a);
  2603. ggml_set_name(a, "a");
  2604. ggml_tensor * out = ggml_sqr(ctx, a);
  2605. ggml_set_name(out, "out");
  2606. return out;
  2607. }
  2608. float grad_eps() override {
  2609. return 0.1f * 0.25f*ne[0]*ne[1]*ne[2]*ne[3]; // 10% of expected value of sum.
  2610. }
  2611. };
  2612. // GGML_OP_SQRT
  2613. struct test_sqrt : public test_case {
  2614. const ggml_type type;
  2615. const std::array<int64_t, 4> ne;
  2616. std::string vars() override {
  2617. return VARS_TO_STR2(type, ne);
  2618. }
  2619. test_sqrt(ggml_type type = GGML_TYPE_F32,
  2620. std::array<int64_t, 4> ne = {10, 3, 3, 2})
  2621. : type(type), ne(ne) {}
  2622. ggml_tensor * build_graph(ggml_context * ctx) override {
  2623. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2624. ggml_set_param(a);
  2625. ggml_set_name(a, "a");
  2626. ggml_tensor * out = ggml_sqrt(ctx, a);
  2627. ggml_set_name(out, "out");
  2628. return out;
  2629. }
  2630. void initialize_tensors(ggml_context * ctx) override {
  2631. // fill with positive values
  2632. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2633. init_tensor_uniform(t, 50.0f, 100.0f);
  2634. }
  2635. }
  2636. float grad_eps() override {
  2637. return 20.0f;
  2638. }
  2639. bool grad_precise() override {
  2640. return true;
  2641. }
  2642. };
  2643. // GGML_OP_LOG
  2644. struct test_log : public test_case {
  2645. const ggml_type type;
  2646. const std::array<int64_t, 4> ne;
  2647. std::string vars() override {
  2648. return VARS_TO_STR2(type, ne);
  2649. }
  2650. test_log(ggml_type type = GGML_TYPE_F32,
  2651. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  2652. : type(type), ne(ne) {}
  2653. ggml_tensor * build_graph(ggml_context * ctx) override {
  2654. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2655. ggml_set_param(a);
  2656. ggml_set_name(a, "a");
  2657. ggml_tensor * out = ggml_log(ctx, a);
  2658. ggml_set_name(out, "out");
  2659. return out;
  2660. }
  2661. void initialize_tensors(ggml_context * ctx) override {
  2662. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2663. // log(1) == 0, cluster values there to keep the sum low for better precision in the backward pass:
  2664. init_tensor_uniform(t, 0.9f, 1.1f);
  2665. }
  2666. }
  2667. bool grad_precise() override {
  2668. return true;
  2669. }
  2670. };
  2671. // GGML_OP_SIN
  2672. struct test_sin : public test_case {
  2673. const ggml_type type;
  2674. const std::array<int64_t, 4> ne;
  2675. std::string vars() override {
  2676. return VARS_TO_STR2(type, ne);
  2677. }
  2678. test_sin(ggml_type type = GGML_TYPE_F32,
  2679. std::array<int64_t, 4> ne = {10, 2, 2, 2})
  2680. : type(type), ne(ne) {}
  2681. ggml_tensor * build_graph(ggml_context * ctx) override {
  2682. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2683. ggml_set_param(a);
  2684. ggml_set_name(a, "a");
  2685. ggml_tensor * out = ggml_sin(ctx, a);
  2686. ggml_set_name(out, "out");
  2687. return out;
  2688. }
  2689. void initialize_tensors(ggml_context * ctx) override {
  2690. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2691. init_tensor_uniform(t, -6.5f, 6.5f); // Covers interval [-2*pi, 2*pi].
  2692. }
  2693. }
  2694. double max_maa_err() override {
  2695. return 1e-3;
  2696. }
  2697. float grad_eps() override {
  2698. return 0.2f;
  2699. }
  2700. bool grad_precise() override {
  2701. return true;
  2702. }
  2703. };
  2704. // GGML_OP_COS
  2705. struct test_cos : public test_case {
  2706. const ggml_type type;
  2707. const std::array<int64_t, 4> ne;
  2708. std::string vars() override {
  2709. return VARS_TO_STR2(type, ne);
  2710. }
  2711. test_cos(ggml_type type = GGML_TYPE_F32,
  2712. std::array<int64_t, 4> ne = {10, 2, 2, 2})
  2713. : type(type), ne(ne) {}
  2714. ggml_tensor * build_graph(ggml_context * ctx) override {
  2715. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2716. ggml_set_param(a);
  2717. ggml_set_name(a, "a");
  2718. ggml_tensor * out = ggml_cos(ctx, a);
  2719. ggml_set_name(out, "out");
  2720. return out;
  2721. }
  2722. void initialize_tensors(ggml_context * ctx) override {
  2723. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2724. init_tensor_uniform(t, -6.5f, 6.5f); // Covers interval [-2*pi, 2*pi].
  2725. }
  2726. }
  2727. double max_maa_err() override {
  2728. return 1e-3;
  2729. }
  2730. float grad_eps() override {
  2731. return 0.2f;
  2732. }
  2733. bool grad_precise() override {
  2734. return true;
  2735. }
  2736. };
  2737. // GGML_OP_CLAMP
  2738. struct test_clamp : public test_case {
  2739. const ggml_type type;
  2740. const std::array<int64_t, 4> ne;
  2741. float min;
  2742. float max;
  2743. std::string vars() override {
  2744. return VARS_TO_STR4(type, ne, min, max);
  2745. }
  2746. test_clamp(ggml_type type = GGML_TYPE_F32,
  2747. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  2748. float min = -0.5f, float max = 0.5f)
  2749. : type(type), ne(ne), min(min), max(max) {}
  2750. ggml_tensor * build_graph(ggml_context * ctx) override {
  2751. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2752. ggml_set_name(a, "a");
  2753. ggml_tensor * out = ggml_clamp(ctx, a, min, max);
  2754. ggml_set_name(out, "out");
  2755. return out;
  2756. }
  2757. float grad_eps() override {
  2758. return 1e-2f;
  2759. }
  2760. std::vector<float> grad_expect() override {
  2761. return {0.0f, 1.0f};
  2762. }
  2763. };
  2764. // GGML_OP_DIAG_MASK_INF
  2765. struct test_diag_mask_inf : public test_case {
  2766. const ggml_type type;
  2767. const std::array<int64_t, 4> ne;
  2768. const int n_past;
  2769. std::string vars() override {
  2770. return VARS_TO_STR3(type, ne, n_past);
  2771. }
  2772. test_diag_mask_inf(ggml_type type = GGML_TYPE_F32,
  2773. std::array<int64_t, 4> ne = {10, 10, 3, 2},
  2774. int n_past = 5)
  2775. : type(type), ne(ne), n_past(n_past) {}
  2776. ggml_tensor * build_graph(ggml_context * ctx) override {
  2777. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2778. ggml_set_param(a);
  2779. ggml_set_name(a, "a");
  2780. ggml_tensor * out = ggml_diag_mask_inf(ctx, a, n_past);
  2781. ggml_set_name(out, "out");
  2782. return out;
  2783. }
  2784. };
  2785. // GGML_OP_SOFT_MAX
  2786. struct test_soft_max : public test_case {
  2787. const ggml_type type;
  2788. const std::array<int64_t, 4> ne;
  2789. const bool mask;
  2790. const ggml_type m_prec;
  2791. const std::array<int64_t, 2> nr23; // broadcast only dims 2 and 3
  2792. const float scale;
  2793. const float max_bias;
  2794. std::string vars() override {
  2795. return VARS_TO_STR7(type, ne, mask, m_prec, nr23, scale, max_bias);
  2796. }
  2797. // the 1024 test with bias occasionally fails:
  2798. // 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
  2799. virtual double max_nmse_err() override {
  2800. return 1e-6;
  2801. }
  2802. test_soft_max(ggml_type type = GGML_TYPE_F32,
  2803. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  2804. bool mask = false,
  2805. ggml_type m_prec = GGML_TYPE_F32,
  2806. std::array<int64_t, 2> nr23 = {1, 1},
  2807. float scale = 1.0f,
  2808. float max_bias = 0.0f)
  2809. : type(type), ne(ne), mask(mask), m_prec(m_prec), nr23(nr23), scale(scale), max_bias(max_bias) {}
  2810. ggml_tensor * build_graph(ggml_context * ctx) override {
  2811. ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2]*nr23[0], ne[3]*nr23[1]);
  2812. ggml_set_param(a);
  2813. ggml_set_name(a, "a");
  2814. ggml_tensor * mask = nullptr;
  2815. if (this->mask) {
  2816. mask = ggml_new_tensor_4d(ctx, m_prec, ne[0], ne[1], ne[2], ne[3]);
  2817. ggml_set_name(mask, "mask");
  2818. }
  2819. ggml_tensor * out = ggml_soft_max_ext(ctx, a, mask, scale, max_bias);
  2820. ggml_set_name(out, "out");
  2821. return out;
  2822. }
  2823. bool grad_precise() override {
  2824. return true;
  2825. }
  2826. };
  2827. // GGML_OP_SOFT_MAX_BACK
  2828. struct test_soft_max_back : public test_case {
  2829. const ggml_type type;
  2830. const std::array<int64_t, 4> ne;
  2831. const float scale;
  2832. const float max_bias;
  2833. std::string vars() override {
  2834. return VARS_TO_STR4(type, ne, scale, max_bias);
  2835. }
  2836. test_soft_max_back(ggml_type type = GGML_TYPE_F32,
  2837. std::array<int64_t, 4> ne = {10, 5, 4, 3},
  2838. float scale = 1.0f,
  2839. float max_bias = 0.0f)
  2840. : type(type), ne(ne), scale(scale), max_bias(max_bias) {}
  2841. ggml_tensor * build_graph(ggml_context * ctx) override {
  2842. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  2843. ggml_set_name(a, "a");
  2844. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data());
  2845. ggml_set_name(a, "a");
  2846. ggml_tensor * out = ggml_soft_max_ext_back(ctx, a, b, scale, max_bias);
  2847. ggml_set_name(out, "out");
  2848. return out;
  2849. }
  2850. };
  2851. // GGML_OP_ROPE + GGML_OP_ROPE_BACK
  2852. struct test_rope : public test_case {
  2853. const ggml_type type;
  2854. const std::array<int64_t, 4> ne_a;
  2855. int n_dims;
  2856. int mode;
  2857. int n_ctx; // used to generate positions
  2858. float fs; // freq_scale
  2859. float ef; // ext_factor
  2860. float af; // attn_factor
  2861. bool ff;
  2862. int v; // view (1 : non-contiguous a)
  2863. bool forward;
  2864. std::string vars() override {
  2865. // forward can be inferred from the op, does not need to be printed
  2866. return VARS_TO_STR10(type, ne_a, n_dims, mode, n_ctx, fs, ef, af, ff, v);
  2867. }
  2868. test_rope(ggml_type type = GGML_TYPE_F32,
  2869. std::array<int64_t, 4> ne_a = {10, 5, 3, 1},
  2870. int n_dims = 10, int mode = 0, int n_ctx = 512, float fs = 1.0f,
  2871. float ef = 0.0f, float af = 0.0f, bool ff = false, int v = 0, bool forward = true)
  2872. : 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), forward(forward) {}
  2873. ggml_tensor * build_graph(ggml_context * ctx) override {
  2874. ggml_tensor * a;
  2875. if (v & 1) {
  2876. auto ne = ne_a; ne[0] *= 2; ne[1] *= 4; ne[2] *= 3;
  2877. a = ggml_new_tensor(ctx, type, 4, ne.data());
  2878. if (forward) {
  2879. ggml_set_param(a);
  2880. }
  2881. ggml_set_name(a, "a");
  2882. 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);
  2883. ggml_set_name(a, "view_of_a");
  2884. } else {
  2885. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  2886. if (forward) {
  2887. ggml_set_param(a);
  2888. }
  2889. ggml_set_name(a, "a");
  2890. }
  2891. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  2892. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  2893. ggml_tensor * pos;
  2894. if (is_mrope || is_vision) {
  2895. pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, ne_a[2] * 4);
  2896. } else {
  2897. pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, ne_a[2]);
  2898. }
  2899. ggml_set_name(pos, "pos");
  2900. ggml_tensor * freq = nullptr;
  2901. if (ff) {
  2902. freq = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_dims/2);
  2903. ggml_set_name(freq, "freq");
  2904. }
  2905. ggml_tensor * out;
  2906. if (is_mrope) {
  2907. if (is_vision) {
  2908. GGML_ASSERT(n_dims/4 > 0);
  2909. int rope_sections[4] = {n_dims/4, n_dims/4, 0, 0}; // Vision-RoPE only use first two dimension for image (x, y) coordinate
  2910. if (forward) {
  2911. out = ggml_rope_multi (ctx, a, pos, freq, n_dims/2, rope_sections, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2912. } else {
  2913. out = ggml_rope_multi_back(ctx, a, pos, freq, n_dims/2, rope_sections, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2914. }
  2915. } else {
  2916. GGML_ASSERT(n_dims/3 > 0);
  2917. int rope_sections[4] = {n_dims/3, n_dims/3, n_dims/3, 0};
  2918. if (forward) {
  2919. out = ggml_rope_multi (ctx, a, pos, freq, n_dims, rope_sections, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2920. } else {
  2921. out = ggml_rope_multi_back(ctx, a, pos, freq, n_dims, rope_sections, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2922. }
  2923. }
  2924. } else {
  2925. if (forward) {
  2926. out = ggml_rope_ext (ctx, a, pos, freq, n_dims, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2927. } else {
  2928. out = ggml_rope_ext_back(ctx, a, pos, freq, n_dims, mode, 0, 10000.0f, fs, ef, af, 1.0f, 1.0f);
  2929. }
  2930. // TODO: add test with a non-contiguous view as input ; this case is needed for build_rope_2d in clip.cpp
  2931. }
  2932. ggml_set_name(out, "out");
  2933. return out;
  2934. }
  2935. void initialize_tensors(ggml_context * ctx) override {
  2936. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  2937. if (t->type == GGML_TYPE_I32) {
  2938. // pos
  2939. const int num_pos_ids = (mode & GGML_ROPE_TYPE_MROPE) ? ne_a[2] * 4 : ne_a[2];
  2940. std::vector<int> data(num_pos_ids);
  2941. for (int i = 0; i < num_pos_ids; i++) {
  2942. data[i] = rand() % n_ctx;
  2943. }
  2944. ggml_backend_tensor_set(t, data.data(), 0, num_pos_ids * sizeof(int));
  2945. } else {
  2946. if (t->ne[0] == n_dims/2) {
  2947. // frequency factors in the range [0.9f, 1.1f]
  2948. init_tensor_uniform(t, 0.9f, 1.1f);
  2949. } else {
  2950. init_tensor_uniform(t);
  2951. }
  2952. }
  2953. }
  2954. }
  2955. double max_maa_err() override {
  2956. return 1e-3;
  2957. }
  2958. bool grad_precise() override {
  2959. return true;
  2960. }
  2961. };
  2962. // GGML_OP_POOL2D
  2963. struct test_pool2d : public test_case {
  2964. enum ggml_op_pool pool_type;
  2965. const ggml_type type_input;
  2966. const std::array<int64_t, 4> ne_input;
  2967. // kernel size
  2968. const int k0;
  2969. const int k1;
  2970. // stride
  2971. const int s0;
  2972. const int s1;
  2973. // padding
  2974. const int p0;
  2975. const int p1;
  2976. std::string vars() override {
  2977. return VARS_TO_STR9(pool_type, type_input, ne_input, k0, k1, s0, s1, p0, p1);
  2978. }
  2979. test_pool2d(ggml_op_pool pool_type = GGML_OP_POOL_AVG,
  2980. ggml_type type_input = GGML_TYPE_F32,
  2981. std::array<int64_t, 4> ne_input = {10, 10, 3, 1}, // [input_width, input_height, input_channels, 1]
  2982. int k0 = 3, int k1 = 3,
  2983. int s0 = 1, int s1 = 1,
  2984. int p0 = 1, int p1 = 1)
  2985. : pool_type(pool_type), type_input(type_input), ne_input(ne_input), k0(k0), k1(k1), s0(s0), s1(s1), p0(p0), p1(p1) {}
  2986. ggml_tensor * build_graph(ggml_context * ctx) override {
  2987. ggml_tensor * input = ggml_new_tensor(ctx, type_input, 4, ne_input.data());
  2988. ggml_set_param(input);
  2989. ggml_set_name(input, "input");
  2990. ggml_tensor * out = ggml_pool_2d(ctx, input, pool_type, k0, k1, s0, s1, p0, p1);
  2991. ggml_set_name(out, "out");
  2992. return out;
  2993. }
  2994. };
  2995. // GGML_OP_CONV_TRANSPOSE_1D
  2996. struct test_conv_transpose_1d : public test_case {
  2997. const std::array<int64_t, 4> ne_input;
  2998. const std::array<int64_t, 4> ne_kernel;
  2999. const int s0; // stride
  3000. const int p0; // padding
  3001. const int d0; // dilation
  3002. std::string vars() override {
  3003. return VARS_TO_STR5(ne_input, ne_kernel, s0, p0, d0);
  3004. }
  3005. test_conv_transpose_1d(std::array<int64_t, 4> ne_input = {197, 32, 1, 1}, // [input_width, input_channels, 1 /* assert in cpu kernel*/, 1 (should be batch)]
  3006. std::array<int64_t, 4> ne_kernel = {16, 32, 32, 1}, // [kernel_width, output_channels, input_channels, 1 (should be batch)]
  3007. int s0 = 1, int p0 = 0, int d0 = 1)
  3008. : ne_input(ne_input), ne_kernel(ne_kernel), s0(s0), p0(p0), d0(d0) {}
  3009. ggml_tensor * build_graph(ggml_context * ctx) override {
  3010. ggml_tensor * input = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_input.data());
  3011. ggml_set_name(input, "input");
  3012. ggml_tensor * kernel = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_kernel.data());
  3013. ggml_set_name(kernel, "kernel");
  3014. ggml_tensor * out = ggml_conv_transpose_1d(ctx, kernel, input, s0, p0, d0);
  3015. ggml_set_name(out, "out");
  3016. return out;
  3017. }
  3018. };
  3019. // GGML_OP_CONV_TRANSPOSE_2D
  3020. struct test_conv_transpose_2d : public test_case {
  3021. const std::array<int64_t, 4> ne_input;
  3022. const std::array<int64_t, 4> ne_kernel;
  3023. const int stride;
  3024. std::string vars() override {
  3025. return VARS_TO_STR3(ne_input, ne_kernel, stride);
  3026. }
  3027. test_conv_transpose_2d(std::array<int64_t, 4> ne_input = {10, 10, 3, 1}, // [input_width, input_height, input_channels, 1]
  3028. std::array<int64_t, 4> ne_kernel = {3, 3, 3, 1}, // [kernel_width, kernel_height, input_channels, 1]
  3029. int stride = 1)
  3030. : ne_input(ne_input), ne_kernel(ne_kernel), stride(stride){}
  3031. ggml_tensor * build_graph(ggml_context * ctx) override {
  3032. ggml_tensor * input = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_input.data());
  3033. ggml_set_name(input, "input");
  3034. ggml_tensor * kernel = ggml_new_tensor(ctx, GGML_TYPE_F16, 4, ne_kernel.data());
  3035. ggml_set_name(kernel, "kernel");
  3036. ggml_tensor * out = ggml_conv_transpose_2d_p0(ctx, kernel, input, stride);
  3037. ggml_set_name(out, "out");
  3038. return out;
  3039. }
  3040. };
  3041. // GGML_OP_IM2COL
  3042. struct test_im2col : public test_case {
  3043. const ggml_type type_input;
  3044. const ggml_type type_kernel;
  3045. const ggml_type dst_type;
  3046. const std::array<int64_t, 4> ne_input;
  3047. const std::array<int64_t, 4> ne_kernel;
  3048. // stride
  3049. const int s0;
  3050. const int s1;
  3051. // padding
  3052. const int p0;
  3053. const int p1;
  3054. // dilation
  3055. const int d0;
  3056. const int d1;
  3057. // mode
  3058. const bool is_2D;
  3059. std::string vars() override {
  3060. return VARS_TO_STR12(type_input, type_kernel, dst_type, ne_input, ne_kernel, s0, s1, p0, p1, d0, d1, is_2D);
  3061. }
  3062. test_im2col(ggml_type type_input = GGML_TYPE_F32, ggml_type type_kernel = GGML_TYPE_F16, ggml_type dst_type = GGML_TYPE_F32,
  3063. std::array<int64_t, 4> ne_input = {10, 10, 3, 1}, // [input_width, input_height, input_channels, 1]
  3064. std::array<int64_t, 4> ne_kernel = {3, 3, 3, 1}, // [kernel_width, kernel_height, input_channels, 1]
  3065. int s0 = 1, int s1 = 1,
  3066. int p0 = 1, int p1 = 1,
  3067. int d0 = 1, int d1 = 1,
  3068. bool is_2D = true)
  3069. : 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) {}
  3070. ggml_tensor * build_graph(ggml_context * ctx) override {
  3071. ggml_tensor * input = ggml_new_tensor(ctx, type_input, 4, ne_input.data());
  3072. ggml_set_param(input);
  3073. ggml_set_name(input, "input");
  3074. ggml_tensor * kernel = ggml_new_tensor(ctx, type_kernel, 4, ne_kernel.data());
  3075. ggml_set_name(kernel, "kernel");
  3076. ggml_tensor * out = ggml_im2col(ctx, kernel, input, s0, s1, p0, p1, d0, d1, is_2D, dst_type);
  3077. ggml_set_name(out, "out");
  3078. return out;
  3079. }
  3080. };
  3081. // CONV_2D
  3082. struct test_conv_2d : public test_case {
  3083. const std::array<int64_t, 4> ne_input;
  3084. const std::array<int64_t, 4> ne_kernel;
  3085. const ggml_type type_kernel;
  3086. const int stride0;
  3087. const int stride1;
  3088. const int padding0;
  3089. const int padding1;
  3090. const int dilation0;
  3091. const int dilation1;
  3092. // Whether the inputs are contiguous in the channel dim or the width dim
  3093. const bool cwhn;
  3094. // If true, the direct CONV_2D will be used in the graph, otherwise it
  3095. // uses ggml_conv_2d:
  3096. // * if the program is called with -o CONV_2D_DIRECT_IMPL, the
  3097. // CONV_2D graph will be built, while
  3098. // * if the program is called with -o CONV_2D_INDIRECT_IMPL, the
  3099. // IM2COL -> MUL_MM graph will be built.
  3100. std::string vars() override {
  3101. return VARS_TO_STR10(ne_input, ne_kernel, type_kernel, stride0, stride1, padding0, padding1, dilation0, dilation1, cwhn);
  3102. }
  3103. double max_nmse_err() override {
  3104. return 5e-4;
  3105. }
  3106. uint64_t op_flops(ggml_tensor * t) override {
  3107. GGML_UNUSED(t);
  3108. // Just counting matmul costs:
  3109. // KxCRS @ CRSxNPQ = KxNPQ --> KxNPQx(CRS+CRS-1) flops
  3110. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  3111. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  3112. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  3113. };
  3114. int64_t W = ne_input[0];
  3115. int64_t H = ne_input[1];
  3116. int64_t KW = ne_kernel[0];
  3117. int64_t KH = ne_kernel[1];
  3118. int64_t Cin = ne_kernel[2];
  3119. int64_t Cout = ne_kernel[3];
  3120. int64_t N = ne_input[3];
  3121. int64_t OH = calc_conv_output_size(H, KH, stride0, padding0, dilation0);
  3122. int64_t OW = calc_conv_output_size(W, KW, stride0, padding0, dilation0);
  3123. int64_t K = Cout;
  3124. int64_t CRS = Cin * KH * KW;
  3125. int64_t NPQ = N * OH * OW;
  3126. return K * NPQ * (2 * CRS - 1);
  3127. }
  3128. test_conv_2d(std::array<int64_t, 4> ne_input = { 64, 64, 16, 1 },
  3129. std::array<int64_t, 4> ne_kernel = { 3, 3, 1, 16 }, ggml_type type_kernel = GGML_TYPE_F32, int stride0 = 1,
  3130. int stride1 = 1, int padding0 = 0, int padding1 = 0, int dilation0 = 1, int dilation1 = 1, bool cwhn = false) :
  3131. ne_input(ne_input),
  3132. ne_kernel(ne_kernel),
  3133. type_kernel(type_kernel),
  3134. stride0(stride0),
  3135. stride1(stride1),
  3136. padding0(padding0),
  3137. padding1(padding1),
  3138. dilation0(dilation0),
  3139. dilation1(dilation1),
  3140. cwhn(cwhn) {}
  3141. ggml_tensor * build_graph(ggml_context * ctx) override {
  3142. ggml_tensor * input = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_input.data());
  3143. ggml_set_name(input, "input");
  3144. ggml_tensor * kernel = ggml_new_tensor(ctx, type_kernel, 4, ne_kernel.data());
  3145. ggml_set_name(kernel, "kernel");
  3146. if (cwhn) {
  3147. // change memory layout to channel-most-contiguous (CWHN),
  3148. // then permute it back so NE matches the original input
  3149. input = ggml_cont(ctx, ggml_permute(ctx, input, 1, 2, 0, 3));
  3150. input = ggml_permute(ctx, input, 2, 0, 1, 3);
  3151. kernel = ggml_cont(ctx, ggml_permute(ctx, kernel, 2, 3, 1, 0));
  3152. kernel = ggml_permute(ctx, kernel, 3, 2, 0, 1);
  3153. }
  3154. ggml_tensor * out =
  3155. ggml_conv_2d_direct(ctx, kernel, input, stride0, stride1, padding0, padding1, dilation0, dilation1);
  3156. ggml_set_name(out, "out");
  3157. return out;
  3158. }
  3159. };
  3160. // GGML_OP_CONV_2D_DW
  3161. struct test_conv_2d_dw : public test_case {
  3162. const std::array<int64_t, 4> ne_input;
  3163. const std::array<int64_t, 4> ne_kernel;
  3164. const int stride;
  3165. const int padding;
  3166. const int dilation;
  3167. const bool cwhn;
  3168. std::string vars() override {
  3169. return VARS_TO_STR6(ne_input, ne_kernel, stride, padding, dilation, cwhn);
  3170. }
  3171. test_conv_2d_dw(std::array<int64_t, 4> ne_input = {64, 64, 16, 1},
  3172. std::array<int64_t, 4> ne_kernel = {3, 3, 1, 16},
  3173. int stride = 1, int padding = 0, int dilation = 1, bool cwhn = false)
  3174. : ne_input(ne_input), ne_kernel(ne_kernel), stride(stride), padding(padding), dilation(dilation), cwhn(cwhn) {}
  3175. ggml_tensor * build_graph(ggml_context * ctx) override {
  3176. ggml_tensor * input = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_input.data());
  3177. ggml_set_name(input, "input");
  3178. ggml_tensor * kernel = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_kernel.data());
  3179. ggml_set_name(kernel, "kernel");
  3180. if (cwhn) {
  3181. // change memory layout to channel-most-contiguous (CWHN),
  3182. // then permute it back so NE matches the original input
  3183. input = ggml_cont(ctx, ggml_permute(ctx, input, 1, 2, 0, 3));
  3184. input = ggml_permute(ctx, input, 2, 0, 1, 3);
  3185. kernel = ggml_cont(ctx, ggml_permute(ctx, kernel, 2, 3, 1, 0));
  3186. kernel = ggml_permute(ctx, kernel, 3, 2, 0, 1);
  3187. }
  3188. ggml_tensor * out = ggml_conv_2d_dw_direct(
  3189. ctx, kernel, input,
  3190. stride, stride, padding, padding, dilation, dilation);
  3191. ggml_set_name(out, "out");
  3192. return out;
  3193. }
  3194. };
  3195. // GGML_OP_CONCAT
  3196. struct test_concat : public test_case {
  3197. const ggml_type type;
  3198. const std::array<int64_t, 4> ne_a;
  3199. const int64_t ne_b_d;
  3200. const int dim;
  3201. const int v; // view (1 << 0: non-cont a, 1 << 1: non-cont b)
  3202. std::string vars() override {
  3203. return VARS_TO_STR5(type, ne_a, ne_b_d, dim, v);
  3204. }
  3205. test_concat(ggml_type type = GGML_TYPE_F32,
  3206. std::array<int64_t, 4> ne_a = {10, 5, 5, 5},
  3207. int64_t ne_b_d = 5,
  3208. int dim = 2, int v = 0)
  3209. : type(type), ne_a(ne_a), ne_b_d(ne_b_d), dim(dim), v(v) {}
  3210. ggml_tensor * build_graph(ggml_context * ctx) override {
  3211. auto ne_b = ne_a;
  3212. ne_b[dim] = ne_b_d;
  3213. ggml_tensor * a;
  3214. if (v & 1) {
  3215. auto ne = ne_a; ne[0] *= 2; ne[1] *= 4; ne[2] *= 3;
  3216. a = ggml_new_tensor(ctx, type, 4, ne.data());
  3217. ggml_set_name(a, "a");
  3218. 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);
  3219. ggml_set_name(a, "view_of_a");
  3220. } else {
  3221. a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  3222. ggml_set_name(a, "a");
  3223. }
  3224. ggml_tensor * b;
  3225. if (v & 2) {
  3226. auto ne = ne_b; ne[0] *= 3; ne[1] *= 2; ne[2] *= 4;
  3227. b = ggml_new_tensor(ctx, type, 4, ne.data());
  3228. ggml_set_name(b, "b");
  3229. 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);
  3230. ggml_set_name(b, "view_of_b");
  3231. } else {
  3232. b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  3233. ggml_set_name(b, "b");
  3234. }
  3235. ggml_tensor * out = ggml_concat(ctx, a, b, dim);
  3236. ggml_set_name(out, "out");
  3237. return out;
  3238. }
  3239. };
  3240. // GGML_OP_ARGSORT
  3241. struct test_argsort : public test_case {
  3242. const ggml_type type;
  3243. const std::array<int64_t, 4> ne;
  3244. ggml_sort_order order;
  3245. std::string vars() override {
  3246. return VARS_TO_STR3(type, ne, order);
  3247. }
  3248. test_argsort(ggml_type type = GGML_TYPE_F32,
  3249. std::array<int64_t, 4> ne = {16, 10, 10, 10},
  3250. ggml_sort_order order = GGML_SORT_ORDER_ASC)
  3251. : type(type), ne(ne), order(order) {}
  3252. ggml_tensor * build_graph(ggml_context * ctx) override {
  3253. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3254. ggml_set_name(a, "a");
  3255. ggml_tensor * out = ggml_argsort(ctx, a, order);
  3256. ggml_set_name(out, "out");
  3257. return out;
  3258. }
  3259. void initialize_tensors(ggml_context * ctx) override {
  3260. std::random_device rd;
  3261. std::default_random_engine rng(rd());
  3262. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  3263. if (t->type == GGML_TYPE_I32) {
  3264. // indices
  3265. std::vector<int> data(ggml_nelements(t));
  3266. for (int i = 0; i < ggml_nelements(t); i++) {
  3267. data[i] = rand();
  3268. }
  3269. std::shuffle(data.begin(), data.end(), rng);
  3270. ggml_backend_tensor_set(t, data.data(), 0, ne[0]*ne[1]*ne[2]*ne[3] * sizeof(int));
  3271. } else if (t->type == GGML_TYPE_F32) {
  3272. // initialize with unique values to avoid ties
  3273. for (int64_t r = 0; r < ggml_nrows(t); r++) {
  3274. std::vector<float> data(t->ne[0]);
  3275. for (int i = 0; i < t->ne[0]; i++) {
  3276. data[i] = i;
  3277. }
  3278. std::shuffle(data.begin(), data.end(), rng);
  3279. ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(float));
  3280. }
  3281. } else {
  3282. GGML_ABORT("fatal error");
  3283. }
  3284. }
  3285. }
  3286. };
  3287. // GGML_OP_SUM
  3288. struct test_sum : public test_case {
  3289. const ggml_type type;
  3290. const std::array<int64_t, 4> ne;
  3291. std::string vars() override {
  3292. return VARS_TO_STR2(type, ne);
  3293. }
  3294. test_sum(ggml_type type = GGML_TYPE_F32,
  3295. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3296. : type(type), ne(ne) {}
  3297. ggml_tensor * build_graph(ggml_context * ctx) override {
  3298. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3299. ggml_set_param(a);
  3300. ggml_set_name(a, "a");
  3301. ggml_tensor * out = ggml_sum(ctx, a);
  3302. ggml_set_name(out, "out");
  3303. return out;
  3304. }
  3305. float grad_eps() override {
  3306. return 0.1f * sqrtf(ne[0]*ne[1]*ne[2]*ne[3]);
  3307. }
  3308. };
  3309. // GGML_OP_SUM_ROWS
  3310. struct test_sum_rows : public test_case {
  3311. const ggml_type type;
  3312. const std::array<int64_t, 4> ne;
  3313. std::string vars() override {
  3314. return VARS_TO_STR2(type, ne);
  3315. }
  3316. test_sum_rows(ggml_type type = GGML_TYPE_F32,
  3317. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3318. : type(type), ne(ne) {}
  3319. ggml_tensor * build_graph(ggml_context * ctx) override {
  3320. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3321. ggml_set_param(a);
  3322. ggml_set_name(a, "a");
  3323. ggml_tensor * out = ggml_sum_rows(ctx, a);
  3324. ggml_set_name(out, "out");
  3325. return out;
  3326. }
  3327. };
  3328. // GGML_OP_MEAN
  3329. struct test_mean : public test_case {
  3330. const ggml_type type;
  3331. const std::array<int64_t, 4> ne;
  3332. std::string vars() override {
  3333. return VARS_TO_STR2(type, ne);
  3334. }
  3335. test_mean(ggml_type type = GGML_TYPE_F32,
  3336. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3337. : type(type), ne(ne) {}
  3338. ggml_tensor * build_graph(ggml_context * ctx) override {
  3339. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3340. ggml_set_param(a);
  3341. ggml_set_name(a, "a");
  3342. ggml_tensor * out = ggml_mean(ctx, a);
  3343. ggml_set_name(out, "out");
  3344. return out;
  3345. }
  3346. float grad_eps() override {
  3347. return 0.1f * ne[0]*ne[1]*ne[2]*ne[3];
  3348. }
  3349. };
  3350. // GGML_OP_UPSCALE
  3351. struct test_upscale : public test_case {
  3352. const ggml_type type;
  3353. const std::array<int64_t, 4> ne;
  3354. const int32_t scale_factor;
  3355. const bool transpose;
  3356. const ggml_scale_mode mode;
  3357. std::string vars() override {
  3358. return VARS_TO_STR5(type, ne, scale_factor, mode, transpose);
  3359. }
  3360. test_upscale(ggml_type type = GGML_TYPE_F32,
  3361. std::array<int64_t, 4> ne = {512, 512, 3, 1},
  3362. int32_t scale_factor = 2, ggml_scale_mode mode = GGML_SCALE_MODE_NEAREST, bool transpose = false)
  3363. : type(type), ne(ne), scale_factor(scale_factor), transpose(transpose), mode(mode) {}
  3364. ggml_tensor * build_graph(ggml_context * ctx) override {
  3365. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3366. ggml_set_name(a, "a");
  3367. if (transpose) {
  3368. a = ggml_transpose(ctx, a);
  3369. ggml_set_name(a, "a_transposed");
  3370. }
  3371. ggml_tensor * out = ggml_upscale(ctx, a, scale_factor, mode);
  3372. ggml_set_name(out, "out");
  3373. return out;
  3374. }
  3375. };
  3376. // GGML_OP_UPSCALE (via ggml_interpolate)
  3377. struct test_interpolate : public test_case {
  3378. const ggml_type type;
  3379. const std::array<int64_t, 4> ne;
  3380. const std::array<int64_t, 4> ne_tgt;
  3381. const uint32_t mode = GGML_SCALE_MODE_NEAREST;
  3382. std::string vars() override {
  3383. return VARS_TO_STR4(type, ne, ne_tgt, mode);
  3384. }
  3385. test_interpolate(ggml_type type = GGML_TYPE_F32,
  3386. std::array<int64_t, 4> ne = {2, 5, 7, 11},
  3387. std::array<int64_t, 4> ne_tgt = {5, 7, 11, 13},
  3388. uint32_t mode = GGML_SCALE_MODE_NEAREST)
  3389. : type(type), ne(ne), ne_tgt(ne_tgt), mode(mode) {}
  3390. ggml_tensor * build_graph(ggml_context * ctx) override {
  3391. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3392. ggml_set_name(a, "a");
  3393. ggml_tensor * out = ggml_interpolate(ctx, a, ne_tgt[0], ne_tgt[1],ne_tgt[2], ne_tgt[3], mode);
  3394. ggml_set_name(out, "out");
  3395. return out;
  3396. }
  3397. };
  3398. // GGML_OP_GROUP_NORM
  3399. struct test_group_norm : public test_case {
  3400. const ggml_type type;
  3401. const std::array<int64_t, 4> ne;
  3402. const int32_t num_groups;
  3403. const float eps;
  3404. std::string vars() override {
  3405. return VARS_TO_STR4(type, ne, num_groups, eps);
  3406. }
  3407. test_group_norm(ggml_type type = GGML_TYPE_F32,
  3408. std::array<int64_t, 4> ne = {64, 64, 320, 1},
  3409. int32_t num_groups = 32,
  3410. float eps = 1e-6f)
  3411. : type(type), ne(ne), num_groups(num_groups), eps(eps) {}
  3412. ggml_tensor * build_graph(ggml_context * ctx) override {
  3413. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3414. ggml_set_name(a, "a");
  3415. ggml_tensor * out = ggml_group_norm(ctx, a, num_groups, eps);
  3416. ggml_set_name(out, "out");
  3417. return out;
  3418. }
  3419. };
  3420. // GGML_OP_L2_NORM
  3421. struct test_l2_norm : public test_case {
  3422. const ggml_type type;
  3423. const std::array<int64_t, 4> ne;
  3424. const float eps;
  3425. std::string vars() override {
  3426. return VARS_TO_STR2(type, ne);
  3427. }
  3428. test_l2_norm(ggml_type type = GGML_TYPE_F32,
  3429. std::array<int64_t, 4> ne = {64, 64, 320, 1},
  3430. float eps = 1e-12f)
  3431. : type(type), ne(ne), eps(eps) {}
  3432. ggml_tensor * build_graph(ggml_context * ctx) override {
  3433. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data());
  3434. ggml_set_name(a, "a");
  3435. ggml_tensor * out = ggml_l2_norm(ctx, a, eps);
  3436. ggml_set_name(out, "out");
  3437. return out;
  3438. }
  3439. };
  3440. // GGML_OP_ACC
  3441. struct test_acc : public test_case {
  3442. const ggml_type type;
  3443. const std::array<int64_t, 4> ne_a;
  3444. const std::array<int64_t, 4> ne_b;
  3445. std::string vars() override {
  3446. return VARS_TO_STR3(type, ne_a, ne_b);
  3447. }
  3448. test_acc(ggml_type type = GGML_TYPE_F32,
  3449. std::array<int64_t, 4> ne_a = {256, 17, 1, 1},
  3450. std::array<int64_t, 4> ne_b = {256, 16, 1, 1})
  3451. : type(type), ne_a(ne_a), ne_b(ne_b) {}
  3452. ggml_tensor * build_graph(ggml_context * ctx) override {
  3453. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  3454. ggml_set_param(a);
  3455. ggml_set_name(a, "a");
  3456. ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data());
  3457. ggml_set_param(b);
  3458. ggml_set_name(b, "b");
  3459. ggml_tensor * out = ggml_acc(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], b->nb[1]);
  3460. ggml_set_name(out, "out");
  3461. return out;
  3462. }
  3463. };
  3464. // GGML_OP_PAD
  3465. struct test_pad : public test_case {
  3466. const ggml_type type;
  3467. const std::array<int64_t, 4> ne_a;
  3468. const int pad_0;
  3469. const int pad_1;
  3470. std::string vars() override {
  3471. return VARS_TO_STR4(type, ne_a, pad_0, pad_1);
  3472. }
  3473. test_pad(ggml_type type = GGML_TYPE_F32,
  3474. std::array<int64_t, 4> ne_a = {512, 512, 1, 1},
  3475. int pad_0 = 1, int pad_1 = 1)
  3476. : type(type), ne_a(ne_a), pad_0(pad_0), pad_1(pad_1) {}
  3477. ggml_tensor * build_graph(ggml_context * ctx) override {
  3478. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  3479. ggml_set_name(a, "a");
  3480. ggml_tensor * out = ggml_pad(ctx, a, pad_0, pad_1, 0, 0);
  3481. ggml_set_name(out, "out");
  3482. return out;
  3483. }
  3484. };
  3485. // GGML_OP_PAD_REFLECT_1D
  3486. struct test_pad_reflect_1d : public test_case {
  3487. const ggml_type type;
  3488. const std::array<int64_t, 4> ne_a;
  3489. const int pad_0;
  3490. const int pad_1;
  3491. std::string vars() override {
  3492. return VARS_TO_STR4(type, ne_a, pad_0, pad_1);
  3493. }
  3494. test_pad_reflect_1d(ggml_type type = GGML_TYPE_F32,
  3495. std::array<int64_t, 4> ne_a = {512, 34, 2, 1},
  3496. int pad_0 = 10, int pad_1 = 9)
  3497. : type(type), ne_a(ne_a), pad_0(pad_0), pad_1(pad_1) {}
  3498. ggml_tensor * build_graph(ggml_context * ctx) override {
  3499. ggml_tensor * a = ggml_new_tensor(ctx, type, 2, ne_a.data());
  3500. ggml_set_name(a, "a");
  3501. ggml_tensor * out = ggml_pad_reflect_1d(ctx, a, pad_0, pad_1);
  3502. ggml_set_name(out, "out");
  3503. return out;
  3504. }
  3505. };
  3506. // GGML_OP_ROLL
  3507. struct test_roll : public test_case {
  3508. const int shift0;
  3509. const int shift1;
  3510. const int shift3;
  3511. const int shift4;
  3512. std::string vars() override {
  3513. return VARS_TO_STR4(shift0, shift1, shift3, shift4);
  3514. }
  3515. test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1)
  3516. : shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4) {}
  3517. ggml_tensor * build_graph(ggml_context * ctx) override {
  3518. int64_t ne[4] = {10, 5, 4, 3};
  3519. ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
  3520. ggml_set_name(a, "a");
  3521. ggml_tensor * out = ggml_roll(ctx, a, shift0, shift1, shift3, shift4);
  3522. ggml_set_name(out, "out");
  3523. return out;
  3524. }
  3525. };
  3526. // GGML_OP_ARANGE
  3527. struct test_arange : public test_case {
  3528. const ggml_type type;
  3529. const float start;
  3530. const float stop;
  3531. const float step;
  3532. std::string vars() override {
  3533. return VARS_TO_STR4(type, start, stop, step);
  3534. }
  3535. test_arange(ggml_type type = GGML_TYPE_F32,
  3536. float start = 0.f, float stop = 10.f, float step = 1.f)
  3537. : type(type), start(start), stop(stop), step(step) {}
  3538. ggml_tensor * build_graph(ggml_context * ctx) override {
  3539. ggml_tensor * out = ggml_arange(ctx, start, stop, step);
  3540. ggml_set_name(out, "out");
  3541. return out;
  3542. }
  3543. };
  3544. // GGML_OP_TIMESTEP_EMBEDDING
  3545. struct test_timestep_embedding : public test_case {
  3546. const ggml_type type;
  3547. const std::array<int64_t, 4> ne_a;
  3548. const int dim;
  3549. const int max_period;
  3550. std::string vars() override {
  3551. return VARS_TO_STR4(type, ne_a, dim, max_period);
  3552. }
  3553. test_timestep_embedding(ggml_type type = GGML_TYPE_F32,
  3554. std::array<int64_t, 4> ne_a = {2, 1, 1, 1},
  3555. int dim = 320, int max_period=10000)
  3556. : type(type), ne_a(ne_a), dim(dim), max_period(max_period) {}
  3557. ggml_tensor * build_graph(ggml_context * ctx) override {
  3558. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  3559. ggml_set_name(a, "a");
  3560. ggml_tensor * out = ggml_timestep_embedding(ctx, a, dim, max_period);
  3561. ggml_set_name(out, "out");
  3562. return out;
  3563. }
  3564. };
  3565. // GGML_OP_LEAKY_RELU
  3566. struct test_leaky_relu : public test_case {
  3567. const ggml_type type;
  3568. const std::array<int64_t, 4> ne_a;
  3569. const float negative_slope;
  3570. std::string vars() override {
  3571. return VARS_TO_STR3(type, ne_a, negative_slope);
  3572. }
  3573. test_leaky_relu(ggml_type type = GGML_TYPE_F32,
  3574. std::array<int64_t, 4> ne_a = {10, 5, 4, 3},
  3575. float negative_slope = 0.1f)
  3576. : type(type), ne_a(ne_a), negative_slope(negative_slope) {}
  3577. ggml_tensor * build_graph(ggml_context * ctx) override {
  3578. ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data());
  3579. ggml_set_name(a, "a");
  3580. ggml_tensor * out = ggml_leaky_relu(ctx, a, negative_slope, true);
  3581. ggml_set_name(out, "out");
  3582. return out;
  3583. }
  3584. };
  3585. // GGML_OP_FLASH_ATTN_EXT
  3586. struct test_flash_attn_ext : public test_case {
  3587. const int64_t hsk; // K head size
  3588. const int64_t hsv; // V head size
  3589. const int64_t nh; // num heads
  3590. const std::array<int64_t, 2> nr23; // repeat in dim 2 and 3, tests for grouped-query attention
  3591. const int64_t kv; // kv size
  3592. const int64_t nb; // batch size
  3593. const bool mask; // use mask
  3594. const float max_bias; // ALiBi
  3595. const float logit_softcap; // Gemma 2
  3596. const ggml_prec prec;
  3597. const ggml_type type_KV;
  3598. std::array<int32_t, 4> permute;
  3599. std::string vars() override {
  3600. return VARS_TO_STR12(hsk, hsv, nh, nr23, kv, nb, mask, max_bias, logit_softcap, prec, type_KV, permute);
  3601. }
  3602. double max_nmse_err() override {
  3603. return 5e-4;
  3604. }
  3605. uint64_t op_flops(ggml_tensor * t) override {
  3606. GGML_UNUSED(t);
  3607. // Just counting matmul costs:
  3608. // Q*K^T is nb x hsk x kv, P*V is nb x kv x hsv, per head
  3609. return (2 * nh*nr23[0] * nb * (hsk + hsv) * kv)*nr23[1];
  3610. }
  3611. test_flash_attn_ext(int64_t hsk = 128, int64_t hsv = 128, int64_t nh = 32, std::array<int64_t, 2> nr23 = {1, 1}, int64_t kv = 96, int64_t nb = 8,
  3612. bool mask = true, float max_bias = 0.0f, float logit_softcap = 0.0f, ggml_prec prec = GGML_PREC_F32,
  3613. ggml_type type_KV = GGML_TYPE_F16, std::array<int32_t, 4> permute = {0, 1, 2, 3})
  3614. : hsk(hsk), hsv(hsv), nh(nh), nr23(nr23), kv(kv), nb(nb), mask(mask), max_bias(max_bias), logit_softcap(logit_softcap), prec(prec), type_KV(type_KV), permute(permute) {}
  3615. ggml_tensor * build_graph(ggml_context * ctx) override {
  3616. const int64_t hsk_padded = GGML_PAD(hsk, ggml_blck_size(type_KV));
  3617. const int64_t hsv_padded = GGML_PAD(hsv, ggml_blck_size(type_KV));
  3618. auto const &create_permuted = [&](ggml_type type, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, bool is_view) -> ggml_tensor * {
  3619. int64_t ne[4] = {ne0, ne1, ne2, ne3};
  3620. int64_t ne_perm[4];
  3621. for (int i = 0; i < 4; ++i) {
  3622. ne_perm[permute[i]] = ne[i];
  3623. }
  3624. ggml_tensor * t;
  3625. if (is_view) {
  3626. ggml_tensor * t0 = ggml_new_tensor_4d(ctx, type, ne_perm[0], 2*ne_perm[1], ne_perm[2], ne_perm[3]);
  3627. t = ggml_view_4d(ctx, t0, ne_perm[0], ne_perm[1], ne_perm[2], ne_perm[3], t0->nb[1], t0->nb[2], t0->nb[3], 0);
  3628. } else {
  3629. t = ggml_new_tensor_4d(ctx, type, ne_perm[0], ne_perm[1], ne_perm[2], ne_perm[3]);
  3630. }
  3631. if (permute != std::array<int32_t, 4>{0, 1, 2, 3}) {
  3632. t = ggml_permute(ctx, t, permute[0], permute[1], permute[2], permute[3]);
  3633. }
  3634. return t;
  3635. };
  3636. ggml_tensor * q = create_permuted(GGML_TYPE_F32, hsk_padded, nb, nh*nr23[0], nr23[1], false);
  3637. ggml_set_name(q, "q");
  3638. ggml_tensor * k = create_permuted(type_KV, hsk_padded, kv, nh, nr23[1], true); // the K tensor is usually a view of the K cache
  3639. ggml_set_name(k, "k");
  3640. ggml_tensor * v = create_permuted(type_KV, hsv_padded, kv, nh, nr23[1], true); // the V tensor is usually a view of the V cache
  3641. ggml_set_name(v, "v");
  3642. ggml_tensor * m = nullptr;
  3643. if (mask) {
  3644. m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, GGML_PAD(nb, GGML_KQ_MASK_PAD), 1, nr23[1]);
  3645. ggml_set_name(m, "m");
  3646. }
  3647. ggml_tensor * out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/sqrtf(hsk), max_bias, logit_softcap);
  3648. ggml_flash_attn_ext_set_prec(out, prec);
  3649. ggml_set_name(out, "out");
  3650. return out;
  3651. }
  3652. bool grad_precise() override {
  3653. return true;
  3654. }
  3655. };
  3656. // GGML_OP_CROSS_ENTROPY_LOSS
  3657. struct test_cross_entropy_loss : public test_case {
  3658. const ggml_type type;
  3659. const std::array<int64_t, 4> ne;
  3660. std::string vars() override {
  3661. return VARS_TO_STR2(type, ne);
  3662. }
  3663. test_cross_entropy_loss(ggml_type type = GGML_TYPE_F32,
  3664. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3665. : type(type), ne(ne) {}
  3666. ggml_tensor * build_graph(ggml_context * ctx) override {
  3667. ggml_tensor * logits = ggml_new_tensor(ctx, type, 4, ne.data());
  3668. ggml_set_param(logits);
  3669. ggml_set_name(logits, "logits");
  3670. ggml_tensor * labels = ggml_new_tensor(ctx, type, 4, ne.data());
  3671. // The labels are assumed to be constant -> no gradients.
  3672. ggml_set_name(labels, "labels");
  3673. // Ensure labels add up to 1:
  3674. labels = ggml_soft_max(ctx, labels);
  3675. ggml_set_name(labels, "labels_normalized");
  3676. ggml_tensor * out = ggml_cross_entropy_loss(ctx, logits, labels);
  3677. ggml_set_name(out, "out");
  3678. return out;
  3679. }
  3680. void initialize_tensors(ggml_context * ctx) override {
  3681. // For larger abs. diffs between logits softmax is more linear, therefore more precise num. gradients.
  3682. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  3683. init_tensor_uniform(t, -100.0f, 100.0f);
  3684. }
  3685. }
  3686. float grad_eps() override {
  3687. return 1.0f;
  3688. }
  3689. bool grad_precise() override {
  3690. return true;
  3691. }
  3692. };
  3693. // GGML_OP_CROSS_ENTROPY_LOSS_BACK
  3694. struct test_cross_entropy_loss_back : public test_case {
  3695. const ggml_type type;
  3696. const std::array<int64_t, 4> ne;
  3697. std::string vars() override {
  3698. return VARS_TO_STR2(type, ne);
  3699. }
  3700. test_cross_entropy_loss_back(ggml_type type = GGML_TYPE_F32,
  3701. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3702. : type(type), ne(ne) {}
  3703. ggml_tensor * build_graph(ggml_context * ctx) override {
  3704. ggml_tensor * grad = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  3705. ggml_set_name(grad, "grad");
  3706. ggml_tensor * logits = ggml_new_tensor(ctx, type, 4, ne.data());
  3707. ggml_set_name(logits, "logits");
  3708. ggml_tensor * labels = ggml_new_tensor(ctx, type, 4, ne.data());
  3709. ggml_set_name(labels, "labels");
  3710. // Ensure labels add up to 1:
  3711. labels = ggml_soft_max(ctx, labels);
  3712. ggml_set_name(labels, "labels_normalized");
  3713. ggml_tensor * out = ggml_cross_entropy_loss_back(ctx, grad, logits, labels);
  3714. ggml_set_name(out, "out");
  3715. return out;
  3716. }
  3717. };
  3718. // GGML_OP_OPT_STEP_ADAMW
  3719. struct test_opt_step_adamw : public test_case {
  3720. const ggml_type type;
  3721. const std::array<int64_t, 4> ne;
  3722. std::string vars() override {
  3723. return VARS_TO_STR2(type, ne);
  3724. }
  3725. test_opt_step_adamw(ggml_type type = GGML_TYPE_F32,
  3726. std::array<int64_t, 4> ne = {10, 5, 4, 3})
  3727. : type(type), ne(ne) {}
  3728. ggml_tensor * build_graph(ggml_context * ctx) override {
  3729. ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  3730. ggml_set_param(a); // Despite tensor a having gradients the output tensor will not.
  3731. ggml_set_name(a, "a");
  3732. ggml_tensor * grad = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  3733. ggml_set_name(grad, "grad");
  3734. ggml_tensor * grad_m = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  3735. ggml_set_name(grad_m, "grad_m");
  3736. ggml_tensor * grad_v = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]);
  3737. ggml_set_name(grad_v, "grad_v");
  3738. ggml_tensor * adamw_params = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 7);
  3739. ggml_set_name(adamw_params, "adamw_params");
  3740. ggml_tensor * out = ggml_opt_step_adamw(ctx, a, grad, grad_m, grad_v, adamw_params);
  3741. ggml_set_name(out, "out");
  3742. return out;
  3743. }
  3744. void initialize_tensors(ggml_context * ctx) override {
  3745. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  3746. init_tensor_uniform(t, 0.0f, 1.0f); // grad_v and adamw_params need non-negative values.
  3747. }
  3748. }
  3749. bool grad_precise() override {
  3750. return true;
  3751. }
  3752. };
  3753. enum llm_norm_type {
  3754. LLM_NORM,
  3755. LLM_NORM_RMS,
  3756. };
  3757. struct llama_hparams {
  3758. uint32_t n_vocab;
  3759. uint32_t n_embd;
  3760. uint32_t n_head;
  3761. uint32_t n_head_kv;
  3762. static constexpr uint32_t n_layer = 1;
  3763. uint32_t n_rot;
  3764. uint32_t n_embd_head; // dimension of values (d_v)
  3765. uint32_t n_ff;
  3766. float f_norm_eps;
  3767. float f_norm_rms_eps;
  3768. // cparams
  3769. static constexpr uint32_t n_ctx = 512; // user-specified context size
  3770. static constexpr uint32_t n_ctx_orig = n_ctx;
  3771. // batch
  3772. int32_t n_tokens;
  3773. // llm_build_context
  3774. static constexpr int32_t n_kv = 32; // size of KV cache to consider (n_kv <= n_ctx
  3775. static constexpr int32_t kv_head = 1; // index of where we store new KV data in the cache
  3776. uint32_t n_embd_gqa() const { // dimension of key embeddings across all k-v heads
  3777. return n_embd_head * n_head_kv;
  3778. }
  3779. };
  3780. // LLM base class
  3781. struct test_llm : public test_case {
  3782. llama_hparams hp;
  3783. protected:
  3784. test_llm(llama_hparams hp)
  3785. : hp(std::move(hp)) {
  3786. }
  3787. public:
  3788. struct ggml_tensor * llm_build_norm(
  3789. struct ggml_context * ctx,
  3790. struct ggml_tensor * cur,
  3791. struct ggml_tensor * mw,
  3792. struct ggml_tensor * mb,
  3793. llm_norm_type type) {
  3794. switch (type) {
  3795. case LLM_NORM: cur = ggml_norm (ctx, cur, hp.f_norm_eps); break;
  3796. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hp.f_norm_rms_eps); break;
  3797. }
  3798. cur = ggml_mul(ctx, cur, mw);
  3799. if (mb) {
  3800. cur = ggml_add(ctx, cur, mb);
  3801. }
  3802. return cur;
  3803. }
  3804. void llm_build_kv_store(
  3805. struct ggml_context * ctx,
  3806. struct ggml_tensor * k_l,
  3807. struct ggml_tensor * v_l,
  3808. struct ggml_tensor * k_cur,
  3809. struct ggml_tensor * v_cur) {
  3810. // compute the transposed [n_tokens, n_embd] V matrix
  3811. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, hp.n_embd_gqa(), hp.n_tokens));
  3812. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, k_l, hp.n_tokens*hp.n_embd_gqa(),
  3813. (ggml_row_size(k_l->type, hp.n_embd_gqa()))*hp.kv_head);
  3814. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, v_l, hp.n_tokens, hp.n_embd_gqa(),
  3815. ( hp.n_ctx)*ggml_element_size(v_l),
  3816. (hp.kv_head)*ggml_element_size(v_l));
  3817. // important: storing RoPE-ed version of K in the KV cache!
  3818. ggml_cpy(ctx, k_cur, k_cache_view);
  3819. ggml_cpy(ctx, v_cur_t, v_cache_view);
  3820. }
  3821. struct ggml_tensor * llm_build_kqv(
  3822. struct ggml_context * ctx,
  3823. struct ggml_tensor * k_l,
  3824. struct ggml_tensor * v_l,
  3825. struct ggml_tensor * q_cur,
  3826. struct ggml_tensor * kq_mask,
  3827. float kq_scale) {
  3828. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3829. struct ggml_tensor * k =
  3830. ggml_view_3d(ctx, k_l,
  3831. hp.n_embd_head, hp.n_kv, hp.n_head_kv,
  3832. ggml_row_size(k_l->type, hp.n_embd_gqa()),
  3833. ggml_row_size(k_l->type, hp.n_embd_head),
  3834. 0);
  3835. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3836. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale, 0.0f);
  3837. // split cached v into n_head heads
  3838. struct ggml_tensor * v =
  3839. ggml_view_3d(ctx, v_l,
  3840. hp.n_kv, hp.n_embd_head, hp.n_head_kv,
  3841. ggml_element_size(v_l)*hp.n_ctx,
  3842. ggml_element_size(v_l)*hp.n_ctx*hp.n_embd_head,
  3843. 0);
  3844. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3845. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3846. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, hp.n_embd_head*hp.n_head, hp.n_tokens);
  3847. struct ggml_tensor * wo = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd);
  3848. cur = ggml_mul_mat(ctx, wo, cur);
  3849. return cur;
  3850. }
  3851. void initialize_tensors(ggml_context * ctx) override {
  3852. for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
  3853. if (t->type == GGML_TYPE_I32) {
  3854. // pos
  3855. std::vector<int> data(hp.n_tokens);
  3856. for (int i = 0; i < hp.n_tokens; i++) {
  3857. data[i] = rand() % hp.n_ctx;
  3858. }
  3859. ggml_backend_tensor_set(t, data.data(), 0, hp.n_tokens * sizeof(int));
  3860. } else {
  3861. init_tensor_uniform(t);
  3862. }
  3863. }
  3864. }
  3865. };
  3866. // Llama
  3867. struct test_llama : public test_llm {
  3868. static constexpr float freq_base = 10000.0f;
  3869. static constexpr float freq_scale = 1.0f;
  3870. static constexpr float ext_factor = 0.0f;
  3871. static constexpr float attn_factor = 1.0f;
  3872. static constexpr float beta_fast = 32.0f;
  3873. static constexpr float beta_slow = 1.0f;
  3874. bool fused;
  3875. std::string op_desc(ggml_tensor * t) override {
  3876. GGML_UNUSED(t);
  3877. return "LLAMA";
  3878. }
  3879. std::string vars() override {
  3880. auto n_tokens = hp.n_tokens;
  3881. return VARS_TO_STR1(n_tokens);
  3882. }
  3883. double max_nmse_err() override {
  3884. return 2e-3;
  3885. }
  3886. bool run_whole_graph() override { return fused; }
  3887. test_llama(int n_tokens = 1, bool fused = false)
  3888. : test_llm({
  3889. /*n_vocab =*/ 32000,
  3890. /*n_embd =*/ 3200,
  3891. /*n_head =*/ 32,
  3892. /*n_head_kv =*/ 32,
  3893. /*n_rot =*/ 100,
  3894. /*n_embd_head =*/ 100,
  3895. /*n_ff =*/ 8640,
  3896. /*f_norm_eps =*/ 0.f,
  3897. /*f_norm_rms_eps =*/ 1e-5f,
  3898. /*n_tokens =*/ n_tokens,
  3899. })
  3900. , fused(fused)
  3901. {
  3902. }
  3903. ggml_tensor * build_graph(ggml_context * ctx) override {
  3904. struct ggml_tensor * cur;
  3905. struct ggml_tensor * inpL;
  3906. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.n_embd, hp.n_tokens);
  3907. // inp_pos - contains the positions
  3908. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, hp.n_tokens);
  3909. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3910. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, hp.n_kv, hp.n_tokens, 1);
  3911. ggml_tensor * k_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  3912. ggml_tensor * v_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  3913. for (uint32_t il = 0; il < hp.n_layer; ++il) {
  3914. struct ggml_tensor * inpSA = inpL;
  3915. // norm
  3916. ggml_tensor * attn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  3917. cur = llm_build_norm(ctx, inpL, attn_norm, nullptr, LLM_NORM_RMS);
  3918. // self-attention
  3919. {
  3920. ggml_tensor * wq = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd);
  3921. ggml_tensor * wk = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd_gqa());
  3922. ggml_tensor * wv = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd_gqa());
  3923. // compute Q and K and RoPE them
  3924. struct ggml_tensor * Qcur = ggml_mul_mat(ctx, wq, cur);
  3925. struct ggml_tensor * Kcur = ggml_mul_mat(ctx, wk, cur);
  3926. struct ggml_tensor * Vcur = ggml_mul_mat(ctx, wv, cur);
  3927. Qcur = ggml_rope_ext(
  3928. ctx, ggml_reshape_3d(ctx, Qcur, hp.n_embd_head, hp.n_head, hp.n_tokens), inp_pos, nullptr,
  3929. hp.n_rot, 0, hp.n_ctx_orig, freq_base, freq_scale,
  3930. ext_factor, attn_factor, beta_fast, beta_slow
  3931. );
  3932. Kcur = ggml_rope_ext(
  3933. ctx, ggml_reshape_3d(ctx, Kcur, hp.n_embd_head, hp.n_head_kv, hp.n_tokens), inp_pos, nullptr,
  3934. hp.n_rot, 0, hp.n_ctx_orig, freq_base, freq_scale,
  3935. ext_factor, attn_factor, beta_fast, beta_slow
  3936. );
  3937. llm_build_kv_store(ctx, k_l, v_l, Kcur, Vcur);
  3938. cur = llm_build_kqv(ctx, k_l, v_l, Qcur, KQ_mask, 1.0f/sqrtf(float(hp.n_embd_head)));
  3939. }
  3940. struct ggml_tensor * ffn_inp = ggml_add(ctx, cur, inpSA);
  3941. // feed-forward network
  3942. ggml_tensor * ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  3943. cur = llm_build_norm(ctx, ffn_inp, ffn_norm, nullptr, LLM_NORM_RMS);
  3944. ggml_tensor * ffn_gate = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  3945. ggml_tensor * ffn_down = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_ff, hp.n_embd);
  3946. ggml_tensor * ffn_up = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  3947. struct ggml_tensor * tmp = ggml_mul_mat(ctx, ffn_up, cur);
  3948. cur = ggml_mul_mat(ctx, ffn_gate, cur);
  3949. cur = ggml_silu(ctx, cur);
  3950. cur = ggml_mul(ctx, cur, tmp);
  3951. cur = ggml_mul_mat(ctx, ffn_down, cur);
  3952. cur = ggml_add(ctx, cur, ffn_inp);
  3953. // input for next layer
  3954. inpL = cur;
  3955. }
  3956. cur = inpL;
  3957. ggml_tensor * output_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  3958. cur = llm_build_norm(ctx, cur, output_norm, nullptr, LLM_NORM_RMS);
  3959. // lm_head
  3960. ggml_tensor * output = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_vocab);
  3961. cur = ggml_mul_mat(ctx, output, cur);
  3962. return cur;
  3963. }
  3964. };
  3965. // Falcon
  3966. struct test_falcon : public test_llm {
  3967. static constexpr float freq_base = 10000.0f;
  3968. static constexpr float freq_scale = 1.0f;
  3969. static constexpr float ext_factor = 0.0f;
  3970. static constexpr float attn_factor = 1.0f;
  3971. static constexpr float beta_fast = 32.0f;
  3972. static constexpr float beta_slow = 1.0f;
  3973. std::string op_desc(ggml_tensor * t) override {
  3974. GGML_UNUSED(t);
  3975. return "FALCON";
  3976. }
  3977. std::string vars() override {
  3978. auto n_tokens = hp.n_tokens;
  3979. return VARS_TO_STR1(n_tokens);
  3980. }
  3981. double max_nmse_err() override {
  3982. return 2e-3;
  3983. }
  3984. test_falcon(int n_tokens = 1)
  3985. : test_llm({
  3986. /*n_vocab =*/ 32000,
  3987. /*n_embd =*/ 3200,
  3988. /*n_head =*/ 50,
  3989. /*n_head_kv =*/ 1,
  3990. /*n_rot =*/ 64,
  3991. /*n_embd_head =*/ 64,
  3992. /*n_ff =*/ 8640,
  3993. /*f_norm_eps =*/ 1e-5f,
  3994. /*f_norm_rms_eps =*/ 0.f,
  3995. /*n_tokens =*/ n_tokens,
  3996. }) {
  3997. }
  3998. ggml_tensor * build_graph(ggml_context * ctx) override {
  3999. struct ggml_tensor * cur;
  4000. struct ggml_tensor * inpL;
  4001. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, hp.n_embd, hp.n_tokens);
  4002. // inp_pos - contains the positions
  4003. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, hp.n_tokens);
  4004. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4005. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, hp.n_kv, hp.n_tokens, 1);
  4006. ggml_tensor * k_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  4007. ggml_tensor * v_l = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, 1638400);
  4008. for (uint32_t il = 0; il < hp.n_layer; ++il) {
  4009. // norm
  4010. ggml_tensor * attn_norm_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  4011. ggml_tensor * attn_norm_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  4012. ggml_tensor * attn_norm = llm_build_norm(ctx, inpL, attn_norm_w, attn_norm_b, LLM_NORM);
  4013. // self-attention
  4014. {
  4015. cur = attn_norm;
  4016. ggml_tensor * wqkv = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_embd + 2*hp.n_embd_gqa());
  4017. cur = ggml_mul_mat(ctx, wqkv, cur);
  4018. 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)));
  4019. 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)));
  4020. 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())));
  4021. Qcur = ggml_reshape_3d(ctx, Qcur, hp.n_embd_head, hp.n_head, hp.n_tokens);
  4022. Kcur = ggml_reshape_3d(ctx, Kcur, hp.n_embd_head, hp.n_head_kv, hp.n_tokens);
  4023. // using mode = 2 for neox mode
  4024. Qcur = ggml_rope_ext(
  4025. ctx, Qcur, inp_pos, nullptr, hp.n_rot, 2, hp.n_ctx_orig,
  4026. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4027. );
  4028. Kcur = ggml_rope_ext(
  4029. ctx, Kcur, inp_pos, nullptr, hp.n_rot, 2, hp.n_ctx_orig,
  4030. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4031. );
  4032. llm_build_kv_store(ctx, k_l, v_l, Kcur, Vcur);
  4033. cur = llm_build_kqv(ctx, k_l, v_l, Qcur, KQ_mask, 1.0f/sqrtf(float(hp.n_embd_head)));
  4034. }
  4035. struct ggml_tensor * ffn_inp = cur;
  4036. // feed forward
  4037. {
  4038. ggml_tensor * ffn_up = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_embd, hp.n_ff);
  4039. ggml_tensor * ffn_down = ggml_new_tensor_2d(ctx, GGML_TYPE_Q4_0, hp.n_ff, hp.n_embd);
  4040. cur = attn_norm;
  4041. cur = ggml_mul_mat(ctx, ffn_up, cur);
  4042. cur = ggml_gelu(ctx, cur);
  4043. cur = ggml_mul_mat(ctx, ffn_down, cur);
  4044. }
  4045. cur = ggml_add(ctx, cur, ffn_inp);
  4046. cur = ggml_add(ctx, cur, inpL);
  4047. // input for next layer
  4048. inpL = cur;
  4049. }
  4050. cur = inpL;
  4051. ggml_tensor * output_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  4052. ggml_tensor * output_norm_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, hp.n_embd);
  4053. cur = llm_build_norm(ctx, cur, output_norm, output_norm_b, LLM_NORM);
  4054. // lm_head
  4055. ggml_tensor * output = ggml_new_tensor_2d(ctx, GGML_TYPE_Q8_0, hp.n_embd, hp.n_vocab);
  4056. cur = ggml_mul_mat(ctx, output, cur);
  4057. return cur;
  4058. }
  4059. };
  4060. // ###########################################
  4061. // ## Section 3: GGML Op Test Instantiation ##
  4062. // ###########################################
  4063. static const ggml_type all_types[] = {
  4064. GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16,
  4065. GGML_TYPE_Q4_0, GGML_TYPE_Q4_1,
  4066. GGML_TYPE_Q5_0, GGML_TYPE_Q5_1,
  4067. GGML_TYPE_Q8_0,
  4068. GGML_TYPE_Q2_K, GGML_TYPE_Q3_K,
  4069. GGML_TYPE_Q4_K, GGML_TYPE_Q5_K,
  4070. GGML_TYPE_Q6_K,
  4071. // GGML_TYPE_TQ1_0, GGML_TYPE_TQ2_0, // TODO: implement for all backends
  4072. GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S,
  4073. GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M,
  4074. GGML_TYPE_IQ4_NL, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_XS,
  4075. };
  4076. static const ggml_type base_types[] = {
  4077. GGML_TYPE_F32, GGML_TYPE_F16,
  4078. GGML_TYPE_Q8_0, // for I8MM tests
  4079. GGML_TYPE_Q4_0,
  4080. GGML_TYPE_Q4_1, // for I8MM tests
  4081. GGML_TYPE_Q4_K,
  4082. GGML_TYPE_IQ2_XXS
  4083. };
  4084. static const ggml_type other_types[] = {
  4085. GGML_TYPE_Q4_1,
  4086. GGML_TYPE_Q5_0, GGML_TYPE_Q5_1,
  4087. GGML_TYPE_Q8_0,
  4088. GGML_TYPE_Q2_K, GGML_TYPE_Q3_K,
  4089. GGML_TYPE_Q5_K,
  4090. GGML_TYPE_Q6_K,
  4091. // GGML_TYPE_TQ1_0, GGML_TYPE_TQ2_0, // TODO: implement for all backends
  4092. GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S,
  4093. GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M,
  4094. GGML_TYPE_IQ4_NL, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_XS,
  4095. GGML_TYPE_BF16,
  4096. };
  4097. // Test cases for evaluation: should try to cover edge cases while using small input sizes to keep the runtime low
  4098. static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
  4099. std::vector<std::unique_ptr<test_case>> test_cases;
  4100. std::default_random_engine rng(0);
  4101. // unary ops
  4102. for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4103. for (int v : {0, 1}) {
  4104. for (int op = 0; op < GGML_UNARY_OP_COUNT; op++) {
  4105. test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 128, 2, 2, 2 }, v));
  4106. test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 5, 7, 11, 13 }, v));
  4107. }
  4108. }
  4109. }
  4110. // glu ops
  4111. for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4112. for (int v : {0, 1}) {
  4113. for (int op = 0; op < GGML_GLU_OP_COUNT; op++) {
  4114. for (bool swapped : {false, true}) {
  4115. test_cases.emplace_back(new test_glu((ggml_glu_op) op, type, { 128, 2, 2, 2 }, v, swapped));
  4116. test_cases.emplace_back(new test_glu((ggml_glu_op) op, type, { 5, 7, 11, 13 }, v, swapped));
  4117. }
  4118. test_cases.emplace_back(new test_glu_split((ggml_glu_op) op, type, { 128, 2, 2, 2 }, v));
  4119. test_cases.emplace_back(new test_glu_split((ggml_glu_op) op, type, { 5, 7, 11, 13 }, v));
  4120. }
  4121. }
  4122. }
  4123. test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 1, 8, 2, 1, false));
  4124. for (ggml_type type : all_types) {
  4125. for (int b : {1, 7}) {
  4126. for (bool v : {false, true}) {
  4127. test_cases.emplace_back(new test_get_rows(type, 256, 5, 4, b, v));
  4128. }
  4129. }
  4130. }
  4131. for (int b : {1, 7}) {
  4132. for (bool v : {false, true}) {
  4133. test_cases.emplace_back(new test_get_rows(GGML_TYPE_I32, 256, 5, 4, b, v));
  4134. }
  4135. }
  4136. test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_F32, 1, 8, 2, 1, false));
  4137. for (ggml_type type : all_types) {
  4138. for (bool v : {false, true}) {
  4139. test_cases.emplace_back(new test_get_rows_back(type, 256, 5, 4, 1, v));
  4140. }
  4141. }
  4142. for (bool v : {false, true}) {
  4143. test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_I32, 256, 5, 4, 1, v));
  4144. }
  4145. test_cases.emplace_back(new test_set_rows(GGML_TYPE_F32, { 1, 8, 1, 3 }, { 1, 1 }, 2, false));
  4146. for (ggml_type type : all_types) {
  4147. for (int b : {1, 7}) {
  4148. for (bool v : {false, true}) {
  4149. test_cases.emplace_back(new test_set_rows(type, { 256, 5, b, 3 }, { 1, 1, }, 1, v));
  4150. test_cases.emplace_back(new test_set_rows(type, { 256, 11, 1, b }, { 2, 3, }, 7, v));
  4151. test_cases.emplace_back(new test_set_rows(type, { 3*ggml_blck_size(type), 3, b, 1 }, { 2, 3, }, 2, v));
  4152. if (ggml_blck_size(type) == 1) {
  4153. test_cases.emplace_back(new test_set_rows(type, { 31, 3, b, 1 }, { 2, 3, }, 2, v));
  4154. test_cases.emplace_back(new test_set_rows(type, { 33, 5, 1, b }, { 2, 3, }, 1, v));
  4155. }
  4156. }
  4157. }
  4158. }
  4159. for (ggml_type type_input : {GGML_TYPE_F32}) {
  4160. for (ggml_op_pool pool_type : {GGML_OP_POOL_AVG, GGML_OP_POOL_MAX}) {
  4161. for (int k0 : {1, 3}) {
  4162. for (int k1 : {1, 3}) {
  4163. for (int s0 : {1, 2}) {
  4164. for (int s1 : {1, 2}) {
  4165. for (int p0 : {0, 1}) {
  4166. for (int p1 : {0, 1}) {
  4167. test_cases.emplace_back(new test_pool2d(pool_type, type_input, {10, 10, 3, 1}, k0, k1, s0, s1, p0, p1));
  4168. }
  4169. }
  4170. }
  4171. }
  4172. }
  4173. }
  4174. }
  4175. }
  4176. // im2col 1D
  4177. 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));
  4178. 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));
  4179. 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));
  4180. for (int s0 : {1, 3}) {
  4181. for (int p0 : {0, 3}) {
  4182. for (int d0 : {1, 3}) {
  4183. test_cases.emplace_back(new test_im2col(
  4184. GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32, {20, 2, 2, 1}, {3, 2, 2, 1},
  4185. s0, 0, p0, 0, d0, 0, false));
  4186. }
  4187. }
  4188. }
  4189. // im2col 2D
  4190. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32));
  4191. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F32));
  4192. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16));
  4193. for (int s0 : {1, 3}) {
  4194. for (int s1 : {1, 3}) {
  4195. for (int p0 : {0, 3}) {
  4196. for (int p1 : {0, 3}) {
  4197. for (int d0 : {1, 3}) {
  4198. for (int d1 : {1, 3}) {
  4199. test_cases.emplace_back(new test_im2col(
  4200. GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32, {20, 20, 2, 2}, {3, 3, 2, 2},
  4201. s0, s1, p0, p1, d0, d1, true));
  4202. }
  4203. }
  4204. }
  4205. }
  4206. }
  4207. }
  4208. // extra tests for im2col 2D
  4209. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 32}, {3, 3, 1, 32}, 1, 1, 1, 1, 1, 1, true));
  4210. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 32}, {3, 3, 2, 32}, 1, 1, 1, 1, 1, 1, true));
  4211. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 1024}, {3, 3, 1, 1024}, 1, 1, 1, 1, 1, 1, true));
  4212. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 1024}, {3, 3, 2, 1024}, 1, 1, 1, 1, 1, 1, true));
  4213. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 2048}, {3, 3, 1, 2048}, 1, 1, 1, 1, 1, 1, true));
  4214. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 2048}, {3, 3, 2, 2048}, 1, 1, 1, 1, 1, 1, true));
  4215. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 1, 2560}, {3, 3, 1, 2560}, 1, 1, 1, 1, 1, 1, true));
  4216. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {12, 12, 2, 2560}, {3, 3, 2, 2560}, 1, 1, 1, 1, 1, 1, true));
  4217. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F16, {5, 5, 1, 32}, {3, 4, 1, 32}, 1, 1, 0, 0, 1, 1, true));
  4218. // Conv_2D test cases
  4219. #ifdef DETAILED_TESTS
  4220. // Probably we do not have enough time to execute these in the pipeline.
  4221. uint32_t iwh_idx = 0;
  4222. uint32_t kwh_idx = 1;
  4223. uint32_t Cout_idx = 2;
  4224. uint32_t Cin_idx = 3;
  4225. uint32_t B_idx = 4;
  4226. std::vector<std::array<int, 5>> cases = {
  4227. //{IWH, KWH, Cout, Cin, B}
  4228. // K=CRS=NPQ=4096 conv_2d matmul performance
  4229. {19, 4, 4096, 256, 16},
  4230. // K=128, CRS=128, NPQ=4096
  4231. { 19, 4, 128, 8, 16},
  4232. // K=130, CRS=128, NPQ=4096
  4233. { 19, 4, 130, 8, 16},
  4234. // Edge case: K x CRS is small
  4235. { 19, 2, 4, 4, 16},
  4236. // A ConvNet's first layer
  4237. { 224, 3, 8, 3, 1 },
  4238. // A ConvNet's first layer with 2x2 convolution, and 1 channel
  4239. { 224, 2, 8, 1, 1 },
  4240. // A ConvNet's first layer with 2x2 convolution, and 1 channel, several images in the batch
  4241. { 224, 2, 8, 1, 8 },
  4242. // A middle layer of a ConvNet
  4243. { 58, 3, 64, 32, 1 },
  4244. // A middle layer of a ConvNet, several images in the batch
  4245. { 58, 3, 64, 32, 8 },
  4246. // A deep layer of a ConvNet, several images in the batch
  4247. { 16, 3, 256, 128, 8 }
  4248. };
  4249. for (auto kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4250. for (auto act_case : cases) {
  4251. test_cases.emplace_back(new test_conv_2d(
  4252. { act_case[iwh_idx], act_case[iwh_idx], act_case[Cin_idx], act_case[B_idx] },
  4253. { act_case[kwh_idx], act_case[kwh_idx], act_case[Cin_idx], act_case[Cout_idx] },
  4254. kernel_type, 1, 1, 0, 0, 1, 1, false));
  4255. }
  4256. }
  4257. #endif
  4258. // CONV_2D:
  4259. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  4260. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  4261. };
  4262. //uint32_t s0 = 3;
  4263. uint32_t s1 = 5;
  4264. uint32_t p0 = 5;
  4265. //uint32_t p1 = 2;
  4266. uint32_t d0 = 2;
  4267. uint32_t d1 = 4;
  4268. for (uint32_t s0 : { 1, 3 }) {
  4269. for (uint32_t p1 : { 2, 5 }) {
  4270. for (uint32_t Cin : { 1, 25 }) {
  4271. for (uint32_t Cout : { 1, 12 }) {
  4272. for (uint32_t KH : { 1, 2, 3, 11 }) {
  4273. for (uint32_t KW : { 1, 2, 3, 11 }) {
  4274. for (uint32_t H : { 1, 133 }) {
  4275. for (uint32_t W : { 1, 141 }) {
  4276. if (calc_conv_output_size(W, KW, s0, p0, d0) > 0 &&
  4277. calc_conv_output_size(H, KH, s1, p1, d1) > 0) {
  4278. for (auto kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4279. test_cases.emplace_back(new test_conv_2d(
  4280. { W, H, Cin, 2 }, { KW, KH, Cin, Cout }, kernel_type, s0, s1, p0, p1, d0, d1, false));
  4281. }
  4282. }
  4283. }
  4284. }
  4285. }
  4286. }
  4287. }
  4288. }
  4289. }
  4290. }
  4291. // sycl backend will limit task global_range < MAX_INT
  4292. // test cases for 2D im2col with large input W and H (occurs in stable-diffusion)
  4293. // however these cases need to alloc more memory which may fail in some devices (Intel Arc770, etc.)
  4294. // these cases are verified (pass) in Intel(R) Data Center GPU Max 1100 (sycl backend) and NV A30 (cuda backend)
  4295. // 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));
  4296. // 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));
  4297. test_cases.emplace_back(new test_conv_2d_dw({17, 34, 9, 1}, {3, 3, 1, 9}, 1, 0, 1, false));
  4298. test_cases.emplace_back(new test_conv_2d_dw({17, 34, 9, 1}, {3, 3, 1, 9}, 1, 0, 1, true));
  4299. test_cases.emplace_back(new test_conv_2d_dw({32, 8, 64, 1}, {3, 3, 1, 64}, 2, 1, 1, false));
  4300. test_cases.emplace_back(new test_conv_2d_dw({32, 8, 64, 1}, {3, 3, 1, 64}, 2, 1, 1, true));
  4301. for(uint32_t Cout : {1, 9}){
  4302. for(uint32_t Cin : {1, 7}){
  4303. for(uint32_t K : {1, 3, 1337}){
  4304. for(uint32_t L : {1, 2, 13}){
  4305. for(uint32_t s0: {1, 2, 3}){
  4306. test_cases.emplace_back(new test_conv_transpose_1d({L,Cin,1,1}, {K,Cout,Cin,1}, s0, 0, 1));
  4307. }
  4308. }
  4309. }
  4310. }
  4311. }
  4312. test_cases.emplace_back(new test_conv_transpose_1d());
  4313. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 3, 0, 1));
  4314. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 2, 0, 1));
  4315. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {2,3,2,1}, 1, 0, 1));
  4316. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,2,2,1}, 2, 0, 1));
  4317. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,2,2,1}, 1, 0, 1));
  4318. test_cases.emplace_back(new test_conv_transpose_1d({3,2,1,1}, {3,1,2,1}, 1, 0, 1));
  4319. test_cases.emplace_back(new test_conv_transpose_1d({2,1,1,1}, {3,1,1,1}, 1, 0, 1));
  4320. test_cases.emplace_back(new test_conv_transpose_2d({3, 2, 3, 1}, {2, 2, 1, 3}, 1));
  4321. test_cases.emplace_back(new test_conv_transpose_2d({10, 10, 9, 1}, {3, 3, 1, 9}, 2));
  4322. test_cases.emplace_back(new test_count_equal(GGML_TYPE_F32, {4, 500, 1, 1}));
  4323. test_cases.emplace_back(new test_count_equal(GGML_TYPE_F32, {4, 5000, 1, 1}));
  4324. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {32, 1, 1, 1}));
  4325. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {100, 10, 1, 1}));
  4326. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {1024, 10, 1, 1}));
  4327. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {1024, 12, 1, 1}));
  4328. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {2000, 10, 1, 1}));
  4329. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {5438, 3, 1, 1}));
  4330. for (int ne3 : {1, 3}) { // CUDA backward pass only supports ne3 == 1
  4331. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 1, 1}));
  4332. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {2, 1, 1, 1}));
  4333. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 2, 1, 1}));
  4334. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 2, 1}));
  4335. test_cases.emplace_back(new test_repeat(GGML_TYPE_F32, {10, 5, 4, ne3}, {1, 1, 1, 2}));
  4336. test_cases.emplace_back(new test_repeat(GGML_TYPE_I32, {10, 5, 4, ne3}, {2, 1, 1, 1}));
  4337. test_cases.emplace_back(new test_repeat(GGML_TYPE_I16, {10, 5, 4, ne3}, {1, 1, 1, 2}));
  4338. }
  4339. for (bool view : {false, true}) {
  4340. test_cases.emplace_back(new test_repeat_back(GGML_TYPE_F32, {8, 6, 4, 2}, {1, 1, 1, 1}, view));
  4341. test_cases.emplace_back(new test_repeat_back(GGML_TYPE_F32, {8, 6, 4, 2}, {2, 1, 1, 1}, view));
  4342. test_cases.emplace_back(new test_repeat_back(GGML_TYPE_F32, {8, 6, 4, 2}, {1, 2, 1, 1}, view));
  4343. test_cases.emplace_back(new test_repeat_back(GGML_TYPE_F32, {8, 6, 4, 2}, {1, 1, 2, 1}, view));
  4344. test_cases.emplace_back(new test_repeat_back(GGML_TYPE_F32, {8, 6, 4, 2}, {1, 1, 1, 2}, view));
  4345. }
  4346. test_cases.emplace_back(new test_dup(GGML_TYPE_F32));
  4347. test_cases.emplace_back(new test_dup(GGML_TYPE_F16));
  4348. test_cases.emplace_back(new test_dup(GGML_TYPE_I32));
  4349. test_cases.emplace_back(new test_dup(GGML_TYPE_I16));
  4350. test_cases.emplace_back(new test_dup(GGML_TYPE_F32, {10, 10, 5, 1}, {0, 2, 1, 3}));
  4351. test_cases.emplace_back(new test_dup(GGML_TYPE_F16, {10, 10, 5, 1}, {0, 2, 1, 3})); // dup by rows
  4352. test_cases.emplace_back(new test_dup(GGML_TYPE_F32, {10, 10, 5, 1}, {1, 0, 2, 3}));
  4353. test_cases.emplace_back(new test_dup(GGML_TYPE_F16, {10, 10, 5, 1}, {1, 0, 2, 3})); // dup dst not-contiguous
  4354. test_cases.emplace_back(new test_dup(GGML_TYPE_I16, {10, 8, 3, 1}, {0, 2, 1, 3}));
  4355. test_cases.emplace_back(new test_dup(GGML_TYPE_I16, {10, 8, 3, 1}, {1, 2, 0, 3}));
  4356. for (int dim = 1; dim < GGML_MAX_DIMS; ++dim) {
  4357. test_cases.emplace_back(new test_set(GGML_TYPE_F32, GGML_TYPE_F32, {6, 5, 4, 3}, dim));
  4358. }
  4359. for (int dim = 1; dim < GGML_MAX_DIMS; ++dim) {
  4360. test_cases.emplace_back(new test_set(GGML_TYPE_I32, GGML_TYPE_I32, {6, 5, 4, 3}, dim));
  4361. }
  4362. // same-type copy
  4363. for (ggml_type type : all_types) {
  4364. const auto nk = ggml_blck_size(type);
  4365. for (int k = 1; k < 4; ++k) {
  4366. test_cases.emplace_back(new test_cpy(type, type, {k*nk, 2, 3, 4}));
  4367. test_cases.emplace_back(new test_cpy(type, type, {k*nk, 2, 3, 4}, {0, 2, 1, 3}));
  4368. test_cases.emplace_back(new test_cpy(type, type, {k*nk, 2, 3, 4}, {0, 3, 1, 2}, {0, 2, 1, 3}));
  4369. }
  4370. }
  4371. for (ggml_type type_src : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F32}) {
  4372. for (ggml_type type_dst : all_types) {
  4373. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 4, 4, 4}));
  4374. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 2, 3, 4}, {0, 2, 1, 3})); // cpy by rows
  4375. }
  4376. }
  4377. for (ggml_type type_src : all_types) {
  4378. for (ggml_type type_dst : {GGML_TYPE_F32}) {
  4379. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 4, 4, 4}));
  4380. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 2, 3, 4}, {0, 2, 1, 3})); // cpy by rows
  4381. }
  4382. }
  4383. for (ggml_type type_src : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4384. for (ggml_type type_dst : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4385. test_cases.emplace_back(new test_cpy(type_src, type_dst, {256, 2, 3, 4}, {1, 0, 2, 3})); // cpy not-contiguous
  4386. }
  4387. }
  4388. test_cases.emplace_back(new test_cont());
  4389. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 1, 1 ,1}));
  4390. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 1, 3 ,5}));
  4391. test_cases.emplace_back(new test_cont(GGML_TYPE_F32, {2, 3, 5 ,7}));
  4392. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 1, 1 ,1}));
  4393. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 1, 3 ,5}));
  4394. test_cases.emplace_back(new test_cont(GGML_TYPE_F16, {2, 3, 5 ,7}));
  4395. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 1, 1 ,1}));
  4396. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 1, 3 ,5}));
  4397. test_cases.emplace_back(new test_cont(GGML_TYPE_BF16, {2, 3, 5 ,7}));
  4398. auto add_test_bin_bcast = [&](ggml_type type, std::array<int64_t, 4> ne, std::array<int, 4> nr) {
  4399. for (auto op : {ggml_add, ggml_sub, ggml_mul, ggml_div}) {
  4400. test_cases.emplace_back(new test_bin_bcast(op, type, ne, nr));
  4401. }
  4402. };
  4403. for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4404. add_test_bin_bcast(type, {1, 1, 8, 1}, {1, 1, 1, 1});
  4405. add_test_bin_bcast(type, {1, 1, 1, 1}, {32, 1, 1, 1});
  4406. add_test_bin_bcast(type, {1, 1, 320, 320}, {1, 1, 1, 1});
  4407. add_test_bin_bcast(type, {10, 5, 1, 1}, {1, 1, 1, 1});
  4408. add_test_bin_bcast(type, {10, 5, 4, 1}, {1, 1, 1, 1});
  4409. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 1, 1, 1});
  4410. add_test_bin_bcast(type, {10, 5, 4, 3}, {2, 1, 1, 1});
  4411. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 2, 1, 1});
  4412. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 1, 2, 1});
  4413. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 1, 1, 2});
  4414. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 1, 2, 2});
  4415. add_test_bin_bcast(type, {10, 5, 4, 3}, {1, 2, 2, 2});
  4416. add_test_bin_bcast(type, {10, 5, 4, 3}, {2, 2, 2, 2});
  4417. // stable diffusion
  4418. add_test_bin_bcast(type, {1280, 1, 1, 1}, {1, 1, 1, 1});
  4419. add_test_bin_bcast(type, {1280, 1, 1, 1}, {1, 16, 16, 1});
  4420. add_test_bin_bcast(type, {1280, 16, 16, 1}, {1, 1, 1, 1});
  4421. add_test_bin_bcast(type, {1280, 1, 1, 1}, {1, 256, 1, 1});
  4422. add_test_bin_bcast(type, {1, 1, 1280, 1}, {16, 16, 1, 1});
  4423. add_test_bin_bcast(type, {16, 16, 1280, 1}, {1, 1, 1, 1});
  4424. add_test_bin_bcast(type, {1, 1, 1920, 1}, {16, 16, 1, 1});
  4425. add_test_bin_bcast(type, {1, 1, 2560, 1}, {16, 16, 1, 1});
  4426. add_test_bin_bcast(type, {1, 1, 1280, 1}, {32, 32, 1, 1});
  4427. add_test_bin_bcast(type, {1, 1, 1920, 1}, {32, 32, 1, 1});
  4428. add_test_bin_bcast(type, {1, 1, 640, 1}, {32, 32, 1, 1});
  4429. add_test_bin_bcast(type, {5120, 1, 1, 1}, {1, 256, 1, 1});
  4430. add_test_bin_bcast(type, {640, 1, 1, 1}, {1, 1, 1, 1});
  4431. //add_test_bin_bcast(type, {3, 3, 2560, 1280}, {1, 1, 1, 1});
  4432. //add_test_bin_bcast(type, {3, 3, 2560, 1280}, {2, 1, 1, 1});
  4433. }
  4434. // fusion
  4435. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {10, 5, 4, 3}, {2, 1, 1, 1}, 2));
  4436. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {16, 5, 4, 3}, {1, 2, 1, 1}, 3));
  4437. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 2, 1}, 4));
  4438. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {16, 5, 4, 3}, {1, 1, 1, 2}, 5));
  4439. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {10, 5, 4, 3}, {1, 1, 2, 2}, 6));
  4440. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {10, 5, 4, 3}, {1, 2, 2, 2}, 7));
  4441. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {16, 5, 4, 3}, {2, 2, 2, 2}, 8));
  4442. test_cases.emplace_back(new test_add1());
  4443. test_cases.emplace_back(new test_scale());
  4444. test_cases.emplace_back(new test_scale(GGML_TYPE_F32, {10, 10, 10, 10}, 2.0f, 1.0f));
  4445. test_cases.emplace_back(new test_silu_back());
  4446. for (float eps : {0.0f, 1e-6f, 1e-4f, 1e-1f}) {
  4447. for (bool v : {false, true}) {
  4448. test_cases.emplace_back(new test_norm (GGML_TYPE_F32, {64, 5, 4, 3}, v, eps));
  4449. test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {64, 5, 4, 3}, v, eps));
  4450. }
  4451. test_cases.emplace_back(new test_rms_norm_back(GGML_TYPE_F32, {64, 5, 4, 3}, eps));
  4452. test_cases.emplace_back(new test_l2_norm (GGML_TYPE_F32, {64, 5, 4, 3}, eps));
  4453. }
  4454. for (float eps : {0.0f, 1e-6f, 1e-4f, 1e-1f, 1.0f}) {
  4455. test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {64, 5, 4, 3}, eps));
  4456. test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {64, 5, 4, 3}, eps, true));
  4457. }
  4458. test_cases.emplace_back(new test_l2_norm(GGML_TYPE_F32, {64, 5, 4, 3}, 1e-12f));
  4459. for (int64_t d_conv : {3, 4}) {
  4460. for (int64_t d_inner: {1024, 1536, 2048}) {
  4461. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, d_inner, 1, 1}, {d_conv, d_inner, 1, 1}));
  4462. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {8, d_inner, 1, 1}, {d_conv, d_inner, 1, 1}));
  4463. test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, d_inner, 4, 1}, {d_conv, d_inner, 1, 1}));
  4464. }
  4465. }
  4466. test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 16, 1, 1024, 1, 32, 4)); // Mamba-1
  4467. test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 32, 4)); // Mamba-2
  4468. test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 32, 4)); // Falcon-H1
  4469. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 1, 1));
  4470. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 32, 1));
  4471. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 32, 4));
  4472. test_cases.emplace_back(new test_rwkv_wkv6(GGML_TYPE_F32, 32, 64, 128, 4));
  4473. test_cases.emplace_back(new test_rwkv_wkv7(GGML_TYPE_F32, 32, 64, 1, 1));
  4474. test_cases.emplace_back(new test_rwkv_wkv7(GGML_TYPE_F32, 32, 64, 32, 1));
  4475. test_cases.emplace_back(new test_rwkv_wkv7(GGML_TYPE_F32, 32, 64, 32, 4));
  4476. test_cases.emplace_back(new test_rwkv_wkv7(GGML_TYPE_F32, 32, 64, 128, 4));
  4477. test_cases.emplace_back(new test_gla(GGML_TYPE_F32, 32, 64, 1, 1));
  4478. test_cases.emplace_back(new test_gla(GGML_TYPE_F32, 32, 64, 32, 1));
  4479. test_cases.emplace_back(new test_gla(GGML_TYPE_F32, 32, 64, 32, 4));
  4480. test_cases.emplace_back(new test_gla(GGML_TYPE_F32, 32, 64, 128, 4));
  4481. for (ggml_type type_a : all_types) {
  4482. for (int i = 1; i < 10; ++i) {
  4483. test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 16, i, 256, { 1, 1}, {1, 1}));
  4484. }
  4485. }
  4486. #if 1
  4487. for (ggml_type type_a : base_types) {
  4488. for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4489. std::vector<int> ks = { 256 };
  4490. if (ggml_blck_size(type_a) == 1) {
  4491. ks.push_back(4);
  4492. }
  4493. for (auto k : ks) {
  4494. // test cases without permutation
  4495. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {1, 1}, {1, 1}));
  4496. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {1, 1}, {2, 1}));
  4497. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {1, 1}, {1, 2}));
  4498. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 1}, {1, 1}));
  4499. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 1}, {2, 1}));
  4500. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 2}, {1, 1}));
  4501. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 2}, {2, 1}));
  4502. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 2}, {1, 2}));
  4503. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {3, 2}, {2, 2}));
  4504. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {1, 1}, {1, 1}));
  4505. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {1, 1}, {2, 1}));
  4506. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {1, 1}, {1, 2}));
  4507. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 1}, {1, 1}));
  4508. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 1}, {2, 1}));
  4509. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 2}, {1, 1}));
  4510. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 2}, {2, 1}));
  4511. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 2}, {1, 2}));
  4512. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {3, 2}, {2, 2}));
  4513. // test cases with permutation
  4514. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  4515. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  4516. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, k, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  4517. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, k, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  4518. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, k, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  4519. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, k, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  4520. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {2, 3}, {1, 1}, {0, 2, 1, 3}));
  4521. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {2, 3}, {1, 1}, {0, 1, 3, 2}));
  4522. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, k, {2, 3}, {1, 1}, {0, 3, 2, 1}));
  4523. }
  4524. // test cases with large ne00/ne10 to cover stream-k fixup
  4525. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 1024, {3, 2}, {1, 1}));
  4526. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 8, 1024, {3, 2}, {1, 1}));
  4527. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 16, 1024, {3, 2}, {1, 1}));
  4528. }
  4529. }
  4530. for (ggml_type type_a : other_types) {
  4531. for (ggml_type type_b : {GGML_TYPE_F32}) {
  4532. if (ggml_blck_size(type_a) != 256) {
  4533. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, ggml_blck_size(type_a), {1, 1}, {1, 1}));
  4534. }
  4535. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 16, 1, 256, {1, 1}, {1, 1}));
  4536. }
  4537. }
  4538. #else
  4539. // m = a rows
  4540. // n = b rows
  4541. // k = cols
  4542. std::uniform_int_distribution<> dist_m(1, 128);
  4543. std::uniform_int_distribution<> dist_n(16, 128);
  4544. std::uniform_int_distribution<> dist_k(1, 16);
  4545. for (int i = 0; i < 1000; i++) {
  4546. for (ggml_type type_a : all_types) {
  4547. for (ggml_type type_b : {GGML_TYPE_F32}) {
  4548. int m = dist_m(rng);
  4549. int n = dist_n(rng);
  4550. int k = dist_k(rng) * ggml_blck_size(type_a);
  4551. test_cases.emplace_back(new test_mul_mat(type_a, type_b, m, n, k, { 1, 1}, {1, 1}));
  4552. }
  4553. }
  4554. }
  4555. #endif
  4556. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 2, 128, { 8, 1}, {1, 1}));
  4557. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 83, 2, 128, { 8, 1}, {4, 1}));
  4558. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 2, 64, { 8, 1}, {4, 1}));
  4559. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 83, 2, 64, { 8, 1}, {4, 1}));
  4560. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 64, 45, 128, { 8, 1}, {4, 1}));
  4561. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 128, 45, 64, { 8, 1}, {4, 1}));
  4562. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 1056, 1, 193, {1, 1}, {4, 1}, {0, 2, 1, 3}));
  4563. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 1056, 1, 67, {1, 1}, {4, 1}, {0, 2, 1, 3}));
  4564. for (auto bs : {1,2,4,8}) {
  4565. for (auto nr : {1,4}) {
  4566. for (uint32_t m = 0; m < 2; ++m) {
  4567. for (uint32_t k = 0; k < 2; ++k) {
  4568. for (ggml_type type: {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F32}) {
  4569. test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 1056 + m, 1, 128 + k, {bs, 1}, {nr, 1}, {0, 2, 1, 3}));
  4570. test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 128 + m, 1, 1056 + k, {bs, 1}, {nr, 1}, {0, 1, 2, 3}, true));
  4571. }
  4572. }
  4573. }
  4574. }
  4575. }
  4576. // sycl backend will limit task global_range < MAX_INT
  4577. // test case for f16-type-convert-to-fp32 kernel with large k under fp32 compute dtype (occurs in stable-diffusion)
  4578. // however this case needs to alloc more memory which may fail in some devices (Intel Arc770, etc.)
  4579. // this case is verified (pass) in Intel(R) Data Center GPU Max 1100 (sycl backend) and NV A30 (cuda backend)
  4580. // test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F16, 512, 262144, 9216, {1, 1}, {1, 1}));
  4581. // test large experts*tokens
  4582. for (bool b : {false, true}) {
  4583. test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_F32, 16, 16, b, 32, 1024, 16));
  4584. }
  4585. for (ggml_type type_a : base_types) {
  4586. for (ggml_type type_b : {GGML_TYPE_F32 /*, GGML_TYPE_F16 */}) {
  4587. for (int n_mats : {4, 8}) {
  4588. for (int n_used : {1, 2, 4}) {
  4589. for (bool b : {false, true}) {
  4590. for (int n : {1, 32, 129}) {
  4591. int m = 512;
  4592. int k = 256;
  4593. test_cases.emplace_back(new test_mul_mat_id(type_a, type_b, n_mats, n_used, b, m, n, k));
  4594. }
  4595. }
  4596. }
  4597. }
  4598. }
  4599. }
  4600. for (ggml_type type_a : other_types) {
  4601. for (ggml_type type_b : {GGML_TYPE_F32 /*, GGML_TYPE_F16 */}) {
  4602. for (int n_mats : {4}) {
  4603. for (int n_used : {2}) {
  4604. for (bool b : {false}) {
  4605. for (int n : {1, 32}) {
  4606. int m = 512;
  4607. int k = 256;
  4608. test_cases.emplace_back(new test_mul_mat_id(type_a, type_b, n_mats, n_used, b, m, n, k));
  4609. }
  4610. }
  4611. }
  4612. }
  4613. }
  4614. }
  4615. for (ggml_type type_a : base_types) {
  4616. for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4617. for (int n : {1, 16}) {
  4618. for (int k : {1, 16}) {
  4619. for (int bs2 : {1, 3}) {
  4620. for (int bs3 : {1, 3}) {
  4621. for (int nr2 : {1, 2}) {
  4622. for (int nr3 : {1, 2}) {
  4623. test_cases.emplace_back(new test_out_prod(type_a, type_b, 256, n, k, {bs2, bs3}, {nr2, nr3}));
  4624. }
  4625. }
  4626. }
  4627. }
  4628. }
  4629. }
  4630. }
  4631. }
  4632. for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) {
  4633. test_cases.emplace_back(new test_sqr(type));
  4634. test_cases.emplace_back(new test_sqrt(type));
  4635. test_cases.emplace_back(new test_log(type));
  4636. test_cases.emplace_back(new test_sin(type));
  4637. test_cases.emplace_back(new test_cos(type));
  4638. test_cases.emplace_back(new test_clamp(type));
  4639. }
  4640. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 1, 1}, 5));
  4641. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 1}, 5));
  4642. test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 2}, 5));
  4643. #if 0
  4644. std::uniform_int_distribution<> dist_ne1(1, 50);
  4645. int exponent = 1;
  4646. while (exponent < (1 << 17)) {
  4647. std::uniform_int_distribution<> dist_ne0(exponent, 2*exponent);
  4648. for (int n = 0; n < 10; ++n) {
  4649. int64_t ne0 = dist_ne0(rng);
  4650. int64_t ne1 = dist_ne1(rng);
  4651. 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));
  4652. }
  4653. exponent <<= 1;
  4654. }
  4655. #endif
  4656. for (bool mask : {false, true}) {
  4657. for (float max_bias : {0.0f, 8.0f}) {
  4658. if (!mask && max_bias > 0.0f) continue;
  4659. for (float scale : {1.0f, 0.1f}) {
  4660. for (int64_t ne0 : {16, 1024}) {
  4661. for (int64_t ne1 : {16, 1024}) {
  4662. if (mask) {
  4663. for (ggml_type m_prec : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4664. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0, ne1, 1, 1}, mask, m_prec, {1, 1}, scale, max_bias));
  4665. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0-1, ne1-1, 1, 1}, mask, m_prec, {1, 1}, scale, max_bias));
  4666. if (ne0 <= 32 && ne1 <= 32) {
  4667. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0, ne1, 1, 3}, mask, m_prec, {3, 1}, scale, max_bias));
  4668. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0-1, ne1-1, 1, 1}, mask, m_prec, {2, 3}, scale, max_bias));
  4669. }
  4670. }
  4671. } else {
  4672. /* The precision of mask here doesn't matter as boolean mask is false */
  4673. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0, ne1, 1, 1}, mask, GGML_TYPE_F32, {1, 1}, scale, max_bias));
  4674. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0-1, ne1-1, 1, 1}, mask, GGML_TYPE_F32, {1, 1}, scale, max_bias));
  4675. }
  4676. }
  4677. }
  4678. }
  4679. }
  4680. }
  4681. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 2, 32, 1}, true, GGML_TYPE_F32, {1, 1}, 0.1f, 0.0f));
  4682. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 2, 32, 1}, true, GGML_TYPE_F16, {1, 1}, 0.1f, 0.0f));
  4683. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 2, 32, 1}, false, GGML_TYPE_F32, {1, 1}, 0.1f, 0.0f));
  4684. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, GGML_TYPE_F32, {1, 1}, 0.1f, 0.0f));
  4685. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, GGML_TYPE_F16, {1, 1}, 0.1f, 0.0f));
  4686. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, GGML_TYPE_F32, {1, 1}, 0.1f, 8.0f));
  4687. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {32, 2, 32, 1}, true, GGML_TYPE_F16, {1, 1}, 0.1f, 8.0f));
  4688. for (float max_bias : {0.0f, 8.0f}) {
  4689. for (float scale : {1.0f, 0.1f}) {
  4690. for (int64_t ne0 : {16, 1024}) {
  4691. for (int64_t ne1 : {16, 1024}) {
  4692. test_cases.emplace_back(new test_soft_max_back(GGML_TYPE_F32, {ne0, ne1, 1, 1}, scale, max_bias));
  4693. test_cases.emplace_back(new test_soft_max_back(GGML_TYPE_F32, {ne0-1, ne1-1, 1, 1}, scale, max_bias));
  4694. }
  4695. }
  4696. }
  4697. }
  4698. for (bool fw : {true, false}) { // fw == forward
  4699. bool all = true;
  4700. for (float fs : { 1.0f, 1.4245f }) {
  4701. for (float ef : { 0.0f, 0.7465f }) {
  4702. for (float af : { 1.0f, 1.4245f }) {
  4703. for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4704. for (bool ff : {false, true}) { // freq_factors
  4705. for (float v : { 0, 1 }) {
  4706. test_cases.emplace_back(new test_rope(type, {128, 32, 2, 1}, 128, 0, 512, fs, ef, af, ff, v, fw)); // llama 7B
  4707. if (all) {
  4708. test_cases.emplace_back(new test_rope(type, {128, 40, 2, 1}, 128, 0, 512, fs, ef, af, ff, v, fw)); // llama 13B
  4709. test_cases.emplace_back(new test_rope(type, {128, 52, 2, 1}, 128, 0, 512, fs, ef, af, ff, v, fw)); // llama 30B
  4710. test_cases.emplace_back(new test_rope(type, {128, 64, 2, 1}, 128, 0, 512, fs, ef, af, ff, v, fw)); // llama 65B
  4711. }
  4712. if (all) {
  4713. test_cases.emplace_back(new test_rope(type, { 64, 1, 2, 1}, 64, 2, 512, fs, ef, af, ff, v, fw)); // neox (falcon 7B)
  4714. test_cases.emplace_back(new test_rope(type, { 64, 71, 2, 1}, 64, 2, 512, fs, ef, af, ff, v, fw)); // neox (falcon 7B)
  4715. test_cases.emplace_back(new test_rope(type, { 64, 8, 2, 1}, 64, 2, 512, fs, ef, af, ff, v, fw)); // neox (falcon 40B)
  4716. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 20, 0, 512, fs, ef, af, ff, v, fw));
  4717. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 32, 0, 512, fs, ef, af, ff, v, fw));
  4718. test_cases.emplace_back(new test_rope(type, { 80, 32, 4, 1}, 32, 0, 512, fs, ef, af, ff, v, fw));
  4719. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 20, 2, 512, fs, ef, af, ff, v, fw)); // neox (stablelm)
  4720. test_cases.emplace_back(new test_rope(type, { 80, 32, 2, 1}, 32, 2, 512, fs, ef, af, ff, v, fw)); // neox (phi-2)
  4721. test_cases.emplace_back(new test_rope(type, { 80, 32, 4, 1}, 32, 2, 512, fs, ef, af, ff, v, fw)); // neox (phi-2)
  4722. }
  4723. if (all) {
  4724. test_cases.emplace_back(new test_rope(type, {128, 12, 2, 1}, 128, GGML_ROPE_TYPE_MROPE, 512, fs, ef, af, ff, v, fw)); // rope_multi,m-rope (qwen2vl 2B)
  4725. test_cases.emplace_back(new test_rope(type, {128, 28, 2, 1}, 128, GGML_ROPE_TYPE_MROPE, 512, fs, ef, af, ff, v, fw)); // rope_multi,m-rope (qwen2vl 7B)
  4726. test_cases.emplace_back(new test_rope(type, {128, 12, 2, 1}, 20, GGML_ROPE_TYPE_MROPE, 512, fs, ef, af, ff, v, fw));
  4727. test_cases.emplace_back(new test_rope(type, {128, 28, 2, 1}, 32, GGML_ROPE_TYPE_MROPE, 512, fs, ef, af, ff, v, fw));
  4728. test_cases.emplace_back(new test_rope(type, { 80, 16, 2, 1}, 80, GGML_ROPE_TYPE_VISION, 512, fs, ef, af, ff, v, fw)); // rope_multi,m-rope (qwen2vl ViT)
  4729. }
  4730. test_cases.emplace_back(new test_rope(type, { 64, 128, 2, 1}, 64, 2, 512, fs, ef, af, ff, v, fw)); // neox (falcon 40B)
  4731. }
  4732. }
  4733. all = false;
  4734. }
  4735. }
  4736. }
  4737. }
  4738. }
  4739. for (int v : { 0, 1, 2, 3 }) {
  4740. for (int dim : { 0, 1, 2, 3, }) {
  4741. test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {11, 12, 13, 14}, 7, dim, v));
  4742. test_cases.emplace_back(new test_concat(GGML_TYPE_I32, {11, 12, 13, 14}, 7, dim, v));
  4743. }
  4744. }
  4745. for (ggml_sort_order order : {GGML_SORT_ORDER_ASC, GGML_SORT_ORDER_DESC}) {
  4746. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {8, 1, 1, 1}, order));
  4747. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {16, 10, 10, 10}, order));
  4748. test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {60, 10, 10, 10}, order)); // qwen
  4749. }
  4750. for (ggml_scale_mode mode : {GGML_SCALE_MODE_NEAREST, GGML_SCALE_MODE_BILINEAR}) {
  4751. test_cases.emplace_back(new test_upscale(GGML_TYPE_F32, {512, 512, 3, 2}, 2, mode));
  4752. test_cases.emplace_back(new test_upscale(GGML_TYPE_F32, {512, 512, 3, 2}, 2, mode, true));
  4753. test_cases.emplace_back(new test_interpolate(GGML_TYPE_F32, {2, 5, 7, 11}, {5, 7, 11, 13}, mode));
  4754. test_cases.emplace_back(new test_interpolate(GGML_TYPE_F32, {5, 7, 11, 13}, {2, 5, 7, 11}, mode));
  4755. }
  4756. test_cases.emplace_back(new test_interpolate(GGML_TYPE_F32, {2, 5, 7, 11}, {5, 7, 11, 13}, GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ALIGN_CORNERS));
  4757. test_cases.emplace_back(new test_sum());
  4758. test_cases.emplace_back(new test_sum_rows());
  4759. test_cases.emplace_back(new test_mean());
  4760. test_cases.emplace_back(new test_group_norm(GGML_TYPE_F32, {64, 64, 320, 1}));
  4761. test_cases.emplace_back(new test_group_norm(GGML_TYPE_F32, {9, 9, 1280, 1}));
  4762. test_cases.emplace_back(new test_acc());
  4763. test_cases.emplace_back(new test_pad());
  4764. test_cases.emplace_back(new test_pad_reflect_1d());
  4765. test_cases.emplace_back(new test_roll());
  4766. test_cases.emplace_back(new test_arange());
  4767. test_cases.emplace_back(new test_timestep_embedding());
  4768. test_cases.emplace_back(new test_leaky_relu());
  4769. for (int hsk : { 64, 80, 128, 192, 256, 576 }) {
  4770. for (int hsv : { 64, 80, 128, 192, 256, 512 }) {
  4771. if (hsk != 192 && hsk != 576 && hsk != hsv) continue;
  4772. if (hsk == 192 && (hsv != 128 && hsv != 192)) continue;
  4773. if (hsk == 576 && hsv != 512) continue; // DeepSeek MLA
  4774. for (bool mask : { true, false } ) {
  4775. for (float max_bias : { 0.0f, 8.0f }) {
  4776. if (!mask && max_bias > 0.0f) continue;
  4777. for (float logit_softcap : {0.0f, 10.0f}) {
  4778. if (hsk != 128 && logit_softcap != 0.0f) continue;
  4779. for (int nh : { 4, }) {
  4780. for (int nr3 : { 1, 3, }) {
  4781. if (hsk > 64 && nr3 > 1) continue; // skip broadcast for large head sizes
  4782. for (int nr2 : { 1, 4, 16 }) {
  4783. if (nr2 == 16 && hsk != 128) continue;
  4784. for (int kv : { 512, 1024, }) {
  4785. if (nr2 != 1 && kv != 512) continue;
  4786. for (int nb : { 1, 3, 32, 35, }) {
  4787. for (ggml_prec prec : {GGML_PREC_F32, GGML_PREC_DEFAULT}) {
  4788. if (hsk != 128 && prec == GGML_PREC_DEFAULT) continue;
  4789. for (ggml_type type_KV : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
  4790. test_cases.emplace_back(new test_flash_attn_ext(
  4791. hsk, hsv, nh, {nr2, nr3}, kv, nb, mask, max_bias, logit_softcap, prec, type_KV));
  4792. // run fewer test cases permuted
  4793. if (mask == true && max_bias == 0.0f && logit_softcap == 0 && kv == 512) {
  4794. test_cases.emplace_back(new test_flash_attn_ext(
  4795. hsk, hsv, nh, {nr2, nr3}, kv, nb, mask, max_bias, logit_softcap, prec, type_KV, {0, 2, 1, 3}));
  4796. }
  4797. }
  4798. }
  4799. }
  4800. }
  4801. }
  4802. }
  4803. }
  4804. }
  4805. }
  4806. }
  4807. }
  4808. }
  4809. test_cases.emplace_back(new test_cross_entropy_loss (GGML_TYPE_F32, { 10, 5, 4, 3}));
  4810. test_cases.emplace_back(new test_cross_entropy_loss (GGML_TYPE_F32, {30000, 1, 1, 1}));
  4811. test_cases.emplace_back(new test_cross_entropy_loss_back(GGML_TYPE_F32, { 10, 5, 4, 3}));
  4812. test_cases.emplace_back(new test_cross_entropy_loss_back(GGML_TYPE_F32, {30000, 1, 1, 1}));
  4813. test_cases.emplace_back(new test_opt_step_adamw(GGML_TYPE_F32, {10, 5, 4, 3}));
  4814. #if 0
  4815. // these tests are disabled to save execution time, sbut they can be handy for debugging
  4816. test_cases.emplace_back(new test_llama(2, true));
  4817. test_cases.emplace_back(new test_llama(1));
  4818. test_cases.emplace_back(new test_llama(2));
  4819. test_cases.emplace_back(new test_falcon(1));
  4820. test_cases.emplace_back(new test_falcon(2));
  4821. #endif
  4822. return test_cases;
  4823. }
  4824. // Test cases for performance evaluation: should be representative of real-world use cases
  4825. static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
  4826. std::vector<std::unique_ptr<test_case>> test_cases;
  4827. // Conv2d: K=CRS=NPQ=4096 matmul performance
  4828. uint32_t iwh_idx = 0;
  4829. uint32_t kwh_idx = 1;
  4830. uint32_t Cout_idx = 2;
  4831. uint32_t Cin_idx = 3;
  4832. uint32_t B_idx = 4;
  4833. std::vector<std::array<int, 5>> cases = {
  4834. //{IWH, KWH, Cout, Cin, B}
  4835. // K=CRS=NPQ=4096 conv2d matmul performance
  4836. {19, 4, 4096, 256, 16},
  4837. // K=128, CRS=128, NPQ=4096
  4838. { 19, 4, 128, 8, 16},
  4839. // K=130, CRS=128, NPQ=4096
  4840. { 19, 4, 130, 8, 16},
  4841. // Edge case: K x CRS is small
  4842. { 19, 2, 4, 4, 16},
  4843. // A ConvNet's first layer
  4844. { 224, 3, 8, 3, 1 },
  4845. // A ConvNet's first layer with 2x2 convolution, and 1 channel
  4846. { 224, 2, 8, 1, 1 },
  4847. // A ConvNet's first layer with 2x2 convolution, and 1 channel, several images in the batch
  4848. { 224, 2, 8, 1, 8 },
  4849. // A middle layer of a ConvNet
  4850. { 58, 3, 64, 32, 1 },
  4851. // A middle layer of a ConvNet, several images in the batch
  4852. { 58, 3, 64, 32, 8 },
  4853. // A deep layer of a ConvNet, several images in the batch
  4854. { 16, 3, 512, 128, 8 },
  4855. };
  4856. for (auto kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) {
  4857. for (auto act_case : cases) {
  4858. // Direct CONV_2D
  4859. test_cases.emplace_back(new test_conv_2d(
  4860. { act_case[iwh_idx], act_case[iwh_idx], act_case[Cin_idx], act_case[B_idx] },
  4861. { act_case[kwh_idx], act_case[kwh_idx], act_case[Cin_idx], act_case[Cout_idx] },
  4862. kernel_type, 1, 1, 0, 0, 1, 1, false));
  4863. }
  4864. }
  4865. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {4096, 1, 1, 1}, {1, 1, 1, 1}));
  4866. test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F32, {4096, 1, 1, 1}, {1, 512, 1, 1}));
  4867. test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F16, {512, 3072, 1, 1}));
  4868. test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {8192, 512, 2, 1}, {0, 2, 1, 3}));
  4869. test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {3072, 512, 2, 1}, {0, 2, 1, 3}));
  4870. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4096, 4096, 5, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4871. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {12888, 256, 5, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4872. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {77, 4096, 5, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4873. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {1024, 1024, 10, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4874. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {77, 1024, 10, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4875. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {256, 256, 20, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4876. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {64, 64, 20, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4877. test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {77, 64, 20, 1}, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
  4878. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {32, 10, 1, 1}));
  4879. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {1024, 10, 1, 1}));
  4880. test_cases.emplace_back(new test_argmax(GGML_TYPE_F32, {32000, 512, 1, 1}));
  4881. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 16416, 1, 128, {8, 1}, {4, 1}, {0, 2, 1, 3}));
  4882. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, 128, 1, 16416, {8, 1}, {4, 1}, {0, 1, 2, 3}, true));
  4883. for (int bs : {1, 2, 3, 4, 5, 8, 512}) {
  4884. for (ggml_type type_a : all_types) {
  4885. for (ggml_type type_b : {GGML_TYPE_F32}) {
  4886. test_cases.emplace_back(new test_mul_mat(type_a, type_b, 4096, bs, 14336, {1, 1}, {1, 1}));
  4887. }
  4888. }
  4889. }
  4890. for (int K : {3, 5}) {
  4891. for (int IC : {256, 2560}) {
  4892. for (int IW_IH : {32, 64, 256}) {
  4893. if (IC == 2560 && IW_IH == 256) {
  4894. // too big
  4895. continue;
  4896. }
  4897. test_cases.emplace_back(new test_im2col(GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_F32, {IW_IH, IW_IH, IC, 1}, {K, K, IC, 1}, 1, 1, 1, 1, 1, 1, true));
  4898. }
  4899. }
  4900. }
  4901. for (int kv : { 4096, 8192, 16384, }) {
  4902. for (int hs : { 64, 128, }) {
  4903. for (int nr : { 1, 4, }) {
  4904. test_cases.emplace_back(new test_flash_attn_ext(hs, hs, 8, {nr, 1}, kv, 1, true, 0, 0, GGML_PREC_F32, GGML_TYPE_F16));
  4905. }
  4906. }
  4907. }
  4908. test_cases.emplace_back(new test_conv_2d_dw({512, 512, 256, 1}, {3, 3, 1, 256}, 1, 1, 1, false));
  4909. test_cases.emplace_back(new test_conv_2d_dw({512, 512, 256, 1}, {3, 3, 1, 256}, 1, 1, 1, true));
  4910. test_cases.emplace_back(new test_conv_transpose_2d({256, 256, 256, 1}, {3, 3, 16, 256}, 1));
  4911. test_cases.emplace_back(new test_mean(GGML_TYPE_F32, {256, 256, 3, 1}));
  4912. return test_cases;
  4913. }
  4914. static bool test_backend(ggml_backend_t backend, test_mode mode, const char * op_name, const char * params_filter,
  4915. printer * output_printer) {
  4916. auto filter_test_cases = [](std::vector<std::unique_ptr<test_case>> & test_cases, const char * params_filter) {
  4917. if (params_filter == nullptr) {
  4918. return;
  4919. }
  4920. std::regex params_filter_regex(params_filter);
  4921. for (auto it = test_cases.begin(); it != test_cases.end();) {
  4922. if (!std::regex_search((*it)->vars(), params_filter_regex)) {
  4923. it = test_cases.erase(it);
  4924. continue;
  4925. }
  4926. it++;
  4927. }
  4928. };
  4929. if (mode == MODE_TEST) {
  4930. auto test_cases = make_test_cases_eval();
  4931. filter_test_cases(test_cases, params_filter);
  4932. ggml_backend_t backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, NULL);
  4933. if (backend_cpu == NULL) {
  4934. test_operation_info info("", "", "CPU");
  4935. info.set_error("backend", "Failed to initialize CPU backend");
  4936. output_printer->print_operation(info);
  4937. return false;
  4938. }
  4939. size_t n_ok = 0;
  4940. for (auto & test : test_cases) {
  4941. if (test->eval(backend, backend_cpu, op_name, output_printer)) {
  4942. n_ok++;
  4943. }
  4944. }
  4945. output_printer->print_summary(test_summary_info(n_ok, test_cases.size(), false));
  4946. ggml_backend_free(backend_cpu);
  4947. return n_ok == test_cases.size();
  4948. }
  4949. if (mode == MODE_GRAD) {
  4950. auto test_cases = make_test_cases_eval();
  4951. filter_test_cases(test_cases, params_filter);
  4952. size_t n_ok = 0;
  4953. for (auto & test : test_cases) {
  4954. if (test->eval_grad(backend, op_name, output_printer)) {
  4955. n_ok++;
  4956. }
  4957. }
  4958. output_printer->print_summary(test_summary_info(n_ok, test_cases.size(), false));
  4959. return n_ok == test_cases.size();
  4960. }
  4961. if (mode == MODE_PERF) {
  4962. auto test_cases = make_test_cases_perf();
  4963. filter_test_cases(test_cases, params_filter);
  4964. for (auto & test : test_cases) {
  4965. test->eval_perf(backend, op_name, output_printer);
  4966. }
  4967. return true;
  4968. }
  4969. if (mode == MODE_SUPPORT) {
  4970. auto test_cases = make_test_cases_eval();
  4971. filter_test_cases(test_cases, params_filter);
  4972. for (auto & test : test_cases) {
  4973. test->eval_support(backend, op_name, output_printer);
  4974. }
  4975. return true;
  4976. }
  4977. GGML_ABORT("fatal error");
  4978. }
  4979. static void usage(char ** argv) {
  4980. printf("Usage: %s [mode] [-o <op>] [-b <backend>] [-p <params regex>] [--output <console|sql|csv>]\n", argv[0]);
  4981. printf(" valid modes:\n");
  4982. printf(" - test (default, compare with CPU backend for correctness)\n");
  4983. printf(" - grad (compare gradients from backpropagation with method of finite differences)\n");
  4984. printf(" - perf (performance evaluation)\n");
  4985. printf(" - support (probe backend operation support)\n");
  4986. printf(" op names for -o are as given by ggml_op_desc() (e.g. ADD, MUL_MAT, etc)\n");
  4987. printf(" --output specifies output format (default: console, options: console, sql, csv)\n");
  4988. }
  4989. int main(int argc, char ** argv) {
  4990. test_mode mode = MODE_TEST;
  4991. output_formats output_format = CONSOLE;
  4992. const char * op_name_filter = nullptr;
  4993. const char * backend_filter = nullptr;
  4994. const char * params_filter = nullptr;
  4995. for (int i = 1; i < argc; i++) {
  4996. if (strcmp(argv[i], "test") == 0) {
  4997. mode = MODE_TEST;
  4998. } else if (strcmp(argv[i], "perf") == 0) {
  4999. mode = MODE_PERF;
  5000. } else if (strcmp(argv[i], "grad") == 0) {
  5001. mode = MODE_GRAD;
  5002. } else if (strcmp(argv[i], "support") == 0) {
  5003. mode = MODE_SUPPORT;
  5004. } else if (strcmp(argv[i], "-o") == 0) {
  5005. if (i + 1 < argc) {
  5006. op_name_filter = argv[++i];
  5007. } else {
  5008. usage(argv);
  5009. return 1;
  5010. }
  5011. } else if (strcmp(argv[i], "-b") == 0) {
  5012. if (i + 1 < argc) {
  5013. backend_filter = argv[++i];
  5014. } else {
  5015. usage(argv);
  5016. return 1;
  5017. }
  5018. } else if (strcmp(argv[i], "-p") == 0) {
  5019. if (i + 1 < argc) {
  5020. params_filter = argv[++i];
  5021. } else {
  5022. usage(argv);
  5023. return 1;
  5024. }
  5025. } else if (strcmp(argv[i], "--output") == 0) {
  5026. if (i + 1 < argc) {
  5027. if (!output_format_from_str(argv[++i], output_format)) {
  5028. usage(argv);
  5029. return 1;
  5030. }
  5031. } else {
  5032. usage(argv);
  5033. return 1;
  5034. }
  5035. } else {
  5036. usage(argv);
  5037. return 1;
  5038. }
  5039. }
  5040. // load and enumerate backends
  5041. ggml_backend_load_all();
  5042. // Create printer for output format
  5043. std::unique_ptr<printer> output_printer = create_printer(output_format);
  5044. if (output_printer) {
  5045. output_printer->print_header();
  5046. }
  5047. output_printer->print_testing_start(testing_start_info(ggml_backend_dev_count()));
  5048. size_t n_ok = 0;
  5049. for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
  5050. ggml_backend_dev_t dev = ggml_backend_dev_get(i);
  5051. if (backend_filter != NULL && strcmp(backend_filter, ggml_backend_dev_name(dev)) != 0) {
  5052. output_printer->print_backend_init(
  5053. backend_init_info(i, ggml_backend_dev_count(), ggml_backend_dev_name(dev), true, "Skipping"));
  5054. n_ok++;
  5055. continue;
  5056. }
  5057. if (backend_filter == NULL && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU && mode != MODE_GRAD) {
  5058. output_printer->print_backend_init(backend_init_info(
  5059. i, ggml_backend_dev_count(), ggml_backend_dev_name(dev), true, "Skipping CPU backend"));
  5060. n_ok++;
  5061. continue;
  5062. }
  5063. ggml_backend_t backend = ggml_backend_dev_init(dev, NULL);
  5064. GGML_ASSERT(backend != NULL);
  5065. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  5066. auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
  5067. if (ggml_backend_set_n_threads_fn) {
  5068. // TODO: better value for n_threads
  5069. ggml_backend_set_n_threads_fn(backend, std::thread::hardware_concurrency());
  5070. }
  5071. size_t free, total; // NOLINT
  5072. ggml_backend_dev_memory(dev, &free, &total);
  5073. output_printer->print_backend_init(backend_init_info(i, ggml_backend_dev_count(), ggml_backend_dev_name(dev),
  5074. false, "", ggml_backend_dev_description(dev),
  5075. total / 1024 / 1024, free / 1024 / 1024, true));
  5076. bool ok = test_backend(backend, mode, op_name_filter, params_filter, output_printer.get());
  5077. if (ok) {
  5078. n_ok++;
  5079. }
  5080. output_printer->print_backend_status(
  5081. backend_status_info(ggml_backend_name(backend), ok ? test_status_t::OK : test_status_t::FAIL));
  5082. ggml_backend_free(backend);
  5083. }
  5084. ggml_quantize_free();
  5085. if (output_printer) {
  5086. output_printer->print_footer();
  5087. }
  5088. output_printer->print_overall_summary(
  5089. overall_summary_info(n_ok, ggml_backend_dev_count(), n_ok == ggml_backend_dev_count()));
  5090. if (n_ok != ggml_backend_dev_count()) {
  5091. return 1;
  5092. }
  5093. return 0;
  5094. }