test-backend-ops.cpp 261 KB

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