test-backend-ops.cpp 229 KB

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