test-backend-ops.cpp 257 KB

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