test-backend-ops.cpp 253 KB

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