test-backend-ops.cpp 226 KB

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