ggml-vulkan.cpp 430 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_PERF) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. #include <vulkan/vulkan.hpp>
  8. #include <algorithm>
  9. #include <cmath>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <tuple>
  13. #include <vector>
  14. #include <sstream>
  15. #include <utility>
  16. #include <memory>
  17. #include <limits>
  18. #include <map>
  19. #include <unordered_map>
  20. #include <memory>
  21. #include <mutex>
  22. #include <future>
  23. #include <thread>
  24. #include "ggml-impl.h"
  25. #include "ggml-backend-impl.h"
  26. #include "ggml-vulkan-shaders.hpp"
  27. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  28. #define VK_VENDOR_ID_AMD 0x1002
  29. #define VK_VENDOR_ID_APPLE 0x106b
  30. #define VK_VENDOR_ID_INTEL 0x8086
  31. #define VK_VENDOR_ID_NVIDIA 0x10de
  32. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 32
  33. #define GGML_VK_MAX_NODES 8192
  34. #define MAX_VK_BUFFERS 256
  35. #define VK_CHECK(err, msg) \
  36. do { \
  37. vk::Result err_ = (err); \
  38. if (err_ != vk::Result::eSuccess) { \
  39. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  40. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  41. exit(1); \
  42. } \
  43. } while (0)
  44. #ifdef GGML_VULKAN_DEBUG
  45. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  46. #else
  47. #define VK_LOG_DEBUG(msg) ((void) 0)
  48. #endif // GGML_VULKAN_DEBUG
  49. struct ggml_backend_vk_context;
  50. struct vk_queue {
  51. uint32_t queue_family_index;
  52. vk::Queue queue;
  53. vk::CommandPool pool;
  54. uint32_t cmd_buffer_idx;
  55. std::vector<vk::CommandBuffer> cmd_buffers;
  56. vk::PipelineStageFlags stage_flags;
  57. bool transfer_only;
  58. };
  59. struct vk_pipeline_struct {
  60. std::string name;
  61. vk::ShaderModule shader_module;
  62. vk::DescriptorSetLayout dsl;
  63. std::vector<vk::DescriptorPool> descriptor_pools;
  64. std::vector<vk::DescriptorSet> descriptor_sets;
  65. uint32_t descriptor_set_idx;
  66. vk::PipelineLayout layout;
  67. vk::Pipeline pipeline;
  68. uint32_t push_constant_size;
  69. uint32_t parameter_count;
  70. std::array<uint32_t, 3> wg_denoms;
  71. uint32_t align;
  72. };
  73. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  74. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  75. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  76. struct vk_matmul_pipeline_struct {
  77. vk_pipeline l, m, s;
  78. vk_pipeline a_l, a_m, a_s;
  79. };
  80. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  81. struct vk_matmul_pipeline2 {
  82. vk_matmul_pipeline2() {
  83. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  84. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  85. }
  86. vk_matmul_pipeline f32acc;
  87. vk_matmul_pipeline f16acc;
  88. };
  89. struct vk_device_struct;
  90. typedef std::shared_ptr<vk_device_struct> vk_device;
  91. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  92. struct vk_buffer_struct;
  93. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  94. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  95. struct ggml_backend_vk_buffer_type_context {
  96. std::string name;
  97. vk_device device;
  98. };
  99. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  100. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  101. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  102. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  103. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  104. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  105. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  106. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  107. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  108. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  109. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  110. /* .is_host = */ NULL,
  111. };
  112. #ifdef GGML_VULKAN_MEMORY_DEBUG
  113. class vk_memory_logger;
  114. #endif
  115. #ifdef GGML_VULKAN_PERF
  116. class vk_perf_logger;
  117. #endif
  118. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  119. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  120. struct vk_device_struct {
  121. std::mutex mutex;
  122. vk::PhysicalDevice physical_device;
  123. vk::PhysicalDeviceProperties properties;
  124. std::string name;
  125. uint64_t max_memory_allocation_size;
  126. bool fp16;
  127. bool pipeline_robustness;
  128. vk::Device device;
  129. uint32_t vendor_id;
  130. vk_queue compute_queue;
  131. vk_queue transfer_queue;
  132. bool single_queue;
  133. uint32_t subgroup_size;
  134. uint32_t shader_core_count;
  135. bool uma;
  136. bool float_controls_rte_fp16;
  137. bool subgroup_size_control;
  138. uint32_t subgroup_min_size;
  139. uint32_t subgroup_max_size;
  140. bool subgroup_require_full_support;
  141. bool coopmat_support;
  142. bool coopmat_acc_f32_support;
  143. bool coopmat_acc_f16_support;
  144. uint32_t coopmat_m;
  145. uint32_t coopmat_n;
  146. uint32_t coopmat_k;
  147. bool coopmat2;
  148. size_t idx;
  149. bool mul_mat_l;
  150. bool mul_mat_m;
  151. bool mul_mat_s;
  152. bool mul_mat_id_l;
  153. bool mul_mat_id_m;
  154. bool mul_mat_id_s;
  155. vk_matmul_pipeline pipeline_matmul_f32;
  156. vk_matmul_pipeline pipeline_matmul_f32_f16;
  157. vk_matmul_pipeline2 pipeline_matmul_f16;
  158. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  159. vk_pipeline pipeline_matmul_split_k_reduce;
  160. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  161. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  162. vk_matmul_pipeline pipeline_matmul_id_f32;
  163. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  164. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  165. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  166. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  167. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  168. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  169. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  170. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  171. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  172. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  173. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  174. vk_pipeline pipeline_acc_f32;
  175. vk_pipeline pipeline_add_f32, pipeline_add_f32_norepeat;
  176. vk_pipeline pipeline_add_f16_f32_f16, pipeline_add_f16_f32_f16_norepeat;
  177. vk_pipeline pipeline_mul_f32, pipeline_mul_f32_norepeat;
  178. vk_pipeline pipeline_div_f32, pipeline_div_f32_norepeat;
  179. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  180. vk_pipeline pipeline_upscale_f32;
  181. vk_pipeline pipeline_scale_f32;
  182. vk_pipeline pipeline_sqr_f32;
  183. vk_pipeline pipeline_sin_f32;
  184. vk_pipeline pipeline_cos_f32;
  185. vk_pipeline pipeline_clamp_f32;
  186. vk_pipeline pipeline_pad_f32;
  187. vk_pipeline pipeline_repeat_f32;
  188. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  189. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16;
  190. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  191. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  192. vk_pipeline pipeline_norm_f32;
  193. vk_pipeline pipeline_group_norm_f32;
  194. vk_pipeline pipeline_rms_norm_f32;
  195. vk_pipeline pipeline_gelu_f32;
  196. vk_pipeline pipeline_gelu_quick_f32;
  197. vk_pipeline pipeline_silu_f32;
  198. vk_pipeline pipeline_relu_f32;
  199. vk_pipeline pipeline_leaky_relu_f32;
  200. vk_pipeline pipeline_tanh_f32;
  201. vk_pipeline pipeline_diag_mask_inf_f32;
  202. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  203. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  204. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  205. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  206. vk_pipeline pipeline_argsort_f32;
  207. vk_pipeline pipeline_sum_rows_f32;
  208. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  209. vk_pipeline pipeline_timestep_embedding_f32;
  210. vk_pipeline pipeline_pool2d_f32;
  211. vk_pipeline pipeline_rwkv_wkv6_f32;
  212. // [2][2][2] is for {f16acc,f32acc}x{large,small_rows}x{unaligned, aligned}
  213. vk_pipeline pipeline_flash_attn_f32_f16_D64[GGML_TYPE_COUNT][2][2][2];
  214. vk_pipeline pipeline_flash_attn_f32_f16_D80[GGML_TYPE_COUNT][2][2][2];
  215. vk_pipeline pipeline_flash_attn_f32_f16_D96[GGML_TYPE_COUNT][2][2][2];
  216. vk_pipeline pipeline_flash_attn_f32_f16_D112[GGML_TYPE_COUNT][2][2][2];
  217. vk_pipeline pipeline_flash_attn_f32_f16_D128[GGML_TYPE_COUNT][2][2][2];
  218. vk_pipeline pipeline_flash_attn_f32_f16_D256[GGML_TYPE_COUNT][2][2][2];
  219. std::unordered_map<std::string, vk_pipeline_ref> pipelines;
  220. std::unordered_map<std::string, uint64_t> pipeline_descriptor_set_requirements;
  221. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  222. vk::Fence fence;
  223. vk_buffer sync_staging;
  224. ggml_backend_buffer_type buffer_type;
  225. #ifdef GGML_VULKAN_MEMORY_DEBUG
  226. std::unique_ptr<vk_memory_logger> memory_logger;
  227. #endif
  228. #ifdef GGML_VULKAN_PERF
  229. std::unique_ptr<vk_perf_logger> perf_logger;
  230. #endif
  231. ~vk_device_struct() {
  232. VK_LOG_DEBUG("destroy device " << name);
  233. device.destroyFence(fence);
  234. ggml_vk_destroy_buffer(sync_staging);
  235. device.destroyCommandPool(compute_queue.pool);
  236. if (!single_queue) {
  237. device.destroyCommandPool(transfer_queue.pool);
  238. }
  239. for (auto& pipeline : pipelines) {
  240. if (pipeline.second.expired()) {
  241. continue;
  242. }
  243. vk_pipeline pl = pipeline.second.lock();
  244. ggml_vk_destroy_pipeline(device, pl);
  245. }
  246. pipelines.clear();
  247. device.destroy();
  248. }
  249. };
  250. struct vk_buffer_struct {
  251. vk::Buffer buffer = VK_NULL_HANDLE;
  252. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  253. vk::MemoryPropertyFlags memory_property_flags;
  254. void * ptr;
  255. size_t size = 0;
  256. vk_device device;
  257. ~vk_buffer_struct() {
  258. if (size == 0) {
  259. return;
  260. }
  261. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  262. device->device.freeMemory(device_memory);
  263. device->device.destroyBuffer(buffer);
  264. }
  265. };
  266. struct vk_subbuffer {
  267. vk_buffer buffer;
  268. uint64_t offset;
  269. uint64_t size;
  270. operator vk::DescriptorBufferInfo() const {
  271. return { buffer->buffer, offset, size };
  272. }
  273. };
  274. struct vk_semaphore {
  275. vk::Semaphore s;
  276. uint64_t value;
  277. };
  278. struct vk_submission {
  279. vk::CommandBuffer buffer;
  280. std::vector<vk_semaphore> wait_semaphores;
  281. std::vector<vk_semaphore> signal_semaphores;
  282. };
  283. typedef std::vector<vk_submission> vk_sequence;
  284. struct vk_mat_mat_push_constants {
  285. uint32_t M; uint32_t N; uint32_t K;
  286. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  287. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  288. uint32_t k_split;
  289. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  290. };
  291. struct vk_mat_vec_push_constants {
  292. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  293. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  294. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  295. };
  296. struct vk_mat_mat_id_push_constants {
  297. uint32_t M; uint32_t N; uint32_t K;
  298. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  299. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  300. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  301. };
  302. struct vk_mat_vec_id_push_constants {
  303. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  304. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  305. uint32_t nei0; uint32_t ne11;
  306. };
  307. struct vk_flash_attn_push_constants {
  308. uint32_t N;
  309. uint32_t KV;
  310. uint32_t ne1;
  311. uint32_t ne2;
  312. uint32_t ne3;
  313. uint32_t neq2;
  314. uint32_t neq3;
  315. uint32_t nek2;
  316. uint32_t nek3;
  317. uint32_t nev2;
  318. uint32_t nev3;
  319. uint32_t nem1;
  320. uint32_t nb01;
  321. uint32_t nb02;
  322. uint32_t nb03;
  323. uint32_t nb11;
  324. uint32_t nb12;
  325. uint32_t nb13;
  326. uint32_t nb21;
  327. uint32_t nb22;
  328. uint32_t nb23;
  329. uint32_t nb31;
  330. float scale;
  331. float max_bias;
  332. float logit_softcap;
  333. uint32_t mask;
  334. uint32_t n_head_log2;
  335. float m0;
  336. float m1;
  337. };
  338. struct vk_op_push_constants {
  339. uint32_t KX;
  340. uint32_t KY;
  341. float param1;
  342. float param2;
  343. };
  344. struct vk_op_unary_push_constants {
  345. uint32_t ne;
  346. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  347. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  348. uint32_t misalign_offsets;
  349. float param1; float param2;
  350. uint32_t ne0_012mp; uint32_t ne0_012L;
  351. uint32_t ne0_01mp; uint32_t ne0_01L;
  352. uint32_t ne0_0mp; uint32_t ne0_0L;
  353. uint32_t ne1_012mp; uint32_t ne1_012L;
  354. uint32_t ne1_01mp; uint32_t ne1_01L;
  355. uint32_t ne1_0mp; uint32_t ne1_0L;
  356. };
  357. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  358. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  359. // Precompute mp (m' in the paper) and L such that division
  360. // can be computed using a multiply (high 32b of 64b result)
  361. // and a shift:
  362. //
  363. // n/d = (mulhi(n, mp) + n) >> L;
  364. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  365. {
  366. // compute L = ceil(log2(d));
  367. L = 0;
  368. while (L < 32 && (uint32_t{1} << L) < d) {
  369. L++;
  370. }
  371. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  372. }
  373. template <typename T> void init_pushconst_fastdiv(T &p) {
  374. GGML_UNUSED(p);
  375. static_assert(!std::is_const<T>::value, "unexpected type");
  376. }
  377. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  378. // Compute magic values to divide by these six numbers.
  379. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  380. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  381. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  382. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  383. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  384. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  385. }
  386. struct vk_op_binary_push_constants {
  387. uint32_t ne;
  388. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  389. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  390. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  391. uint32_t misalign_offsets;
  392. float param1; float param2; int32_t param3;
  393. };
  394. struct vk_op_diag_mask_push_constants {
  395. uint32_t ncols;
  396. uint32_t rows_per_channel;
  397. int32_t n_past;
  398. };
  399. struct vk_op_rope_push_constants {
  400. uint32_t ncols;
  401. uint32_t n_dims;
  402. float freq_scale;
  403. uint32_t p_delta_rows;
  404. float freq_base;
  405. float ext_factor;
  406. float attn_factor;
  407. float corr_dims[2];
  408. float theta_scale;
  409. uint32_t has_ff;
  410. };
  411. struct vk_op_soft_max_push_constants {
  412. uint32_t KX;
  413. uint32_t KY;
  414. float scale;
  415. float max_bias;
  416. float m0;
  417. float m1;
  418. uint32_t n_head_log2;
  419. uint32_t nrows_x;
  420. };
  421. struct vk_op_argsort_push_constants {
  422. uint32_t ncols;
  423. uint32_t ncols_pad;
  424. int32_t order;
  425. };
  426. struct vk_op_im2col_push_constants {
  427. uint32_t batch_offset; uint32_t offset_delta;
  428. uint32_t IC;
  429. uint32_t IW; uint32_t IH;
  430. uint32_t OW; uint32_t OH;
  431. uint32_t KW; uint32_t KH;
  432. uint32_t pelements;
  433. uint32_t CHW;
  434. int32_t s0; int32_t s1;
  435. int32_t p0; int32_t p1;
  436. int32_t d0; int32_t d1;
  437. };
  438. struct vk_op_timestep_embedding_push_constants {
  439. uint32_t nb1;
  440. uint32_t dim;
  441. uint32_t max_period;
  442. };
  443. struct vk_op_pool2d_push_constants {
  444. uint32_t IW; uint32_t IH;
  445. uint32_t OW; uint32_t OH;
  446. uint32_t OC;
  447. uint32_t pelements;
  448. uint32_t op;
  449. int32_t k0; int32_t k1;
  450. int32_t s0; int32_t s1;
  451. int32_t p0; int32_t p1;
  452. };
  453. struct vk_op_rwkv_wkv6_push_constants {
  454. uint32_t B;
  455. uint32_t T;
  456. uint32_t C;
  457. uint32_t H;
  458. };
  459. // Allow pre-recording command buffers
  460. struct vk_staging_memcpy {
  461. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  462. void * dst;
  463. const void * src;
  464. size_t n;
  465. };
  466. struct vk_op_upscale_push_constants {
  467. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  468. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  469. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  470. float sf0; float sf1; float sf2; float sf3;
  471. };
  472. struct vk_context_struct {
  473. vk_submission * s;
  474. std::vector<vk_sequence> seqs;
  475. int exit_tensor_idx;
  476. std::vector<vk_staging_memcpy> in_memcpys;
  477. std::vector<vk_staging_memcpy> out_memcpys;
  478. vk_queue * q;
  479. };
  480. typedef std::shared_ptr<vk_context_struct> vk_context;
  481. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  482. struct ggml_vk_garbage_collector {
  483. std::vector<vk_semaphore> tl_semaphores;
  484. std::vector<vk_semaphore> semaphores;
  485. std::vector<vk::Event> events;
  486. std::vector<vk_buffer> temp_buffers;
  487. std::vector<vk_context> contexts;
  488. };
  489. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  490. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  491. static std::string format_size(size_t size) {
  492. const size_t kib = 1024;
  493. const size_t mib = kib * 1024;
  494. const size_t gib = mib * 1024;
  495. std::ostringstream oss;
  496. oss << std::fixed << std::setprecision(2);
  497. if (size >= gib) {
  498. oss << static_cast<double>(size) / gib << " GiB";
  499. } else if (size >= mib) {
  500. oss << static_cast<double>(size) / mib << " MiB";
  501. } else if (size >= kib) {
  502. oss << static_cast<double>(size) / kib << " KiB";
  503. } else {
  504. oss << size << " B";
  505. }
  506. return oss.str();
  507. }
  508. static std::mutex log_mutex;
  509. class vk_memory_logger {
  510. public:
  511. vk_memory_logger(): total_device(0), total_host(0) {}
  512. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  513. void log_deallocation(vk_buffer_ref buf_ref);
  514. private:
  515. std::map<vk::Buffer, size_t> allocations; // Track allocations
  516. size_t total_device;
  517. size_t total_host;
  518. };
  519. #else
  520. #define VK_LOG_MEMORY(msg) ((void) 0)
  521. #endif // GGML_VULKAN_MEMORY_DEBUG
  522. #if defined(GGML_VULKAN_PERF)
  523. class vk_perf_logger {
  524. public:
  525. void print_timings() {
  526. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  527. for (const auto& t : timings) {
  528. uint64_t total = 0;
  529. for (const auto& time : t.second) {
  530. total += time;
  531. }
  532. std::cerr << t.first << ": " << t.second.size() << " x " << (total / t.second.size() / 1000.0) << " ms" << std::endl;
  533. }
  534. timings.clear();
  535. }
  536. void log_timing(const ggml_tensor * node, uint64_t time) {
  537. if (node->op == GGML_OP_UNARY) {
  538. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  539. return;
  540. }
  541. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  542. const uint64_t m = node->src[0]->ne[1];
  543. const uint64_t n = node->src[1]->ne[1];
  544. const uint64_t k = node->src[1]->ne[0];
  545. std::string name = ggml_op_name(node->op);
  546. if (n == 1) {
  547. name += "_VEC m=" + std::to_string(m) + " k=" + std::to_string(k);
  548. } else {
  549. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  550. }
  551. timings[name].push_back(time);
  552. return;
  553. }
  554. timings[ggml_op_name(node->op)].push_back(time);
  555. }
  556. private:
  557. std::map<std::string, std::vector<uint64_t>> timings;
  558. };
  559. #endif // GGML_VULKAN_PERF
  560. struct ggml_backend_vk_context {
  561. std::string name;
  562. vk_device device;
  563. size_t semaphore_idx, event_idx;
  564. ggml_vk_garbage_collector gc;
  565. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  566. vk_buffer prealloc_x, prealloc_y, prealloc_split_k;
  567. vk::Fence fence;
  568. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  569. vk_context_ref compute_ctx;
  570. vk_context_ref transfer_ctx;
  571. std::vector<vk_context_ref> tensor_ctxs;
  572. };
  573. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  574. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  575. if (tensor->view_src) {
  576. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  577. }
  578. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  579. }
  580. struct ggml_backend_vk_buffer_context {
  581. vk_device_ref device;
  582. vk_buffer dev_buffer;
  583. std::string name;
  584. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  585. device(device),
  586. dev_buffer(dev_buffer),
  587. name(name) {
  588. }
  589. ~ggml_backend_vk_buffer_context() {
  590. ggml_vk_destroy_buffer(dev_buffer);
  591. }
  592. };
  593. #ifdef GGML_VULKAN_MEMORY_DEBUG
  594. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  595. std::lock_guard<std::mutex> guard(log_mutex);
  596. vk_buffer buf = buf_ref.lock();
  597. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  598. const std::string type = device ? "device" : "host";
  599. allocations[buf->buffer] = size;
  600. total_device += device ? size : 0;
  601. total_host += device ? 0 : size;
  602. VK_LOG_MEMORY(buf->device->name << ": +" << format_size(size) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  603. }
  604. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  605. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  606. return;
  607. }
  608. std::lock_guard<std::mutex> guard(log_mutex);
  609. vk_buffer buf = buf_ref.lock();
  610. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  611. std::string type = device ? "device" : "host";
  612. auto it = allocations.find(buf->buffer);
  613. total_device -= device ? it->second : 0;
  614. total_host -= device ? 0 : it->second;
  615. if (it != allocations.end()) {
  616. VK_LOG_MEMORY(buf->device->name << ": -" << format_size(it->second) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  617. allocations.erase(it);
  618. } else {
  619. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  620. }
  621. }
  622. #endif // GGML_VULKAN_MEMORY_DEBUG
  623. struct vk_instance_t {
  624. vk::Instance instance;
  625. std::vector<size_t> device_indices;
  626. vk_device devices[GGML_VK_MAX_DEVICES];
  627. };
  628. static bool vk_instance_initialized = false;
  629. static vk_instance_t vk_instance;
  630. #ifdef GGML_VULKAN_CHECK_RESULTS
  631. static size_t vk_skip_checks;
  632. static size_t vk_output_tensor;
  633. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  634. static void ggml_vk_check_results_0(ggml_tensor * tensor);
  635. static void ggml_vk_check_results_1(ggml_tensor * tensor);
  636. #endif
  637. typedef void (*ggml_vk_func_t)(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
  638. static void ggml_backend_vk_free(ggml_backend_t backend);
  639. // variables to track number of compiles in progress
  640. static uint32_t compile_count = 0;
  641. static std::mutex compile_count_mutex;
  642. static std::condition_variable compile_count_cond;
  643. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, const std::string name, size_t spv_size, const void* spv_data, const std::string entrypoint,
  644. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  645. uint32_t align, bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  646. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << name << ", " << entrypoint << ", " << parameter_count << ", " << push_constant_size <<
  647. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << align <<
  648. ", " << disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  649. GGML_ASSERT(parameter_count > 0);
  650. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  651. pipeline = std::make_shared<vk_pipeline_struct>();
  652. pipeline->name = name;
  653. pipeline->parameter_count = parameter_count;
  654. pipeline->push_constant_size = push_constant_size;
  655. pipeline->wg_denoms = wg_denoms;
  656. pipeline->align = align;
  657. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  658. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  659. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  660. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  661. for (uint32_t i = 0; i < parameter_count; i++) {
  662. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  663. dsl_binding_flags.push_back({});
  664. }
  665. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  666. vk::PushConstantRange pcr(
  667. vk::ShaderStageFlagBits::eCompute,
  668. 0,
  669. pipeline->push_constant_size
  670. );
  671. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  672. {},
  673. dsl_binding);
  674. descriptor_set_layout_create_info.setPNext(&dslbfci);
  675. pipeline->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  676. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  677. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  678. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  679. pipeline->descriptor_set_idx = 0;
  680. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline->dsl, pcr);
  681. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  682. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  683. for (size_t i = 0; i < specialization_constants.size(); i++) {
  684. specialization_entries[i].constantID = i;
  685. specialization_entries[i].offset = i * sizeof(uint32_t);
  686. specialization_entries[i].size = sizeof(uint32_t);
  687. }
  688. vk::SpecializationInfo specialization_info(
  689. specialization_entries.size(),
  690. specialization_entries.data(),
  691. specialization_constants.size() * sizeof(uint32_t),
  692. specialization_constants.data()
  693. );
  694. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  695. if (device->subgroup_require_full_support && require_full_subgroups) {
  696. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  697. }
  698. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  699. pipeline_shader_stage_create_flags,
  700. vk::ShaderStageFlagBits::eCompute,
  701. pipeline->shader_module,
  702. entrypoint.c_str(),
  703. &specialization_info);
  704. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  705. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  706. if (device->subgroup_size_control && required_subgroup_size > 0) {
  707. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  708. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  709. }
  710. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  711. vk::PipelineCreateFlags{},
  712. pipeline_shader_create_info,
  713. pipeline->layout);
  714. vk::PipelineRobustnessCreateInfoEXT rci;
  715. if (device->pipeline_robustness && disable_robustness) {
  716. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  717. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  718. compute_pipeline_create_info.setPNext(&rci);
  719. }
  720. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  721. {
  722. std::lock_guard<std::mutex> guard(device->mutex);
  723. device->pipelines.insert({ pipeline->name, pipeline });
  724. }
  725. {
  726. std::lock_guard<std::mutex> guard(compile_count_mutex);
  727. assert(compile_count > 0);
  728. compile_count--;
  729. // "Progress bar" for shader compiles
  730. static uint32_t total_compile_count = 0;
  731. if ((total_compile_count++ % 10) == 0) {
  732. std::cerr << ".";
  733. }
  734. }
  735. compile_count_cond.notify_all();
  736. }
  737. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  738. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  739. for (auto& pool : pipeline->descriptor_pools) {
  740. device.destroyDescriptorPool(pool);
  741. }
  742. pipeline->descriptor_pools.clear();
  743. pipeline->descriptor_sets.clear();
  744. pipeline->descriptor_set_idx = 0;
  745. device.destroyDescriptorSetLayout(pipeline->dsl);
  746. device.destroyPipelineLayout(pipeline->layout);
  747. device.destroyShaderModule(pipeline->shader_module);
  748. device.destroyPipeline(pipeline->pipeline);
  749. }
  750. static void ggml_pipeline_request_descriptor_sets(vk_device& device, vk_pipeline& pipeline, uint32_t n) {
  751. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  752. device->pipeline_descriptor_set_requirements[pipeline->name] += n;
  753. }
  754. static void ggml_pipeline_allocate_descriptor_sets(vk_device& device) {
  755. std::lock_guard<std::mutex> guard(device->mutex);
  756. for (auto& pair : device->pipeline_descriptor_set_requirements) {
  757. vk_pipeline pipeline = device->pipelines.at(pair.first).lock();
  758. const uint64_t n = pair.second;
  759. VK_LOG_DEBUG("ggml_pipeline_allocate_descriptor_sets(" << pipeline->name << ", " << n << ")");
  760. if (pipeline->descriptor_sets.size() >= pipeline->descriptor_set_idx + n) {
  761. // Enough descriptors are available
  762. continue;
  763. }
  764. uint32_t to_alloc = pipeline->descriptor_set_idx + n - pipeline->descriptor_sets.size();
  765. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - pipeline->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  766. uint32_t pool_idx = pipeline->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  767. while (to_alloc > 0) {
  768. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  769. to_alloc -= alloc_count;
  770. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  771. if (pool_idx >= pipeline->descriptor_pools.size()) {
  772. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  773. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  774. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  775. }
  776. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  777. for (uint32_t i = 0; i < alloc_count; i++) {
  778. layouts[i] = pipeline->dsl;
  779. }
  780. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[pool_idx], alloc_count, layouts.data());
  781. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  782. pipeline->descriptor_sets.insert(pipeline->descriptor_sets.end(), sets.begin(), sets.end());
  783. pool_idx++;
  784. }
  785. }
  786. }
  787. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  788. VK_LOG_DEBUG("ggml_pipeline_cleanup(" << pipeline->name << ")");
  789. pipeline->descriptor_set_idx = 0;
  790. }
  791. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_queue& q) {
  792. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  793. std::lock_guard<std::mutex> guard(device->mutex);
  794. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  795. // Reuse command buffer
  796. return q.cmd_buffers[q.cmd_buffer_idx++];
  797. }
  798. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  799. q.pool,
  800. vk::CommandBufferLevel::ePrimary,
  801. 1);
  802. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  803. auto buf = cmd_buffers.front();
  804. q.cmd_buffers.push_back(buf);
  805. q.cmd_buffer_idx++;
  806. return buf;
  807. }
  808. static vk_submission ggml_vk_create_submission(vk_device& device, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  809. VK_LOG_DEBUG("ggml_vk_create_submission()");
  810. vk_submission s;
  811. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  812. s.wait_semaphores = std::move(wait_semaphores);
  813. s.signal_semaphores = std::move(signal_semaphores);
  814. return s;
  815. }
  816. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  817. if (ctx->seqs.empty()) {
  818. if (fence) {
  819. ctx->q->queue.submit({}, fence);
  820. }
  821. return;
  822. }
  823. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  824. std::vector<std::vector<uint64_t>> tl_wait_vals;
  825. std::vector<std::vector<uint64_t>> tl_signal_vals;
  826. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  827. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  828. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  829. std::vector<vk::SubmitInfo> submit_infos;
  830. int idx = -1;
  831. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  832. size_t reserve = 0;
  833. for (const auto& sequence : ctx->seqs) {
  834. reserve += sequence.size();
  835. }
  836. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  837. tl_wait_semaphores.reserve(reserve);
  838. tl_wait_vals.reserve(reserve);
  839. tl_signal_semaphores.reserve(reserve);
  840. tl_signal_vals.reserve(reserve);
  841. tl_submit_infos.reserve(reserve);
  842. submit_infos.reserve(reserve);
  843. stage_flags.reserve(reserve);
  844. for (const auto& sequence : ctx->seqs) {
  845. for (const auto& submission : sequence) {
  846. stage_flags.push_back({});
  847. idx++;
  848. tl_wait_vals.push_back({});
  849. tl_wait_semaphores.push_back({});
  850. tl_signal_vals.push_back({});
  851. tl_signal_semaphores.push_back({});
  852. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  853. stage_flags[idx].push_back(ctx->q->stage_flags);
  854. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  855. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  856. }
  857. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  858. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  859. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  860. }
  861. tl_submit_infos.push_back({
  862. (uint32_t) submission.wait_semaphores.size(),
  863. tl_wait_vals[idx].data(),
  864. (uint32_t) submission.signal_semaphores.size(),
  865. tl_signal_vals[idx].data(),
  866. });
  867. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  868. tl_submit_infos[idx].pNext = nullptr;
  869. vk::SubmitInfo si{
  870. (uint32_t) submission.wait_semaphores.size(),
  871. tl_wait_semaphores[idx].data(),
  872. stage_flags[idx].data(),
  873. 1,
  874. &submission.buffer,
  875. (uint32_t) submission.signal_semaphores.size(),
  876. tl_signal_semaphores[idx].data(),
  877. };
  878. si.setPNext(&tl_submit_infos[idx]);
  879. submit_infos.push_back(si);
  880. }
  881. }
  882. ctx->q->queue.submit(submit_infos, fence);
  883. ctx->seqs.clear();
  884. }
  885. static uint32_t ggml_vk_find_queue_family_index(std::vector<vk::QueueFamilyProperties>& queue_family_props, const vk::QueueFlags& required, const vk::QueueFlags& avoid, int32_t compute_index, uint32_t min_num_queues) {
  886. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  887. const uint32_t qfsize = queue_family_props.size();
  888. // Try with avoid preferences first
  889. for (uint32_t i = 0; i < qfsize; i++) {
  890. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required && !(queue_family_props[i].queueFlags & avoid)) {
  891. return i;
  892. }
  893. }
  894. // Fall back to only required
  895. for (size_t i = 0; i < qfsize; i++) {
  896. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  897. return i;
  898. }
  899. }
  900. // Fall back to reusing compute queue
  901. for (size_t i = 0; i < qfsize; i++) {
  902. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  903. return i;
  904. }
  905. }
  906. // Fall back to ignoring min_num_queries
  907. for (size_t i = 0; i < qfsize; i++) {
  908. if (queue_family_props[i].queueFlags & required) {
  909. return i;
  910. }
  911. }
  912. // All commands that are allowed on a queue that supports transfer operations are also allowed on a queue that supports either graphics or compute operations.
  913. // Thus, if the capabilities of a queue family include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT capability separately for that queue family is optional.
  914. if (compute_index >= 0) {
  915. return compute_index;
  916. }
  917. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  918. for(auto &q_family : queue_family_props) {
  919. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  920. }
  921. abort();
  922. }
  923. static void ggml_vk_create_queue(vk_device& device, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags, bool transfer_only) {
  924. VK_LOG_DEBUG("ggml_vk_create_queue()");
  925. std::lock_guard<std::mutex> guard(device->mutex);
  926. q.queue_family_index = queue_family_index;
  927. q.transfer_only = transfer_only;
  928. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  929. q.pool = device->device.createCommandPool(command_pool_create_info_compute);
  930. q.cmd_buffer_idx = 0;
  931. q.queue = device->device.getQueue(queue_family_index, queue_index);
  932. q.stage_flags = stage_flags;
  933. }
  934. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  935. vk_context result = std::make_shared<vk_context_struct>();
  936. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  937. ctx->gc.contexts.emplace_back(result);
  938. result->q = &q;
  939. return result;
  940. }
  941. static vk_context ggml_vk_create_temporary_context(vk_queue& q) {
  942. vk_context result = std::make_shared<vk_context_struct>();
  943. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  944. result->q = &q;
  945. return result;
  946. }
  947. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  948. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  949. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  950. vk::SemaphoreCreateInfo ci{};
  951. ci.setPNext(&tci);
  952. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  953. ctx->gc.semaphores.push_back({ semaphore, 0 });
  954. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  955. }
  956. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  957. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  958. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  959. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  960. vk::SemaphoreCreateInfo ci{};
  961. ci.setPNext(&tci);
  962. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  963. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  964. }
  965. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  966. }
  967. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  968. if (ctx->event_idx >= ctx->gc.events.size()) {
  969. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  970. }
  971. return ctx->gc.events[ctx->event_idx++];
  972. }
  973. static void ggml_vk_queue_cleanup(vk_device& device, vk_queue& q) {
  974. VK_LOG_DEBUG("ggml_vk_queue_cleanup()");
  975. std::lock_guard<std::mutex> guard(device->mutex);
  976. // Requires command buffers to be done
  977. device->device.resetCommandPool(q.pool);
  978. q.cmd_buffer_idx = 0;
  979. }
  980. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  981. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  982. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  983. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  984. (flags & memory_type.propertyFlags) == flags &&
  985. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  986. return static_cast<int32_t>(i);
  987. }
  988. }
  989. return UINT32_MAX;
  990. }
  991. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  992. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")");
  993. if (size > device->max_memory_allocation_size) {
  994. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  995. }
  996. std::lock_guard<std::mutex> guard(device->mutex);
  997. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  998. if (size == 0) {
  999. buf->size = 0;
  1000. return buf;
  1001. }
  1002. vk::BufferCreateInfo buffer_create_info{
  1003. vk::BufferCreateFlags(),
  1004. size,
  1005. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  1006. vk::SharingMode::eExclusive,
  1007. 0,
  1008. nullptr,
  1009. };
  1010. buf->buffer = device->device.createBuffer(buffer_create_info);
  1011. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1012. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1013. uint32_t memory_type_index = UINT32_MAX;
  1014. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1015. buf->memory_property_flags = req_flags;
  1016. if (memory_type_index == UINT32_MAX && fallback_flags) {
  1017. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1018. buf->memory_property_flags = fallback_flags;
  1019. }
  1020. if (memory_type_index == UINT32_MAX) {
  1021. device->device.destroyBuffer(buf->buffer);
  1022. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1023. }
  1024. try {
  1025. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1026. } catch (const vk::SystemError& e) {
  1027. if (buf->memory_property_flags != fallback_flags) {
  1028. // Try again with fallback flags
  1029. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1030. buf->memory_property_flags = fallback_flags;
  1031. try {
  1032. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1033. }
  1034. catch (const vk::SystemError& e) {
  1035. device->device.destroyBuffer(buf->buffer);
  1036. throw e;
  1037. }
  1038. } else {
  1039. // Out of Host/Device memory, clean up buffer
  1040. device->device.destroyBuffer(buf->buffer);
  1041. throw e;
  1042. }
  1043. }
  1044. buf->ptr = nullptr;
  1045. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1046. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1047. }
  1048. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1049. buf->device = device;
  1050. buf->size = size;
  1051. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1052. device->memory_logger->log_allocation(buf, size);
  1053. #endif
  1054. return buf;
  1055. }
  1056. static vk_buffer ggml_vk_create_buffer_check(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  1057. try {
  1058. return ggml_vk_create_buffer(device, size, req_flags, fallback_flags);
  1059. } catch (const vk::SystemError& e) {
  1060. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1061. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1062. throw e;
  1063. }
  1064. }
  1065. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1066. vk_buffer buf;
  1067. try {
  1068. if (device->uma) {
  1069. // Fall back to host memory type
  1070. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1071. } else {
  1072. // use rebar if available, otherwise fallback to device only visible memory
  1073. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1074. }
  1075. } catch (const vk::SystemError& e) {
  1076. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1077. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1078. throw e;
  1079. }
  1080. return buf;
  1081. }
  1082. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1083. if (buf == nullptr) {
  1084. return;
  1085. }
  1086. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1087. if (buf->device != nullptr) {
  1088. buf->device->memory_logger->log_deallocation(buf);
  1089. }
  1090. #endif
  1091. buf.reset();
  1092. }
  1093. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1094. return { buf, 0, VK_WHOLE_SIZE };
  1095. }
  1096. static void ggml_vk_sync_buffers(vk_context& ctx) {
  1097. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1098. const bool transfer_queue = ctx->q->transfer_only;
  1099. ctx->s->buffer.pipelineBarrier(
  1100. ctx->q->stage_flags,
  1101. ctx->q->stage_flags,
  1102. {},
  1103. { {
  1104. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1105. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1106. } },
  1107. {},
  1108. {}
  1109. );
  1110. }
  1111. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1112. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1113. if (events.empty()) {
  1114. return;
  1115. }
  1116. ctx->s->buffer.waitEvents(
  1117. events,
  1118. ctx->q->stage_flags,
  1119. ctx->q->stage_flags,
  1120. {},
  1121. {},
  1122. {}
  1123. );
  1124. }
  1125. // number of rows/cols for flash attention shader
  1126. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1127. static std::array<uint32_t, 2> fa_rows_cols(uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) {
  1128. GGML_UNUSED(clamp);
  1129. // small rows, large cols
  1130. if (small_rows) {
  1131. return {flash_attention_num_small_rows, 128};
  1132. }
  1133. // small cols to reduce register count
  1134. if (ggml_is_quantized(type) || D == 256) {
  1135. return {64, 32};
  1136. }
  1137. return {64, 64};
  1138. };
  1139. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id) {
  1140. // Needs to be kept up to date on shader changes
  1141. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1142. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1143. const uint32_t warps = warptile[0] / warptile[10];
  1144. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1145. const uint32_t mmid_row_ids = mul_mat_id ? 3072 * sizeof(uint32_t) : 0;
  1146. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1147. return (load_bufs + mmid_row_ids + coopmat_stage) <= device->properties.limits.maxComputeSharedMemorySize;
  1148. }
  1149. static void ggml_vk_load_shaders(vk_device& device) {
  1150. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1151. std::cerr << "ggml_vulkan: Compiling shaders";
  1152. // some shaders have a minimum subgroup size
  1153. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1154. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  1155. // mulmat
  1156. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  1157. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  1158. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  1159. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  1160. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  1161. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  1162. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  1163. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  1164. uint32_t l_align, m_align, s_align;
  1165. if (device->coopmat2) {
  1166. // spec constants and tile sizes for non-quant matmul/matmul_id
  1167. l_warptile = { 256, 128, 256, 64 };
  1168. m_warptile = { 256, 128, 128, 64 };
  1169. s_warptile = { 128, 64, 64, 64 };
  1170. l_wg_denoms = {128, 256, 1 };
  1171. m_wg_denoms = {128, 128, 1 };
  1172. s_wg_denoms = { 64, 64, 1 };
  1173. // spec constants and tile sizes for quant matmul (non-Qi_K)
  1174. l_warptile_mmq = { 256, 128, 256, 64 };
  1175. m_warptile_mmq = { 256, 128, 128, 64 };
  1176. s_warptile_mmq = { 256, 128, 128, 64 };
  1177. l_mmq_wg_denoms = { 128, 256, 1 };
  1178. m_mmq_wg_denoms = { 128, 128, 1 };
  1179. s_mmq_wg_denoms = { 128, 128, 1 };
  1180. // spec constants and tile sizes for quant matmul (Qi_K)
  1181. l_warptile_mmq_k = { 256, 128, 512, 16 };
  1182. m_warptile_mmq_k = { 256, 128, 256, 16 };
  1183. s_warptile_mmq_k = { 256, 32, 128, 64 };
  1184. l_mmq_wg_denoms_k = { 128, 512, 1 };
  1185. m_mmq_wg_denoms_k = { 128, 256, 1 };
  1186. s_mmq_wg_denoms_k = { 32, 128, 1 };
  1187. // spec constants and tile sizes for quant matmul_id
  1188. l_warptile_mmqid = { 256, 128, 128, 16 };
  1189. m_warptile_mmqid = { 256, 128, 64, 16 };
  1190. s_warptile_mmqid = { 256, 64, 64, 16 };
  1191. l_mmqid_wg_denoms = { 128, 128, 1 };
  1192. m_mmqid_wg_denoms = { 128, 64, 1 };
  1193. s_mmqid_wg_denoms = { 64, 64, 1 };
  1194. l_align = 128;
  1195. m_align = 64;
  1196. s_align = 32;
  1197. } else {
  1198. // Matrix cores require different warp group sizes
  1199. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  1200. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  1201. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  1202. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  1203. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  1204. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  1205. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  1206. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  1207. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  1208. l_warptile = { 128, 128, 128, 16, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1209. m_warptile = { 128, 64, 64, 16, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1210. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1211. l_warptile_mmq = { 128, 128, 128, 32, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1212. m_warptile_mmq = { 128, 64, 64, 32, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1213. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1214. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  1215. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  1216. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  1217. l_align = 128;
  1218. m_align = 64;
  1219. s_align = 32;
  1220. // Fallback to smaller sizes if there's not enough shared memory. Given the current shaders
  1221. // and tile sizes, this should handle 16KB, 32KB, and 48KB+.
  1222. // This logic doesn't explicitly account for the 12KB row_ids in the mul_mat_mat_id shaders.
  1223. // But the numbers happen to work out for 32KB shared memory size that when using the medium
  1224. // size there's enough room for everything, and we assert for this.
  1225. uint32_t shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1226. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1227. l_warptile = m_warptile;
  1228. l_wg_denoms = m_wg_denoms;
  1229. shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1230. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1231. }
  1232. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1233. // assert mul_mat_mat_id shaders will fit.
  1234. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1235. }
  1236. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1237. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1238. if (device->properties.limits.maxComputeSharedMemorySize == 32768) {
  1239. l_warptile_mmq = m_warptile_mmq;
  1240. l_mmq_wg_denoms = m_mmq_wg_denoms;
  1241. } else {
  1242. l_warptile_mmq = s_warptile_mmq;
  1243. l_mmq_wg_denoms = s_mmq_wg_denoms;
  1244. }
  1245. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1246. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1247. }
  1248. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1249. // assert mul_mat_mat_id shaders will fit.
  1250. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1251. }
  1252. // Disable medium and large matrix multiplication if not enough shared memory is available
  1253. // Check mmq warptiles as the largest configuration
  1254. // Throw an error if not enough for any matrix multiplication is available
  1255. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false)) {
  1256. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  1257. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  1258. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false)) {
  1259. device->mul_mat_m = false;
  1260. device->mul_mat_l = false;
  1261. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false)) {
  1262. device->mul_mat_l = false;
  1263. }
  1264. // Disable mul_mat_id if not enough shared memory is available
  1265. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, true)) {
  1266. device->mul_mat_id_s = false;
  1267. device->mul_mat_id_m = false;
  1268. device->mul_mat_id_l = false;
  1269. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, true)) {
  1270. device->mul_mat_id_m = false;
  1271. device->mul_mat_id_l = false;
  1272. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, true)) {
  1273. device->mul_mat_id_l = false;
  1274. }
  1275. }
  1276. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1277. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  1278. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1279. std::vector<std::future<void>> compiles;
  1280. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const std::string &entrypoint,
  1281. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  1282. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  1283. {
  1284. // wait until fewer than N compiles are in progress
  1285. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  1286. std::unique_lock<std::mutex> guard(compile_count_mutex);
  1287. while (compile_count >= N) {
  1288. compile_count_cond.wait(guard);
  1289. }
  1290. compile_count++;
  1291. }
  1292. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), name, spv_size, spv_data, entrypoint,
  1293. parameter_count, push_constant_size, wg_denoms, specialization_constants, align, disable_robustness, require_full_subgroups, required_subgroup_size));
  1294. };
  1295. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1296. if (device->coopmat2) {
  1297. auto const &fa_wg_denoms = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  1298. return {fa_rows_cols(D, clamp, type, small_rows)[0], 1, 1};
  1299. };
  1300. auto const &fa_spec_constants = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  1301. // For large number of rows, 128 invocations seems to work best.
  1302. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  1303. // can't use 256 for D==80.
  1304. uint32_t wg_size = (small_rows && (D % 32) == 0) ? 256 : 128;
  1305. auto rows_cols = fa_rows_cols(D, clamp, type, small_rows);
  1306. return {wg_size, rows_cols[0], rows_cols[1], (D), clamp};
  1307. };
  1308. #define CREATE_FA2(TYPE, NAMELC, D) \
  1309. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][0], "flash_attn_f32_f16_D" #D "_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1310. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1311. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][0], "flash_attn_f32_f16_D" #D "_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1312. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1313. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][0], "flash_attn_f32_f16_D" #D "_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1314. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1315. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][0], "flash_attn_f32_f16_D" #D "_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1316. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1317. #define CREATE_FA(TYPE, NAMELC) \
  1318. CREATE_FA2(TYPE, NAMELC, 64) \
  1319. CREATE_FA2(TYPE, NAMELC, 80) \
  1320. CREATE_FA2(TYPE, NAMELC, 96) \
  1321. CREATE_FA2(TYPE, NAMELC, 112) \
  1322. CREATE_FA2(TYPE, NAMELC, 128) \
  1323. CREATE_FA2(TYPE, NAMELC, 256)
  1324. CREATE_FA(GGML_TYPE_F16, f16)
  1325. CREATE_FA(GGML_TYPE_Q4_0, q4_0)
  1326. CREATE_FA(GGML_TYPE_Q4_1, q4_1)
  1327. CREATE_FA(GGML_TYPE_Q5_0, q5_0)
  1328. CREATE_FA(GGML_TYPE_Q5_1, q5_1)
  1329. CREATE_FA(GGML_TYPE_Q8_0, q8_0)
  1330. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  1331. //CREATE_FA(GGML_TYPE_Q2_K, q2_k)
  1332. //CREATE_FA(GGML_TYPE_Q3_K, q3_k)
  1333. //CREATE_FA(GGML_TYPE_Q4_K, q4_k)
  1334. //CREATE_FA(GGML_TYPE_Q5_K, q5_k)
  1335. //CREATE_FA(GGML_TYPE_Q6_K, q6_k)
  1336. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl)
  1337. #undef CREATE_FA
  1338. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1339. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1340. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1341. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1342. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1343. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1344. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1345. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1346. // Create 2 variants, {f16,f32} accumulator
  1347. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1348. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1349. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1350. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1351. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1352. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1353. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1354. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1355. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1356. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1357. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1358. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1359. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1360. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1361. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1362. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1363. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1364. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1365. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1366. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1367. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1368. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1369. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1370. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1371. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1372. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1373. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1374. #undef CREATE_MM
  1375. #undef CREATE_MM2
  1376. } else
  1377. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1378. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  1379. if (device->coopmat_support) {
  1380. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1381. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1382. if (device->mul_mat ## ID ## _l) \
  1383. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  1384. if (device->mul_mat ## ID ## _m) \
  1385. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  1386. if (device->mul_mat ## ID ## _s) \
  1387. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  1388. if (device->mul_mat ## ID ## _l) \
  1389. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  1390. if (device->mul_mat ## ID ## _m) \
  1391. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  1392. if (device->mul_mat ## ID ## _s) \
  1393. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  1394. // Create 2 variants, {f16,f32} accumulator
  1395. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1396. if (device->coopmat_acc_f16_support) { \
  1397. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1398. } \
  1399. if (device->coopmat_acc_f32_support) { \
  1400. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1401. } \
  1402. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1403. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1404. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1405. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1406. if (device->coopmat_acc_f16_support) {
  1407. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1408. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1409. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1410. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1411. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1412. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1413. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1414. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1415. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1416. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1417. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1418. } else {
  1419. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1420. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1421. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1422. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1423. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1424. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1425. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1426. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1427. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1428. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1429. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1430. }
  1431. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1432. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1433. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1434. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1435. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1436. if (device->coopmat_acc_f16_support) {
  1437. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1438. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1439. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1440. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1441. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1442. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1443. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1444. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1445. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1446. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1447. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1448. } else {
  1449. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1450. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1451. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1452. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1453. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1454. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1455. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1456. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1457. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1458. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1459. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1460. }
  1461. }
  1462. #undef CREATE_MM2
  1463. #undef CREATE_MM
  1464. } else
  1465. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  1466. if (device->fp16) {
  1467. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1468. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1469. if (device->mul_mat ## ID ## _l) \
  1470. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1471. if (device->mul_mat ## ID ## _m) \
  1472. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1473. if (device->mul_mat ## ID ## _s) \
  1474. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1475. if (device->mul_mat ## ID ## _l) \
  1476. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1477. if (device->mul_mat ## ID ## _m) \
  1478. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1479. if (device->mul_mat ## ID ## _s) \
  1480. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1481. // Create 2 variants, {f16,f32} accumulator
  1482. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1483. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1484. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1485. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1486. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1487. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1488. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1489. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1490. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1491. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1492. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1493. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1494. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1495. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1496. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1497. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1498. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1499. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1500. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1501. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1502. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1503. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1504. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1505. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1506. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1507. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1508. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1509. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1510. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1511. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1512. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1513. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1514. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1515. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1516. }
  1517. #undef CREATE_MM2
  1518. #undef CREATE_MM
  1519. } else {
  1520. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1521. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1522. if (device->mul_mat ## ID ## _l) \
  1523. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1524. if (device->mul_mat ## ID ## _m) \
  1525. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1526. if (device->mul_mat ## ID ## _s) \
  1527. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1528. if (device->mul_mat ## ID ## _l) \
  1529. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1530. if (device->mul_mat ## ID ## _m) \
  1531. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1532. if (device->mul_mat ## ID ## _s) \
  1533. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1534. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1535. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1536. CREATE_MM(pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1537. CREATE_MM(pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1538. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1539. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1540. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1541. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1542. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1543. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1544. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1545. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1546. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1547. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1548. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1549. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1550. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1551. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1552. CREATE_MM(pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1553. CREATE_MM(pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1554. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1555. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1556. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1557. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1558. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1559. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1560. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1561. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1562. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1563. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1564. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1565. }
  1566. #undef CREATE_MM
  1567. }
  1568. // mul mat vec
  1569. // the number of rows computed per shader depends on GPU model and quant
  1570. uint32_t rm_stdq = 1;
  1571. uint32_t rm_kq = 2;
  1572. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  1573. if (device->subgroup_min_size == 64 && device->subgroup_max_size == 64) { // GCN
  1574. rm_stdq = 2;
  1575. rm_kq = 4;
  1576. }
  1577. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  1578. rm_stdq = 2;
  1579. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  1580. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32_"+std::to_string(i+1), mul_mat_vec_f32_f32_f32_len, mul_mat_vec_f32_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1581. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32_"+std::to_string(i+1), mul_mat_vec_f16_f32_f32_len, mul_mat_vec_f16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1582. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f32_f32_len, mul_mat_vec_q4_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1583. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f32_f32_len, mul_mat_vec_q4_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1584. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f32_f32_len, mul_mat_vec_q5_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1585. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f32_f32_len, mul_mat_vec_q5_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1586. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f32_f32_len, mul_mat_vec_q8_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  1587. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f32_f32_len, mul_mat_vec_q2_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1588. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f32_f32_len, mul_mat_vec_q3_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1589. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f32_f32_len, mul_mat_vec_q4_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1590. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f32_f32_len, mul_mat_vec_q5_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1591. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f32_f32_len, mul_mat_vec_q6_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1592. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f32_f32_len, mul_mat_vec_iq4_nl_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq, i+1}, 1, true);
  1593. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32_"+std::to_string(i+1), mul_mat_vec_f32_f16_f32_len, mul_mat_vec_f32_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1594. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32_"+std::to_string(i+1), mul_mat_vec_f16_f16_f32_len, mul_mat_vec_f16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1595. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f16_f32_len, mul_mat_vec_q4_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1596. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f16_f32_len, mul_mat_vec_q4_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1597. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f16_f32_len, mul_mat_vec_q5_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1598. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f16_f32_len, mul_mat_vec_q5_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1599. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f16_f32_len, mul_mat_vec_q8_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  1600. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f16_f32_len, mul_mat_vec_q2_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1601. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f16_f32_len, mul_mat_vec_q3_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1602. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f16_f32_len, mul_mat_vec_q4_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1603. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f16_f32_len, mul_mat_vec_q5_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1604. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f16_f32_len, mul_mat_vec_q6_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1605. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f16_f32_len, mul_mat_vec_iq4_nl_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq, i+1}, 1, true);
  1606. }
  1607. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", mul_mat_vec_id_f32_f32_len, mul_mat_vec_id_f32_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1608. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", mul_mat_vec_id_f16_f32_len, mul_mat_vec_id_f16_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1609. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", mul_mat_vec_id_q4_0_f32_len, mul_mat_vec_id_q4_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  1610. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", mul_mat_vec_id_q4_1_f32_len, mul_mat_vec_id_q4_1_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  1611. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", mul_mat_vec_id_q5_0_f32_len, mul_mat_vec_id_q5_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  1612. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", mul_mat_vec_id_q5_1_f32_len, mul_mat_vec_id_q5_1_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  1613. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", mul_mat_vec_id_q8_0_f32_len, mul_mat_vec_id_q8_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  1614. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", mul_mat_vec_id_q2_k_f32_len, mul_mat_vec_id_q2_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  1615. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", mul_mat_vec_id_q3_k_f32_len, mul_mat_vec_id_q3_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  1616. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", mul_mat_vec_id_q4_k_f32_len, mul_mat_vec_id_q4_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  1617. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", mul_mat_vec_id_q5_k_f32_len, mul_mat_vec_id_q5_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  1618. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", mul_mat_vec_id_q6_k_f32_len, mul_mat_vec_id_q6_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  1619. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq}, 1, true);
  1620. // dequant shaders
  1621. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", dequant_f32_len, dequant_f32_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1622. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1623. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1624. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1625. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1626. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1627. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1628. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1629. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  1630. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1631. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1632. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1633. // get_rows
  1634. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1635. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1636. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_0], "get_rows_q4_0", get_rows_q4_0_len, get_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1637. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_1], "get_rows_q4_1", get_rows_q4_1_len, get_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1638. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_0], "get_rows_q5_0", get_rows_q5_0_len, get_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1639. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_1], "get_rows_q5_1", get_rows_q5_1_len, get_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1640. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q8_0], "get_rows_q8_0", get_rows_q8_0_len, get_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1641. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1642. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1643. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F16 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1644. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_0], "get_rows_q4_0_f32", get_rows_q4_0_f32_len, get_rows_q4_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1645. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_1], "get_rows_q4_1_f32", get_rows_q4_1_f32_len, get_rows_q4_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1646. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_0], "get_rows_q5_0_f32", get_rows_q5_0_f32_len, get_rows_q5_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1647. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_1], "get_rows_q5_1_f32", get_rows_q5_1_f32_len, get_rows_q5_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1648. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q8_0], "get_rows_q8_0_f32", get_rows_q8_0_f32_len, get_rows_q8_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1649. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1650. ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1);
  1651. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_p021_f16_f32, "mul_mat_vec_p021_f16_f32", mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1652. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 3, 7 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1653. ggml_vk_create_pipeline(device, device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1654. ggml_vk_create_pipeline(device, device->pipeline_group_norm_f32, "group_norm_f32", group_norm_f32_len, group_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1655. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1656. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f32, "cpy_f32_f32", cpy_f32_f32_len, cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1657. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1658. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f16, "cpy_f16_f16", cpy_f16_f16_len, cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1659. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f32, "contig_cpy_f32_f32", contig_cpy_f32_f32_len, contig_cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1660. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1661. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f16, "contig_cpy_f16_f16", contig_cpy_f16_f16_len, contig_cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1662. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_len, cpy_f32_q4_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1);
  1663. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_len, cpy_f32_q4_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1);
  1664. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_len, cpy_f32_q5_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1);
  1665. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_len, cpy_f32_q5_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1);
  1666. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_len, cpy_f32_q8_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1);
  1667. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_len, cpy_f32_iq4_nl_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1);
  1668. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_0], "cpy_q4_0_f32", cpy_q4_0_f32_len, cpy_q4_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1);
  1669. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_1], "cpy_q4_1_f32", cpy_q4_1_f32_len, cpy_q4_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1);
  1670. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_0], "cpy_q5_0_f32", cpy_q5_0_f32_len, cpy_q5_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1);
  1671. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_1], "cpy_q5_1_f32", cpy_q5_1_f32_len, cpy_q5_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1);
  1672. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q8_0], "cpy_q8_0_f32", cpy_q8_0_f32_len, cpy_q8_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1);
  1673. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_IQ4_NL], "cpy_iq4_nl_f32", cpy_iq4_nl_f32_len, cpy_iq4_nl_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1);
  1674. ggml_vk_create_pipeline(device, device->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1675. ggml_vk_create_pipeline(device, device->pipeline_add_f32_norepeat, "add_f32_norepeat", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1676. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16, "add_f16_f32_f16", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1677. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16_norepeat, "add_f16_f32_f16_norepeat", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1678. ggml_vk_create_pipeline(device, device->pipeline_acc_f32, "acc_f32", acc_f32_len, acc_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1679. ggml_vk_create_pipeline(device, device->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1680. ggml_vk_create_pipeline(device, device->pipeline_mul_f32_norepeat, "mul_f32_norepeat", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1681. ggml_vk_create_pipeline(device, device->pipeline_div_f32, "div_f32", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1682. ggml_vk_create_pipeline(device, device->pipeline_div_f32_norepeat, "div_f32_norepeat", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1683. ggml_vk_create_pipeline(device, device->pipeline_concat_f32, "concat_f32", concat_f32_len, concat_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1684. ggml_vk_create_pipeline(device, device->pipeline_concat_f16, "concat_f16", concat_f16_len, concat_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1685. ggml_vk_create_pipeline(device, device->pipeline_concat_i32, "concat_i32", concat_i32_len, concat_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1686. ggml_vk_create_pipeline(device, device->pipeline_upscale_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {}, 1);
  1687. ggml_vk_create_pipeline(device, device->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1688. ggml_vk_create_pipeline(device, device->pipeline_sqr_f32, "sqr_f32", sqr_f32_len, sqr_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1689. ggml_vk_create_pipeline(device, device->pipeline_sin_f32, "sin_f32", sin_f32_len, sin_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1690. ggml_vk_create_pipeline(device, device->pipeline_cos_f32, "cos_f32", cos_f32_len, cos_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1691. ggml_vk_create_pipeline(device, device->pipeline_clamp_f32, "clamp_f32", clamp_f32_len, clamp_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1692. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1693. ggml_vk_create_pipeline(device, device->pipeline_repeat_f32, "repeat_f32", repeat_f32_len, repeat_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1694. ggml_vk_create_pipeline(device, device->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1695. ggml_vk_create_pipeline(device, device->pipeline_gelu_quick_f32, "gelu_quick_f32", gelu_quick_f32_len, gelu_quick_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1696. ggml_vk_create_pipeline(device, device->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1697. ggml_vk_create_pipeline(device, device->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1698. ggml_vk_create_pipeline(device, device->pipeline_leaky_relu_f32, "leaky_relu_f32", leaky_relu_f32_len, leaky_relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1699. ggml_vk_create_pipeline(device, device->pipeline_tanh_f32, "tanh_f32", tanh_f32_len, tanh_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1700. ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {1, 512, 1}, {}, 1, true);
  1701. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1702. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1703. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1704. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1705. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1706. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1707. if (device->float_controls_rte_fp16) {
  1708. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1709. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1710. } else {
  1711. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1712. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1713. }
  1714. ggml_vk_create_pipeline(device, device->pipeline_argsort_f32, "argsort_f32", argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1024, 1, 1}, {}, 1);
  1715. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1716. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32_len, im2col_f32_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1717. if (device->float_controls_rte_fp16) {
  1718. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte_len, im2col_f32_f16_rte_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1719. } else {
  1720. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_len, im2col_f32_f16_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1721. }
  1722. ggml_vk_create_pipeline(device, device->pipeline_timestep_embedding_f32, "timestep_embedding_f32", timestep_embedding_f32_len, timestep_embedding_f32_data, "main", 2, sizeof(vk_op_timestep_embedding_push_constants), {256, 1, 1}, {}, 1);
  1723. ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {512, 1, 1}, {}, 1);
  1724. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv6_f32, "rwkv_wkv6_f32", rwkv_wkv6_f32_len, rwkv_wkv6_f32_data, "main", 7, sizeof(vk_op_rwkv_wkv6_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  1725. for (auto &c : compiles) {
  1726. c.wait();
  1727. }
  1728. std::cerr << "Done!" << std::endl;
  1729. }
  1730. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props);
  1731. static vk_device ggml_vk_get_device(size_t idx) {
  1732. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  1733. if (vk_instance.devices[idx] == nullptr) {
  1734. VK_LOG_DEBUG("Initializing new vk_device");
  1735. vk_device device = std::make_shared<vk_device_struct>();
  1736. vk_instance.devices[idx] = device;
  1737. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1738. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  1739. #endif
  1740. #ifdef GGML_VULKAN_PERF
  1741. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  1742. #endif
  1743. size_t dev_num = vk_instance.device_indices[idx];
  1744. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  1745. if (dev_num >= physical_devices.size()) {
  1746. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  1747. throw std::runtime_error("Device not found");
  1748. }
  1749. device->physical_device = physical_devices[dev_num];
  1750. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  1751. bool fp16_storage = false;
  1752. bool fp16_compute = false;
  1753. bool maintenance4_support = false;
  1754. bool sm_builtins = false;
  1755. bool amd_shader_core_properties2 = false;
  1756. bool pipeline_robustness = false;
  1757. bool coopmat2_support = false;
  1758. device->coopmat_support = false;
  1759. // Check if maintenance4 is supported
  1760. for (const auto& properties : ext_props) {
  1761. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  1762. maintenance4_support = true;
  1763. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1764. fp16_storage = true;
  1765. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1766. fp16_compute = true;
  1767. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  1768. sm_builtins = true;
  1769. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  1770. amd_shader_core_properties2 = true;
  1771. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  1772. pipeline_robustness = true;
  1773. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  1774. device->subgroup_size_control = true;
  1775. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  1776. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  1777. device->coopmat_support = true;
  1778. device->coopmat_m = 0;
  1779. device->coopmat_n = 0;
  1780. device->coopmat_k = 0;
  1781. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  1782. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  1783. coopmat2_support = true;
  1784. }
  1785. }
  1786. vk::PhysicalDeviceProperties2 props2;
  1787. vk::PhysicalDeviceMaintenance3Properties props3;
  1788. vk::PhysicalDeviceMaintenance4Properties props4;
  1789. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  1790. vk::PhysicalDeviceDriverProperties driver_props;
  1791. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  1792. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  1793. vk::PhysicalDeviceVulkan12Properties vk12_props;
  1794. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  1795. props2.pNext = &props3;
  1796. props3.pNext = &subgroup_props;
  1797. subgroup_props.pNext = &driver_props;
  1798. driver_props.pNext = &vk12_props;
  1799. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  1800. if (maintenance4_support) {
  1801. last_struct->pNext = (VkBaseOutStructure *)&props4;
  1802. last_struct = (VkBaseOutStructure *)&props4;
  1803. }
  1804. if (sm_builtins) {
  1805. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  1806. last_struct = (VkBaseOutStructure *)&sm_props;
  1807. }
  1808. if (amd_shader_core_properties2) {
  1809. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1810. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1811. }
  1812. if (device->subgroup_size_control) {
  1813. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  1814. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  1815. }
  1816. #if defined(VK_NV_cooperative_matrix2)
  1817. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  1818. if (coopmat2_support) {
  1819. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  1820. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  1821. }
  1822. #endif
  1823. device->physical_device.getProperties2(&props2);
  1824. device->properties = props2.properties;
  1825. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  1826. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  1827. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  1828. } else if (maintenance4_support) {
  1829. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  1830. } else {
  1831. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  1832. }
  1833. device->vendor_id = device->properties.vendorID;
  1834. device->subgroup_size = subgroup_props.subgroupSize;
  1835. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1836. if (sm_builtins) {
  1837. device->shader_core_count = sm_props.shaderSMCount;
  1838. } else if (amd_shader_core_properties2) {
  1839. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  1840. } else {
  1841. device->shader_core_count = 0;
  1842. }
  1843. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  1844. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  1845. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1846. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props)) {
  1847. device->coopmat_support = false;
  1848. }
  1849. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  1850. // Try to find a non-graphics compute queue and transfer-focused queues
  1851. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1852. const uint32_t transfer_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eTransfer, vk::QueueFlagBits::eCompute | vk::QueueFlagBits::eGraphics, compute_queue_family_index, 1);
  1853. const float priorities[] = { 1.0f, 1.0f };
  1854. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1855. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1856. if (compute_queue_family_index != transfer_queue_family_index) {
  1857. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1858. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1859. } else if(!device->single_queue) {
  1860. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1861. } else {
  1862. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1863. }
  1864. vk::DeviceCreateInfo device_create_info;
  1865. std::vector<const char *> device_extensions;
  1866. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  1867. VkPhysicalDeviceFeatures2 device_features2;
  1868. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1869. device_features2.pNext = nullptr;
  1870. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1871. VkPhysicalDeviceVulkan11Features vk11_features;
  1872. vk11_features.pNext = nullptr;
  1873. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1874. device_features2.pNext = &vk11_features;
  1875. VkPhysicalDeviceVulkan12Features vk12_features;
  1876. vk12_features.pNext = nullptr;
  1877. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1878. vk11_features.pNext = &vk12_features;
  1879. last_struct = (VkBaseOutStructure *)&vk12_features;
  1880. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  1881. pl_robustness_features.pNext = nullptr;
  1882. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  1883. pl_robustness_features.pipelineRobustness = VK_FALSE;
  1884. if (pipeline_robustness) {
  1885. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  1886. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  1887. device_extensions.push_back("VK_EXT_pipeline_robustness");
  1888. }
  1889. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  1890. subgroup_size_control_features.pNext = nullptr;
  1891. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  1892. subgroup_size_control_features.computeFullSubgroups = false;
  1893. subgroup_size_control_features.subgroupSizeControl = false;
  1894. if (device->subgroup_size_control) {
  1895. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  1896. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  1897. }
  1898. #if defined(VK_KHR_cooperative_matrix)
  1899. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  1900. coopmat_features.pNext = nullptr;
  1901. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  1902. coopmat_features.cooperativeMatrix = VK_FALSE;
  1903. if (device->coopmat_support) {
  1904. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  1905. last_struct = (VkBaseOutStructure *)&coopmat_features;
  1906. }
  1907. #endif
  1908. #if defined(VK_NV_cooperative_matrix2)
  1909. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  1910. coopmat2_features.pNext = nullptr;
  1911. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  1912. if (coopmat2_support) {
  1913. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  1914. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  1915. device_extensions.push_back("VK_NV_cooperative_matrix2");
  1916. }
  1917. #endif
  1918. VkPhysicalDeviceMaintenance4Features maint4_features {};
  1919. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  1920. if (maintenance4_support) {
  1921. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  1922. last_struct = (VkBaseOutStructure *)&maint4_features;
  1923. device_extensions.push_back("VK_KHR_maintenance4");
  1924. }
  1925. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  1926. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  1927. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  1928. if (device->subgroup_size_control) {
  1929. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  1930. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  1931. device_extensions.push_back("VK_EXT_subgroup_size_control");
  1932. }
  1933. device->subgroup_size_control = device->subgroup_size_control &&
  1934. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  1935. subgroup_size_control_features.subgroupSizeControl;
  1936. if (device->subgroup_size_control) {
  1937. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  1938. }
  1939. #if defined(VK_KHR_cooperative_matrix)
  1940. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  1941. #endif
  1942. if (coopmat2_support) {
  1943. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1944. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  1945. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  1946. coopmat2_features.cooperativeMatrixReductions &&
  1947. coopmat2_features.cooperativeMatrixConversions &&
  1948. coopmat2_features.cooperativeMatrixPerElementOperations &&
  1949. coopmat2_features.cooperativeMatrixTensorAddressing &&
  1950. coopmat2_features.cooperativeMatrixBlockLoads &&
  1951. vk12_features.bufferDeviceAddress) {
  1952. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  1953. uint32_t count = 0;
  1954. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  1955. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  1956. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  1957. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  1958. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  1959. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  1960. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  1961. flexible_dimensions.resize(count, empty_prop);
  1962. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  1963. bool found_fp16_128 = false,
  1964. found_fp16_256 = false,
  1965. found_fp32_128 = false,
  1966. found_fp32_256 = false;
  1967. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  1968. // with 32x16x16 and 256 with 32x32x16.
  1969. for (auto &prop : flexible_dimensions) {
  1970. if (prop.saturatingAccumulation == VK_FALSE &&
  1971. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  1972. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1973. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1974. if (prop.workgroupInvocations == 128 &&
  1975. prop.MGranularity <= 32 &&
  1976. prop.NGranularity <= 16 &&
  1977. prop.KGranularity <= 16) {
  1978. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1979. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1980. found_fp16_128 = true;
  1981. }
  1982. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1983. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1984. found_fp32_128 = true;
  1985. }
  1986. }
  1987. if (prop.workgroupInvocations == 256 &&
  1988. prop.MGranularity <= 32 &&
  1989. prop.NGranularity <= 32 &&
  1990. prop.KGranularity <= 16) {
  1991. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1992. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1993. found_fp16_256 = true;
  1994. }
  1995. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1996. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1997. found_fp32_256 = true;
  1998. }
  1999. }
  2000. }
  2001. }
  2002. if (found_fp16_128 && found_fp16_256 &&
  2003. found_fp32_128 && found_fp32_256 &&
  2004. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  2005. device->coopmat2 = true;
  2006. }
  2007. }
  2008. #endif
  2009. }
  2010. if (!vk11_features.storageBuffer16BitAccess) {
  2011. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  2012. throw std::runtime_error("Unsupported device");
  2013. }
  2014. device_extensions.push_back("VK_KHR_16bit_storage");
  2015. #ifdef GGML_VULKAN_VALIDATE
  2016. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  2017. #endif
  2018. if (device->fp16) {
  2019. device_extensions.push_back("VK_KHR_shader_float16_int8");
  2020. }
  2021. #if defined(VK_KHR_cooperative_matrix)
  2022. if (device->coopmat_support) {
  2023. // Query supported shapes
  2024. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  2025. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  2026. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  2027. uint32_t cm_props_num;
  2028. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  2029. cm_props.resize(cm_props_num);
  2030. for (auto& prop : cm_props) {
  2031. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  2032. }
  2033. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  2034. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  2035. for (auto& prop : cm_props) {
  2036. VK_LOG_DEBUG("ggml_vulkan: M: " << prop.MSize << " N: " << prop.NSize << " K: " << prop.KSize << " A: " << vk::to_string((vk::ComponentTypeKHR)prop.AType) << " B: " << vk::to_string((vk::ComponentTypeKHR)prop.BType) << " C: " << vk::to_string((vk::ComponentTypeKHR)prop.CType) << " Result: " << vk::to_string((vk::ComponentTypeKHR)prop.ResultType) << " saturatingAccumulation: " << prop.saturatingAccumulation << " scope: " << vk::to_string((vk::ScopeKHR)prop.scope));
  2037. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  2038. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  2039. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  2040. ) {
  2041. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  2042. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  2043. // coopmat sizes not set yet
  2044. if (device->coopmat_m == 0) {
  2045. device->coopmat_acc_f32_support = true;
  2046. device->coopmat_m = prop.MSize;
  2047. device->coopmat_n = prop.NSize;
  2048. device->coopmat_k = prop.KSize;
  2049. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  2050. // Only enable if shape is identical
  2051. device->coopmat_acc_f32_support = true;
  2052. }
  2053. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  2054. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  2055. // coopmat sizes not set yet
  2056. if (device->coopmat_m == 0) {
  2057. device->coopmat_acc_f16_support = true;
  2058. device->coopmat_m = prop.MSize;
  2059. device->coopmat_n = prop.NSize;
  2060. device->coopmat_k = prop.KSize;
  2061. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  2062. // Only enable if shape is identical
  2063. device->coopmat_acc_f16_support = true;
  2064. }
  2065. }
  2066. }
  2067. }
  2068. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  2069. // No suitable matmul mode found
  2070. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  2071. device->coopmat_support = false;
  2072. }
  2073. }
  2074. if (device->coopmat_support) {
  2075. device_extensions.push_back("VK_KHR_cooperative_matrix");
  2076. }
  2077. #endif
  2078. device->name = GGML_VK_NAME + std::to_string(idx);
  2079. device_create_info = {
  2080. vk::DeviceCreateFlags(),
  2081. device_queue_create_infos,
  2082. {},
  2083. device_extensions
  2084. };
  2085. device_create_info.setPNext(&device_features2);
  2086. device->device = device->physical_device.createDevice(device_create_info);
  2087. // Queues
  2088. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  2089. // Shaders
  2090. // Disable matmul tile sizes early if performance low or not supported
  2091. switch (device->vendor_id) {
  2092. #ifndef GGML_VULKAN_RUN_TESTS
  2093. case VK_VENDOR_ID_AMD:
  2094. case VK_VENDOR_ID_INTEL:
  2095. device->mul_mat_l = false;
  2096. device->mul_mat_m = true;
  2097. device->mul_mat_s = true;
  2098. device->mul_mat_id_l = false;
  2099. device->mul_mat_id_m = true;
  2100. device->mul_mat_id_s = true;
  2101. break;
  2102. case VK_VENDOR_ID_APPLE:
  2103. device->mul_mat_l = false;
  2104. device->mul_mat_m = true;
  2105. device->mul_mat_s = false;
  2106. device->mul_mat_id_l = false;
  2107. device->mul_mat_id_m = true;
  2108. device->mul_mat_id_s = false;
  2109. break;
  2110. #endif
  2111. default:
  2112. device->mul_mat_l = true;
  2113. device->mul_mat_m = true;
  2114. device->mul_mat_s = true;
  2115. device->mul_mat_id_l = true;
  2116. device->mul_mat_id_m = true;
  2117. device->mul_mat_id_s = true;
  2118. break;
  2119. }
  2120. ggml_vk_load_shaders(device);
  2121. if (!device->single_queue) {
  2122. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  2123. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  2124. } else {
  2125. // TODO: Use pointer or reference to avoid copy
  2126. device->transfer_queue = device->compute_queue;
  2127. }
  2128. device->buffer_type = {
  2129. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  2130. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  2131. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  2132. };
  2133. device->fence = device->device.createFence({});
  2134. device->idx = idx;
  2135. return device;
  2136. }
  2137. return vk_instance.devices[idx];
  2138. }
  2139. static void ggml_vk_print_gpu_info(size_t idx) {
  2140. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2141. size_t dev_num = vk_instance.device_indices[idx];
  2142. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  2143. GGML_ASSERT(vk_instance_initialized);
  2144. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2145. if (dev_num >= devices.size()) {
  2146. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  2147. throw std::runtime_error("Device not found");
  2148. }
  2149. vk::PhysicalDevice physical_device = devices[dev_num];
  2150. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  2151. vk::PhysicalDeviceProperties2 props2;
  2152. vk::PhysicalDeviceMaintenance3Properties props3;
  2153. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  2154. vk::PhysicalDeviceDriverProperties driver_props;
  2155. props2.pNext = &props3;
  2156. props3.pNext = &subgroup_props;
  2157. subgroup_props.pNext = &driver_props;
  2158. physical_device.getProperties2(&props2);
  2159. const size_t subgroup_size = subgroup_props.subgroupSize;
  2160. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  2161. bool fp16_storage = false;
  2162. bool fp16_compute = false;
  2163. bool coopmat_support = false;
  2164. bool coopmat2_support = false;
  2165. for (auto properties : ext_props) {
  2166. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  2167. fp16_storage = true;
  2168. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  2169. fp16_compute = true;
  2170. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2171. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  2172. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  2173. coopmat_support = true;
  2174. #endif
  2175. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2176. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  2177. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  2178. coopmat2_support = true;
  2179. #endif
  2180. }
  2181. }
  2182. if (!ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props)) {
  2183. coopmat_support = false;
  2184. }
  2185. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  2186. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  2187. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  2188. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  2189. VkPhysicalDeviceFeatures2 device_features2;
  2190. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  2191. device_features2.pNext = nullptr;
  2192. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  2193. VkPhysicalDeviceVulkan11Features vk11_features;
  2194. vk11_features.pNext = nullptr;
  2195. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  2196. device_features2.pNext = &vk11_features;
  2197. VkPhysicalDeviceVulkan12Features vk12_features;
  2198. vk12_features.pNext = nullptr;
  2199. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  2200. vk11_features.pNext = &vk12_features;
  2201. // Pointer to the last chain element
  2202. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_features;
  2203. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2204. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  2205. coopmat_features.pNext = nullptr;
  2206. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  2207. coopmat_features.cooperativeMatrix = VK_FALSE;
  2208. if (coopmat_support) {
  2209. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  2210. last_struct = (VkBaseOutStructure *)&coopmat_features;
  2211. }
  2212. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  2213. fp16 = fp16 && vk12_features.shaderFloat16;
  2214. coopmat_support = coopmat_support && coopmat_features.cooperativeMatrix;
  2215. #endif
  2216. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  2217. std::string device_name = props2.properties.deviceName.data();
  2218. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | warp size: %zu | matrix cores: %s\n",
  2219. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, subgroup_size, matrix_cores.c_str());
  2220. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  2221. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  2222. }
  2223. }
  2224. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2225. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2226. void ggml_vk_instance_init() {
  2227. if (vk_instance_initialized) {
  2228. return;
  2229. }
  2230. VK_LOG_DEBUG("ggml_vk_instance_init()");
  2231. vk_instance_initialized = true;
  2232. uint32_t api_version = vk::enumerateInstanceVersion();
  2233. if (api_version < VK_API_VERSION_1_2) {
  2234. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  2235. GGML_ABORT("fatal error");
  2236. }
  2237. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  2238. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  2239. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  2240. #ifdef __APPLE__
  2241. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  2242. #endif
  2243. std::vector<const char*> layers;
  2244. if (validation_ext) {
  2245. layers.push_back("VK_LAYER_KHRONOS_validation");
  2246. }
  2247. std::vector<const char*> extensions;
  2248. if (validation_ext) {
  2249. extensions.push_back("VK_EXT_validation_features");
  2250. }
  2251. #ifdef __APPLE__
  2252. if (portability_enumeration_ext) {
  2253. extensions.push_back("VK_KHR_portability_enumeration");
  2254. }
  2255. #endif
  2256. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  2257. #ifdef __APPLE__
  2258. if (portability_enumeration_ext) {
  2259. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  2260. }
  2261. #endif
  2262. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  2263. vk::ValidationFeaturesEXT validation_features;
  2264. if (validation_ext) {
  2265. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  2266. validation_features = {
  2267. features_enable,
  2268. {},
  2269. };
  2270. validation_features.setPNext(nullptr);
  2271. instance_create_info.setPNext(&validation_features);
  2272. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  2273. }
  2274. vk_instance.instance = vk::createInstance(instance_create_info);
  2275. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  2276. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  2277. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  2278. if (devices_env != nullptr) {
  2279. std::string devices(devices_env);
  2280. std::replace(devices.begin(), devices.end(), ',', ' ');
  2281. std::stringstream ss(devices);
  2282. size_t tmp;
  2283. while (ss >> tmp) {
  2284. if(tmp >= num_available_devices) {
  2285. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  2286. throw std::runtime_error("Invalid Vulkan device index");
  2287. }
  2288. vk_instance.device_indices.push_back(tmp);
  2289. }
  2290. } else {
  2291. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2292. // Make sure at least one device exists
  2293. if (devices.empty()) {
  2294. std::cerr << "ggml_vulkan: Error: No devices found." << std::endl;
  2295. GGML_ABORT("fatal error");
  2296. }
  2297. // Default to using all dedicated GPUs
  2298. for (size_t i = 0; i < devices.size(); i++) {
  2299. vk::PhysicalDeviceProperties2 new_props;
  2300. vk::PhysicalDeviceDriverProperties new_driver;
  2301. vk::PhysicalDeviceIDProperties new_id;
  2302. new_props.pNext = &new_driver;
  2303. new_driver.pNext = &new_id;
  2304. devices[i].getProperties2(&new_props);
  2305. if (new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
  2306. // Check if there are two physical devices corresponding to the same GPU
  2307. auto old_device = std::find_if(
  2308. vk_instance.device_indices.begin(),
  2309. vk_instance.device_indices.end(),
  2310. [&devices, &new_id](const size_t k){
  2311. vk::PhysicalDeviceProperties2 old_props;
  2312. vk::PhysicalDeviceIDProperties old_id;
  2313. old_props.pNext = &old_id;
  2314. devices[k].getProperties2(&old_props);
  2315. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  2316. }
  2317. );
  2318. if (old_device == vk_instance.device_indices.end()) {
  2319. vk_instance.device_indices.push_back(i);
  2320. } else {
  2321. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  2322. // This can cause error when splitting layers aross the devices, need to keep only 1
  2323. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  2324. vk::PhysicalDeviceProperties2 old_props;
  2325. vk::PhysicalDeviceDriverProperties old_driver;
  2326. old_props.pNext = &old_driver;
  2327. devices[*old_device].getProperties2(&old_props);
  2328. std::map<vk::DriverId, int> driver_priorities {};
  2329. int old_priority = std::numeric_limits<int>::max();
  2330. int new_priority = std::numeric_limits<int>::max();
  2331. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  2332. // Smaller number -> higher priority
  2333. switch (old_props.properties.vendorID) {
  2334. case VK_VENDOR_ID_AMD:
  2335. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  2336. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  2337. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  2338. break;
  2339. case VK_VENDOR_ID_INTEL:
  2340. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  2341. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  2342. break;
  2343. case VK_VENDOR_ID_NVIDIA:
  2344. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  2345. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  2346. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  2347. #endif
  2348. break;
  2349. }
  2350. if (driver_priorities.count(old_driver.driverID)) {
  2351. old_priority = driver_priorities[old_driver.driverID];
  2352. }
  2353. if (driver_priorities.count(new_driver.driverID)) {
  2354. new_priority = driver_priorities[new_driver.driverID];
  2355. }
  2356. if (new_priority < old_priority) {
  2357. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  2358. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  2359. vk_instance.device_indices.push_back(i);
  2360. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  2361. }
  2362. else {
  2363. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  2364. }
  2365. }
  2366. }
  2367. }
  2368. // If no dedicated GPUs found, fall back to GPU 0
  2369. if (vk_instance.device_indices.empty()) {
  2370. vk_instance.device_indices.push_back(0);
  2371. }
  2372. }
  2373. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  2374. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  2375. ggml_vk_print_gpu_info(i);
  2376. }
  2377. }
  2378. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  2379. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  2380. ggml_vk_instance_init();
  2381. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2382. ctx->name = GGML_VK_NAME + std::to_string(idx);
  2383. ctx->device = ggml_vk_get_device(idx);
  2384. ctx->semaphore_idx = 0;
  2385. ctx->event_idx = 0;
  2386. ctx->prealloc_size_x = 0;
  2387. ctx->prealloc_size_y = 0;
  2388. ctx->prealloc_size_split_k = 0;
  2389. ctx->fence = ctx->device->device.createFence({});
  2390. #ifdef GGML_VULKAN_CHECK_RESULTS
  2391. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  2392. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  2393. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  2394. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  2395. #endif
  2396. }
  2397. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  2398. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  2399. switch (type) {
  2400. case GGML_TYPE_F32:
  2401. case GGML_TYPE_Q4_0:
  2402. case GGML_TYPE_Q4_1:
  2403. case GGML_TYPE_Q5_0:
  2404. case GGML_TYPE_Q5_1:
  2405. case GGML_TYPE_Q8_0:
  2406. case GGML_TYPE_Q2_K:
  2407. case GGML_TYPE_Q3_K:
  2408. case GGML_TYPE_Q4_K:
  2409. case GGML_TYPE_Q5_K:
  2410. case GGML_TYPE_Q6_K:
  2411. case GGML_TYPE_IQ4_NL:
  2412. break;
  2413. default:
  2414. return nullptr;
  2415. }
  2416. return ctx->device->pipeline_dequant[type];
  2417. }
  2418. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  2419. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  2420. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2421. return ctx->device->pipeline_matmul_f32;
  2422. }
  2423. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  2424. return ctx->device->pipeline_matmul_f32_f16;
  2425. }
  2426. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  2427. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2428. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  2429. }
  2430. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2431. return ctx->device->pipeline_matmul_f16.f16acc;
  2432. }
  2433. } else {
  2434. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2435. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  2436. }
  2437. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2438. return ctx->device->pipeline_matmul_f16.f32acc;
  2439. }
  2440. }
  2441. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  2442. return nullptr;
  2443. }
  2444. switch (src0_type) {
  2445. case GGML_TYPE_Q4_0:
  2446. case GGML_TYPE_Q4_1:
  2447. case GGML_TYPE_Q5_0:
  2448. case GGML_TYPE_Q5_1:
  2449. case GGML_TYPE_Q8_0:
  2450. case GGML_TYPE_Q2_K:
  2451. case GGML_TYPE_Q3_K:
  2452. case GGML_TYPE_Q4_K:
  2453. case GGML_TYPE_Q5_K:
  2454. case GGML_TYPE_Q6_K:
  2455. case GGML_TYPE_IQ4_NL:
  2456. break;
  2457. default:
  2458. return nullptr;
  2459. }
  2460. if (ctx->device->coopmat2) {
  2461. assert(src1_type == GGML_TYPE_F16);
  2462. return ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc;
  2463. }
  2464. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  2465. }
  2466. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols) {
  2467. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2468. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16);
  2469. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  2470. switch (a_type) {
  2471. case GGML_TYPE_F32:
  2472. case GGML_TYPE_F16:
  2473. case GGML_TYPE_Q4_0:
  2474. case GGML_TYPE_Q4_1:
  2475. case GGML_TYPE_Q5_0:
  2476. case GGML_TYPE_Q5_1:
  2477. case GGML_TYPE_Q8_0:
  2478. case GGML_TYPE_Q2_K:
  2479. case GGML_TYPE_Q3_K:
  2480. case GGML_TYPE_Q4_K:
  2481. case GGML_TYPE_Q5_K:
  2482. case GGML_TYPE_Q6_K:
  2483. case GGML_TYPE_IQ4_NL:
  2484. break;
  2485. default:
  2486. return nullptr;
  2487. }
  2488. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[a_type][num_cols-1];
  2489. }
  2490. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_id_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  2491. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  2492. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2493. return ctx->device->pipeline_matmul_id_f32;
  2494. }
  2495. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  2496. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2497. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  2498. }
  2499. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2500. return ctx->device->pipeline_matmul_id_f16.f16acc;
  2501. }
  2502. } else {
  2503. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2504. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  2505. }
  2506. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2507. return ctx->device->pipeline_matmul_id_f16.f32acc;
  2508. }
  2509. }
  2510. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  2511. switch (src0_type) {
  2512. case GGML_TYPE_Q4_0:
  2513. case GGML_TYPE_Q4_1:
  2514. case GGML_TYPE_Q5_0:
  2515. case GGML_TYPE_Q5_1:
  2516. case GGML_TYPE_Q8_0:
  2517. case GGML_TYPE_Q2_K:
  2518. case GGML_TYPE_Q3_K:
  2519. case GGML_TYPE_Q4_K:
  2520. case GGML_TYPE_Q5_K:
  2521. case GGML_TYPE_Q6_K:
  2522. case GGML_TYPE_IQ4_NL:
  2523. break;
  2524. default:
  2525. return nullptr;
  2526. }
  2527. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  2528. }
  2529. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2530. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2531. GGML_ASSERT(b_type == GGML_TYPE_F32);
  2532. switch (a_type) {
  2533. case GGML_TYPE_F32:
  2534. case GGML_TYPE_F16:
  2535. case GGML_TYPE_Q4_0:
  2536. case GGML_TYPE_Q4_1:
  2537. case GGML_TYPE_Q5_0:
  2538. case GGML_TYPE_Q5_1:
  2539. case GGML_TYPE_Q8_0:
  2540. case GGML_TYPE_Q2_K:
  2541. case GGML_TYPE_Q3_K:
  2542. case GGML_TYPE_Q4_K:
  2543. case GGML_TYPE_Q5_K:
  2544. case GGML_TYPE_Q6_K:
  2545. case GGML_TYPE_IQ4_NL:
  2546. break;
  2547. default:
  2548. return nullptr;
  2549. }
  2550. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  2551. }
  2552. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  2553. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  2554. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  2555. int best_i = -1;
  2556. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  2557. int worst_i = -1;
  2558. size_t worst_size = 0; //largest unused buffer seen so far
  2559. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2560. vk_buffer &b = ctx->buffer_pool[i];
  2561. if (b != nullptr && b->size >= size && b->size < best_size) {
  2562. best_i = i;
  2563. best_size = b->size;
  2564. }
  2565. if (b != nullptr && b->size > worst_size) {
  2566. worst_i = i;
  2567. worst_size = b->size;
  2568. }
  2569. }
  2570. if(best_i != -1) {
  2571. //found the smallest buffer that fits our needs
  2572. vk_buffer b = ctx->buffer_pool[best_i];
  2573. ctx->buffer_pool[best_i].reset();
  2574. return b;
  2575. }
  2576. if(worst_i != -1) {
  2577. //no buffer that fits our needs, resize largest one to save memory
  2578. vk_buffer& b = ctx->buffer_pool[worst_i];
  2579. ggml_vk_destroy_buffer(b);
  2580. }
  2581. return ggml_vk_create_buffer_device(ctx->device, size);
  2582. }
  2583. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  2584. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  2585. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2586. vk_buffer& b = ctx->buffer_pool[i];
  2587. if (b == nullptr) {
  2588. b = buffer;
  2589. return;
  2590. }
  2591. }
  2592. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  2593. ggml_vk_destroy_buffer(buffer);
  2594. }
  2595. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  2596. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  2597. // Try to find existing temp buffer with enough capacity
  2598. for (auto& buffer : ctx->gc.temp_buffers) {
  2599. if (buffer->size >= size) {
  2600. return buffer;
  2601. }
  2602. }
  2603. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  2604. // Otherwise create new buffer
  2605. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  2606. ctx->gc.temp_buffers.push_back(buf);
  2607. return buf;
  2608. }
  2609. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  2610. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  2611. vk_buffer buf = ggml_vk_create_buffer(device, size,
  2612. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2613. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2614. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  2615. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  2616. size/1024.0/1024.0);
  2617. device->device.freeMemory(buf->device_memory);
  2618. device->device.destroyBuffer(buf->buffer);
  2619. return nullptr;
  2620. }
  2621. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  2622. return buf->ptr;
  2623. }
  2624. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  2625. if (ptr == nullptr) {
  2626. return;
  2627. }
  2628. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  2629. vk_buffer buf;
  2630. size_t index;
  2631. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2632. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2633. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2634. if (ptr >= addr && ptr < endr) {
  2635. buf = std::get<2>(device->pinned_memory[i]);
  2636. index = i;
  2637. break;
  2638. }
  2639. }
  2640. if (buf == nullptr) {
  2641. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  2642. return;
  2643. }
  2644. ggml_vk_destroy_buffer(buf);
  2645. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  2646. }
  2647. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  2648. buf = nullptr;
  2649. buf_offset = 0;
  2650. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2651. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2652. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2653. if (ptr >= addr && ptr < endr) {
  2654. buf = std::get<2>(device->pinned_memory[i]);
  2655. buf_offset = ((const uint8_t *)ptr) - addr;
  2656. break;
  2657. }
  2658. }
  2659. }
  2660. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_queue& q, bool one_time = true) {
  2661. vk_submission s;
  2662. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  2663. if (one_time) {
  2664. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  2665. } else {
  2666. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  2667. }
  2668. return s;
  2669. }
  2670. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& subctx, vk_pipeline& pipeline, std::initializer_list<vk::DescriptorBufferInfo> const& descriptor_buffer_infos, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  2671. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  2672. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  2673. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  2674. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  2675. for (auto& buffer : descriptor_buffer_infos) {
  2676. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  2677. }
  2678. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  2679. GGML_ASSERT(pipeline->descriptor_set_idx < pipeline->descriptor_sets.size());
  2680. GGML_ASSERT(descriptor_buffer_infos.size() == pipeline->parameter_count);
  2681. vk::DescriptorSet& descriptor_set = pipeline->descriptor_sets[pipeline->descriptor_set_idx++];
  2682. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  2683. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  2684. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  2685. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  2686. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  2687. pipeline->layout,
  2688. 0,
  2689. { descriptor_set },
  2690. {});
  2691. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  2692. }
  2693. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  2694. s.buffer.end();
  2695. s.wait_semaphores = std::move(wait_semaphores);
  2696. s.signal_semaphores = std::move(signal_semaphores);
  2697. }
  2698. static void ggml_vk_ctx_end(vk_context& ctx) {
  2699. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  2700. if (ctx->s == nullptr) {
  2701. return;
  2702. }
  2703. ctx->s->buffer.end();
  2704. ctx->s = nullptr;
  2705. }
  2706. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  2707. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  2708. if (subctx->s != nullptr) {
  2709. ggml_vk_ctx_end(subctx);
  2710. }
  2711. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->q) });
  2712. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  2713. }
  2714. static size_t ggml_vk_align_size(size_t width, size_t align) {
  2715. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  2716. return CEIL_DIV(width, align) * align;
  2717. }
  2718. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  2719. if (memcpys == nullptr) {
  2720. memcpy(dst, src, size);
  2721. } else {
  2722. memcpys->emplace_back(dst, src, size);
  2723. }
  2724. }
  2725. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  2726. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  2727. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  2728. ggml_vk_destroy_buffer(device->sync_staging);
  2729. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  2730. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2731. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2732. }
  2733. }
  2734. static void ggml_vk_buffer_write_nc_async(ggml_backend_vk_context * ctx, vk_context& subctx, vk_buffer& dst, size_t offset, const ggml_tensor * tensor, bool sync_staging = false) {
  2735. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  2736. GGML_ASSERT(!ggml_is_contiguous(tensor));
  2737. // Buffer is already mapped
  2738. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2739. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2740. GGML_ABORT("fatal error");
  2741. }
  2742. // Check if src is pinned memory
  2743. vk_buffer buf = nullptr;
  2744. size_t buf_offset = 0;
  2745. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  2746. const uint64_t ne0 = tensor->ne[0];
  2747. const uint64_t ne1 = tensor->ne[1];
  2748. const uint64_t ne2 = tensor->ne[2];
  2749. const uint64_t ne3 = tensor->ne[3];
  2750. const uint64_t nb0 = tensor->nb[0];
  2751. const uint64_t nb1 = tensor->nb[1];
  2752. const uint64_t nb2 = tensor->nb[2];
  2753. const uint64_t nb3 = tensor->nb[3];
  2754. const ggml_type type = tensor->type;
  2755. const uint64_t ts = ggml_type_size(type);
  2756. const uint64_t bs = ggml_blck_size(type);
  2757. const uint64_t dstnb0 = ts;
  2758. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  2759. const uint64_t dstnb2 = dstnb1*ne1;
  2760. const uint64_t dstnb3 = dstnb2*ne2;
  2761. const uint64_t ne = ggml_nelements(tensor);
  2762. if (buf != nullptr) {
  2763. // Memory is pinned, use as staging buffer
  2764. std::vector<vk::BufferCopy> slices;
  2765. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2766. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2767. // Find longest contiguous slice
  2768. if (ne1*nb1 == dstnb2) {
  2769. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  2770. } else {
  2771. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2772. if (ne0*nb0/bs == dstnb1) {
  2773. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  2774. } else {
  2775. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2776. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2777. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2778. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  2779. }
  2780. }
  2781. }
  2782. }
  2783. }
  2784. }
  2785. ggml_vk_sync_buffers(subctx);
  2786. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2787. return;
  2788. }
  2789. if (!sync_staging) {
  2790. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2791. }
  2792. // Staging buffer required
  2793. vk_buffer& staging = ctx->device->sync_staging;
  2794. const uint64_t copy_size = ts*ne/bs;
  2795. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  2796. VkBufferCopy buf_copy{ 0, offset, copy_size };
  2797. ggml_vk_sync_buffers(subctx);
  2798. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  2799. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2800. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2801. // Find longest contiguous slice
  2802. if (ne1*nb1 == dstnb2) {
  2803. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2, dstnb2, &subctx->in_memcpys);
  2804. } else {
  2805. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2806. if (ne0*nb0/bs == dstnb1) {
  2807. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2 + i1*nb1, dstnb1, &subctx->in_memcpys);
  2808. } else {
  2809. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2810. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2811. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2812. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  2813. }
  2814. }
  2815. }
  2816. }
  2817. }
  2818. }
  2819. }
  2820. static void ggml_vk_buffer_write_2d_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height, bool sync_staging = false) {
  2821. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  2822. // Buffer is already mapped
  2823. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2824. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2825. GGML_ABORT("fatal error");
  2826. }
  2827. // Check if src is pinned memory
  2828. vk_buffer buf = nullptr;
  2829. size_t buf_offset = 0;
  2830. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  2831. if (buf != nullptr) {
  2832. // Memory is pinned, use as staging buffer
  2833. std::vector<vk::BufferCopy> slices(1);
  2834. if (width == spitch) {
  2835. // Only do single write if stride is equal
  2836. slices[0].srcOffset = buf_offset;
  2837. slices[0].dstOffset = offset;
  2838. slices[0].size = width * height;
  2839. } else {
  2840. slices.resize(height);
  2841. for (size_t i = 0; i < height; i++) {
  2842. slices[i].srcOffset = buf_offset + i * spitch;
  2843. slices[i].dstOffset = offset + i * width;
  2844. slices[i].size = width;
  2845. }
  2846. }
  2847. ggml_vk_sync_buffers(subctx);
  2848. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2849. return;
  2850. }
  2851. VK_LOG_DEBUG("STAGING");
  2852. if (!sync_staging) {
  2853. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2854. }
  2855. // Staging buffer required
  2856. const size_t copy_size = width*height;
  2857. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  2858. vk_buffer& staging_buffer = dst->device->sync_staging;
  2859. VkBufferCopy buf_copy = {
  2860. 0,
  2861. offset,
  2862. copy_size};
  2863. ggml_vk_sync_buffers(subctx);
  2864. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  2865. if (width == spitch) {
  2866. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  2867. } else {
  2868. for (size_t i = 0; i < height; i++) {
  2869. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  2870. }
  2871. }
  2872. }
  2873. static void ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  2874. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  2875. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  2876. }
  2877. static void ggml_vk_buffer_write_2d(vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height) {
  2878. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  2879. // Buffer is already mapped
  2880. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2881. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2882. for (size_t i = 0; i < height; i++) {
  2883. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  2884. }
  2885. } else {
  2886. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2887. ggml_vk_ctx_begin(dst->device, subctx);
  2888. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  2889. ggml_vk_ctx_end(subctx);
  2890. for (auto& cpy : subctx->in_memcpys) {
  2891. memcpy(cpy.dst, cpy.src, cpy.n);
  2892. }
  2893. ggml_vk_submit(subctx, dst->device->fence);
  2894. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  2895. dst->device->device.resetFences({ dst->device->fence });
  2896. }
  2897. }
  2898. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  2899. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  2900. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  2901. }
  2902. static void ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  2903. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  2904. GGML_ASSERT(width > 0);
  2905. GGML_ASSERT(height > 0);
  2906. GGML_ASSERT(src != nullptr);
  2907. // TODO: staging_offset is not used
  2908. // Check if dst is pinned memory
  2909. vk_buffer buf = nullptr;
  2910. size_t buf_offset = 0;
  2911. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  2912. std::vector<vk::BufferCopy> slices(1);
  2913. if (width == spitch && width == dpitch) {
  2914. // Only do single write if stride is equal
  2915. slices[0].srcOffset = offset;
  2916. slices[0].dstOffset = buf_offset;
  2917. slices[0].size = width * height;
  2918. } else {
  2919. slices.resize(height);
  2920. for (size_t i = 0; i < height; i++) {
  2921. slices[i].srcOffset = offset + i * spitch;
  2922. slices[i].dstOffset = buf_offset + i * dpitch;
  2923. slices[i].size = width;
  2924. }
  2925. }
  2926. if (buf != nullptr) {
  2927. // Memory is pinned, use as staging buffer
  2928. ggml_vk_sync_buffers(subctx);
  2929. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  2930. return;
  2931. }
  2932. VK_LOG_DEBUG("STAGING");
  2933. if (!sync_staging) {
  2934. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  2935. }
  2936. // Fall back to staging buffer
  2937. const size_t copy_size = dpitch * height;
  2938. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  2939. vk_buffer& staging_buffer = src->device->sync_staging;
  2940. ggml_vk_sync_buffers(subctx);
  2941. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  2942. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  2943. }
  2944. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  2945. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  2946. }
  2947. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  2948. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  2949. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  2950. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  2951. // the HW device to host copy path.
  2952. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  2953. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2954. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  2955. } else {
  2956. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2957. ggml_vk_ctx_begin(src->device, subctx);
  2958. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  2959. ggml_vk_ctx_end(subctx);
  2960. ggml_vk_submit(subctx, src->device->fence);
  2961. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  2962. src->device->device.resetFences({ src->device->fence });
  2963. for (auto& cpy : subctx->out_memcpys) {
  2964. memcpy(cpy.dst, cpy.src, cpy.n);
  2965. }
  2966. }
  2967. }
  2968. static void ggml_vk_buffer_copy_async(vk_context& ctx, vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  2969. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  2970. // Make sure both buffers are on same device
  2971. GGML_ASSERT(src->device == dst->device);
  2972. VkBufferCopy bc{ src_offset, dst_offset, size };
  2973. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  2974. }
  2975. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  2976. if (src->device == dst->device) {
  2977. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  2978. // Copy within the device
  2979. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2980. ggml_vk_ctx_begin(src->device, subctx);
  2981. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  2982. ggml_vk_ctx_end(subctx);
  2983. ggml_vk_submit(subctx, src->device->fence);
  2984. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  2985. src->device->device.resetFences({ src->device->fence });
  2986. } else {
  2987. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  2988. // Copy device to device
  2989. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  2990. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  2991. // Copy to src staging buffer
  2992. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  2993. // memcpy to dst staging buffer
  2994. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  2995. // Copy to dst buffer
  2996. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  2997. }
  2998. }
  2999. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  3000. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  3001. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  3002. ggml_vk_ctx_begin(dst->device, subctx);
  3003. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  3004. ggml_vk_ctx_end(subctx);
  3005. ggml_vk_submit(subctx, dst->device->fence);
  3006. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  3007. dst->device->device.resetFences({ dst->device->fence });
  3008. }
  3009. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, int m, int n, int k, const vk_pipeline& pipeline) {
  3010. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  3011. uint32_t split_k = 1;
  3012. if (ctx->device->shader_core_count != 0 && m >= (int)pipeline->wg_denoms[0] && n >= (int)pipeline->wg_denoms[1]) {
  3013. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  3014. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  3015. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  3016. if (k >= 2048 && m_tiles * n_tiles < ctx->device->shader_core_count / 2) {
  3017. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  3018. // Clamp to 2 or 4
  3019. split_k = std::min(split_k, 4u);
  3020. if (split_k == 3) {
  3021. split_k = 2;
  3022. }
  3023. }
  3024. }
  3025. return split_k;
  3026. }
  3027. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  3028. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  3029. if (ctx->device->coopmat2) {
  3030. if ((ctx->device->mul_mat_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_s)) {
  3031. return aligned ? mmp->a_l : mmp->l;
  3032. }
  3033. if ((ctx->device->mul_mat_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_s) {
  3034. return aligned ? mmp->a_m : mmp->m;
  3035. }
  3036. return aligned ? mmp->a_s : mmp->s;
  3037. }
  3038. if ((ctx->device->mul_mat_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_l)) {
  3039. return aligned ? mmp->a_s : mmp->s;
  3040. }
  3041. if ((ctx->device->mul_mat_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l) {
  3042. return aligned ? mmp->a_m : mmp->m;
  3043. }
  3044. return aligned ? mmp->a_l : mmp->l;
  3045. }
  3046. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  3047. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  3048. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true)->align;
  3049. }
  3050. static void ggml_vk_matmul(
  3051. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  3052. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  3053. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  3054. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  3055. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3) {
  3056. VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ")");
  3057. ggml_vk_sync_buffers(subctx);
  3058. if (split_k == 1) {
  3059. const vk_mat_mat_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k, ne02, ne12, broadcast2, broadcast3 };
  3060. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, sizeof(vk_mat_mat_push_constants), &pc, { m, n, batch });
  3061. return;
  3062. }
  3063. GGML_ASSERT(batch_stride_d == m * n);
  3064. const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3 };
  3065. // Make sure enough workgroups get assigned for split k to work
  3066. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, sizeof(vk_mat_mat_push_constants), &pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  3067. ggml_vk_sync_buffers(subctx);
  3068. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  3069. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2.size() * sizeof(uint32_t), pc2.data(), { m * n * batch, 1, 1 });
  3070. }
  3071. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  3072. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  3073. if (ctx->device->coopmat2) {
  3074. if ((ctx->device->mul_mat_id_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_s)) {
  3075. return aligned ? mmp->a_l : mmp->l;
  3076. }
  3077. if ((ctx->device->mul_mat_id_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_id_s) {
  3078. return aligned ? mmp->a_m : mmp->m;
  3079. }
  3080. return aligned ? mmp->a_s : mmp->s;
  3081. }
  3082. if ((ctx->device->mul_mat_id_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_l)) {
  3083. return aligned ? mmp->a_s : mmp->s;
  3084. }
  3085. if ((ctx->device->mul_mat_id_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l) {
  3086. return aligned ? mmp->a_m : mmp->m;
  3087. }
  3088. return aligned ? mmp->a_l : mmp->l;
  3089. }
  3090. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  3091. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  3092. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true)->align;
  3093. }
  3094. static void ggml_vk_matmul_id(
  3095. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  3096. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  3097. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  3098. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  3099. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11) {
  3100. VK_LOG_DEBUG("ggml_vk_matmul_id(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), ids: (" << ids.buffer->buffer << ", " << ids.offset << ", " << ids.size << "), " <<
  3101. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  3102. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  3103. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  3104. ggml_vk_sync_buffers(subctx);
  3105. const vk_mat_mat_id_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d,
  3106. nei0, nei1, nbi1, ne11 };
  3107. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, sizeof(vk_mat_mat_id_push_constants), &pc, { m, nei1, n_as });
  3108. }
  3109. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  3110. return
  3111. tensor->nb[0] == ggml_type_size(tensor->type) &&
  3112. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  3113. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  3114. }
  3115. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  3116. // Choose "contiguous copy" shader if src/dst are contiguous
  3117. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  3118. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  3119. if (contig) {
  3120. return ctx->device->pipeline_contig_cpy_f32_f32;
  3121. } else {
  3122. return ctx->device->pipeline_cpy_f32_f32;
  3123. }
  3124. }
  3125. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  3126. if (contig) {
  3127. return ctx->device->pipeline_contig_cpy_f32_f16;
  3128. } else {
  3129. return ctx->device->pipeline_cpy_f32_f16;
  3130. }
  3131. }
  3132. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  3133. if (contig) {
  3134. return ctx->device->pipeline_contig_cpy_f16_f16;
  3135. } else {
  3136. return ctx->device->pipeline_cpy_f16_f16;
  3137. }
  3138. }
  3139. if (src->type == GGML_TYPE_F32) {
  3140. switch (to) {
  3141. case GGML_TYPE_Q4_0:
  3142. case GGML_TYPE_Q4_1:
  3143. case GGML_TYPE_Q5_0:
  3144. case GGML_TYPE_Q5_1:
  3145. case GGML_TYPE_Q8_0:
  3146. case GGML_TYPE_IQ4_NL:
  3147. return ctx->device->pipeline_cpy_f32_quant[to];
  3148. default:
  3149. break;
  3150. }
  3151. }
  3152. if (to == GGML_TYPE_F32) {
  3153. switch (src->type) {
  3154. case GGML_TYPE_Q4_0:
  3155. case GGML_TYPE_Q4_1:
  3156. case GGML_TYPE_Q5_0:
  3157. case GGML_TYPE_Q5_1:
  3158. case GGML_TYPE_Q8_0:
  3159. case GGML_TYPE_IQ4_NL:
  3160. return ctx->device->pipeline_cpy_quant_f32[src->type];
  3161. default:
  3162. break;
  3163. }
  3164. }
  3165. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  3166. GGML_ABORT("fatal error");
  3167. }
  3168. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, vk_subbuffer&& in, vk_subbuffer&& out) {
  3169. VK_LOG_DEBUG("ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << "), ";
  3170. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  3171. const int tensor_type_size = ggml_type_size(tensor->type);
  3172. const uint32_t ne = ggml_nelements(tensor);
  3173. std::array<uint32_t, 3> elements;
  3174. if (ne > 262144) {
  3175. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  3176. } else if (ne > 512) {
  3177. elements = { 512, CEIL_DIV(ne, 512), 1 };
  3178. } else {
  3179. elements = { ne, 1, 1 };
  3180. }
  3181. vk_op_unary_push_constants pc = {
  3182. (uint32_t)ne,
  3183. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], (uint32_t)tensor->ne[2], (uint32_t)tensor->ne[3], (uint32_t)tensor->nb[0] / tensor_type_size, (uint32_t)tensor->nb[1] / tensor_type_size, (uint32_t)tensor->nb[2] / tensor_type_size, (uint32_t)tensor->nb[3] / tensor_type_size,
  3184. (uint32_t)tensor->ne[0], (uint32_t)tensor->ne[1], (uint32_t)tensor->ne[2], (uint32_t)tensor->ne[3], 1 , (uint32_t)tensor->ne[0] , (uint32_t)(tensor->ne[0] * tensor->ne[1]) , (uint32_t)(tensor->ne[0] * tensor->ne[1] * tensor->ne[2]),
  3185. 0,
  3186. 0.0f, 0.0f,
  3187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3188. };
  3189. init_pushconst_fastdiv(pc);
  3190. ggml_vk_sync_buffers(subctx);
  3191. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, sizeof(vk_op_unary_push_constants), &pc, elements);
  3192. }
  3193. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3194. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3195. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3196. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3197. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3198. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3199. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3200. const uint64_t ne00 = src0->ne[0];
  3201. const uint64_t ne01 = src0->ne[1];
  3202. const uint64_t ne02 = src0->ne[2];
  3203. const uint64_t ne03 = src0->ne[3];
  3204. const uint64_t ne10 = src1->ne[0];
  3205. const uint64_t ne11 = src1->ne[1];
  3206. const uint64_t ne12 = src1->ne[2];
  3207. const uint64_t ne13 = src1->ne[3];
  3208. const uint64_t ne20 = dst->ne[0];
  3209. const uint64_t ne21 = dst->ne[1];
  3210. const uint64_t r2 = ne12 / ne02;
  3211. const uint64_t r3 = ne13 / ne03;
  3212. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3213. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3214. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3215. vk_buffer d_Qx = nullptr;
  3216. size_t qx_buf_offset = 0;
  3217. vk_buffer d_Qy = nullptr;
  3218. size_t qy_buf_offset = 0;
  3219. bool src0_uma = false;
  3220. bool src1_uma = false;
  3221. if (ctx->device->uma) {
  3222. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3223. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3224. src0_uma = d_Qx != nullptr;
  3225. src1_uma = d_Qy != nullptr;
  3226. }
  3227. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  3228. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  3229. !ggml_vk_dim01_contiguous(src0);
  3230. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3231. !ggml_vk_dim01_contiguous(src1);
  3232. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3233. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3234. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3235. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3236. if (qx_needs_dequant) {
  3237. // Fall back to dequant + f16 mulmat
  3238. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3239. }
  3240. // Not implemented
  3241. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3242. const int x_ne = ne01 * ne00;
  3243. const int y_ne = ne11 * ne10;
  3244. const int d_ne = ne11 * ne01;
  3245. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11));
  3246. const bool aligned = ne10 == kpad && ne01 > 8 && ne11 > 8;
  3247. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned);
  3248. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  3249. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3250. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3251. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3252. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3253. const uint64_t d_sz = sizeof(float) * d_ne;
  3254. vk_pipeline to_fp16_vk_0 = nullptr;
  3255. vk_pipeline to_fp16_vk_1 = nullptr;
  3256. if (x_non_contig) {
  3257. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3258. } else {
  3259. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3260. }
  3261. if (y_non_contig) {
  3262. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3263. } else {
  3264. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3265. }
  3266. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3267. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3268. if (dryrun) {
  3269. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3270. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3271. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  3272. if (
  3273. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3274. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  3275. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  3276. GGML_ABORT("Requested preallocation size is too large");
  3277. }
  3278. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3279. ctx->prealloc_size_x = x_sz_upd;
  3280. }
  3281. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3282. ctx->prealloc_size_y = y_sz_upd;
  3283. }
  3284. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  3285. ctx->prealloc_size_split_k = split_k_size;
  3286. }
  3287. // Request descriptor sets
  3288. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3289. if (qx_needs_dequant) {
  3290. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3291. }
  3292. if (qy_needs_dequant) {
  3293. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3294. }
  3295. if (split_k > 1) {
  3296. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, 1);
  3297. }
  3298. return;
  3299. }
  3300. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3301. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3302. GGML_ASSERT(d_D != nullptr);
  3303. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  3304. vk_buffer d_X;
  3305. uint64_t x_buf_offset = 0;
  3306. vk_buffer d_Y;
  3307. uint64_t y_buf_offset = 0;
  3308. if (!src0_uma) {
  3309. d_Qx = src0_buf_ctx->dev_buffer;
  3310. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3311. GGML_ASSERT(d_Qx != nullptr);
  3312. }
  3313. if (!src1_uma) {
  3314. d_Qy = src1_buf_ctx->dev_buffer;
  3315. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3316. GGML_ASSERT(d_Qy != nullptr);
  3317. }
  3318. if (qx_needs_dequant) {
  3319. d_X = ctx->prealloc_x;
  3320. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3321. } else {
  3322. d_X = d_Qx;
  3323. x_buf_offset = qx_buf_offset;
  3324. GGML_ASSERT(qx_sz == x_sz);
  3325. }
  3326. if (qy_needs_dequant) {
  3327. d_Y = ctx->prealloc_y;
  3328. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3329. } else {
  3330. d_Y = d_Qy;
  3331. y_buf_offset = qy_buf_offset;
  3332. GGML_ASSERT(qy_sz == y_sz);
  3333. }
  3334. if (x_non_contig) {
  3335. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3336. } else if (qx_needs_dequant) {
  3337. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3338. ggml_vk_sync_buffers(subctx);
  3339. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3340. }
  3341. if (y_non_contig) {
  3342. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3343. }
  3344. uint32_t stride_batch_x = ne00*ne01;
  3345. uint32_t stride_batch_y = ne10*ne11;
  3346. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3347. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3348. }
  3349. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3350. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3351. }
  3352. // compute
  3353. ggml_vk_matmul(
  3354. ctx, subctx, pipeline,
  3355. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3356. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  3357. ne01, ne11, ne10,
  3358. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  3359. split_k, ne12*ne13, ne02, ne12, r2, r3
  3360. ); // NOLINT
  3361. }
  3362. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3363. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3364. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3365. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3366. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  3367. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3368. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3369. const uint64_t ne00 = src0->ne[0];
  3370. const uint64_t ne01 = src0->ne[1];
  3371. const uint64_t ne02 = src0->ne[2];
  3372. const uint64_t ne03 = src0->ne[3];
  3373. const uint64_t ne10 = src1->ne[0];
  3374. const uint64_t ne11 = src1->ne[1];
  3375. const uint64_t ne12 = src1->ne[2];
  3376. const uint64_t ne13 = src1->ne[3];
  3377. const uint64_t ne20 = dst->ne[0];
  3378. const uint64_t ne21 = dst->ne[1];
  3379. const uint64_t ne22 = dst->ne[2];
  3380. const uint64_t ne23 = dst->ne[3];
  3381. const uint64_t r2 = ne12 / ne02;
  3382. const uint64_t r3 = ne13 / ne03;
  3383. // batch_n indicates that we need to compute a few vector results, and this assumes
  3384. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  3385. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  3386. bool batch_n = ne11 > 1;
  3387. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3388. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3389. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3390. vk_buffer d_Qx = nullptr;
  3391. size_t qx_buf_offset = 0;
  3392. vk_buffer d_Qy = nullptr;
  3393. size_t qy_buf_offset = 0;
  3394. bool src0_uma = false;
  3395. bool src1_uma = false;
  3396. if (ctx->device->uma) {
  3397. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3398. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3399. src0_uma = d_Qx != nullptr;
  3400. src1_uma = d_Qy != nullptr;
  3401. }
  3402. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3403. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3404. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3405. const bool qx_needs_dequant = x_non_contig;
  3406. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3407. // Not implemented
  3408. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3409. const uint64_t x_ne = ne01 * ne00;
  3410. const uint64_t y_ne = ne11 * ne10;
  3411. const uint64_t d_ne = ne11 * ne01;
  3412. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  3413. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3414. const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz;
  3415. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3416. const uint64_t d_sz = sizeof(float) * d_ne;
  3417. vk_pipeline to_fp16_vk_0 = nullptr;
  3418. vk_pipeline to_fp16_vk_1 = nullptr;
  3419. if (x_non_contig) {
  3420. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3421. }
  3422. if (y_non_contig) {
  3423. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3424. } else {
  3425. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3426. }
  3427. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11);
  3428. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3429. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3430. GGML_ASSERT(dmmv != nullptr);
  3431. if (dryrun) {
  3432. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3433. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3434. if (
  3435. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3436. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3437. GGML_ABORT("Requested preallocation size is too large");
  3438. }
  3439. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3440. ctx->prealloc_size_x = x_sz_upd;
  3441. }
  3442. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3443. ctx->prealloc_size_y = y_sz_upd;
  3444. }
  3445. // Request descriptor sets
  3446. if (qx_needs_dequant) {
  3447. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3448. }
  3449. if (qy_needs_dequant) {
  3450. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3451. }
  3452. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3453. return;
  3454. }
  3455. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3456. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3457. GGML_ASSERT(d_D != nullptr);
  3458. vk_buffer d_X;
  3459. uint64_t x_buf_offset = 0;
  3460. vk_buffer d_Y;
  3461. uint64_t y_buf_offset = 0;
  3462. if(!src0_uma) {
  3463. d_Qx = src0_buf_ctx->dev_buffer;
  3464. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3465. GGML_ASSERT(d_Qx != nullptr);
  3466. }
  3467. if(!src1_uma) {
  3468. d_Qy = src1_buf_ctx->dev_buffer;
  3469. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3470. GGML_ASSERT(d_Qy != nullptr);
  3471. }
  3472. if (qx_needs_dequant) {
  3473. d_X = ctx->prealloc_x;
  3474. } else {
  3475. d_X = d_Qx;
  3476. x_buf_offset = qx_buf_offset;
  3477. GGML_ASSERT(qx_sz == x_sz);
  3478. }
  3479. if (qy_needs_dequant) {
  3480. d_Y = ctx->prealloc_y;
  3481. } else {
  3482. d_Y = d_Qy;
  3483. y_buf_offset = qy_buf_offset;
  3484. GGML_ASSERT(qy_sz == y_sz);
  3485. }
  3486. if (x_non_contig) {
  3487. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3488. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3489. }
  3490. if (y_non_contig) {
  3491. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3492. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3493. }
  3494. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  3495. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  3496. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  3497. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  3498. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3499. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3500. }
  3501. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3502. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3503. }
  3504. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3505. uint32_t groups_x = ne01;
  3506. uint32_t groups_z = 1;
  3507. if (ne01 > max_groups_x) {
  3508. groups_z = 64;
  3509. groups_x = CEIL_DIV(groups_x, groups_z);
  3510. }
  3511. // compute
  3512. const vk_mat_vec_push_constants pc = {
  3513. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3514. stride_batch_x, stride_batch_y, stride_batch_d,
  3515. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  3516. };
  3517. ggml_vk_sync_buffers(subctx);
  3518. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3519. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  3520. sizeof(vk_mat_vec_push_constants), &pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  3521. }
  3522. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3523. VK_LOG_DEBUG("ggml_vk_mul_mat_p021_f16_f32(" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3524. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3525. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3526. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3527. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  3528. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  3529. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  3530. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3531. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3532. const uint64_t ne00 = src0->ne[0];
  3533. const uint64_t ne01 = src0->ne[1];
  3534. const uint64_t ne02 = src0->ne[2];
  3535. // const uint64_t ne03 = src0->ne[3];
  3536. const uint64_t ne10 = src1->ne[0];
  3537. const uint64_t ne11 = src1->ne[1];
  3538. const uint64_t ne12 = src1->ne[2];
  3539. // const uint64_t ne13 = src1->ne[3];
  3540. GGML_ASSERT(ne11 == 1);
  3541. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3542. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3543. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3544. vk_buffer d_Qy = nullptr;
  3545. size_t qy_buf_offset = 0;
  3546. bool src1_uma = false;
  3547. if (ctx->device->uma) {
  3548. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3549. src1_uma = d_Qy != nullptr;
  3550. }
  3551. const uint64_t x_ne = ne00 * ne01 * ne02;
  3552. const uint64_t y_ne = ne10 * ne11 * ne12;
  3553. const uint64_t d_ne = ne01 * ne11 * ne12;
  3554. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  3555. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3556. const uint64_t d_sz = sizeof(float) * d_ne;
  3557. if (dryrun) {
  3558. // Request descriptor sets
  3559. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, 1);
  3560. return;
  3561. }
  3562. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3563. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3564. GGML_ASSERT(d_D != nullptr);
  3565. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3566. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3567. GGML_ASSERT(d_Qx != nullptr);
  3568. if (!src1_uma) {
  3569. d_Qy = src1_buf_ctx->dev_buffer;
  3570. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3571. GGML_ASSERT(d_Qx != nullptr);
  3572. }
  3573. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3574. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3575. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3576. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3577. // compute
  3578. const std::array<uint32_t, 6> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  3579. ggml_vk_sync_buffers(subctx);
  3580. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3581. }
  3582. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3583. VK_LOG_DEBUG("ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3584. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3585. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3586. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3587. GGML_ASSERT(!ggml_is_transposed(src0));
  3588. GGML_ASSERT(!ggml_is_transposed(src1));
  3589. GGML_ASSERT(!ggml_is_permuted(src0));
  3590. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3591. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3592. const uint64_t ne00 = src0->ne[0];
  3593. const uint64_t ne01 = src0->ne[1];
  3594. const uint64_t ne02 = src0->ne[2];
  3595. // const uint64_t ne03 = src0->ne[3];
  3596. const uint64_t nb01 = src0->nb[1];
  3597. const uint64_t nb02 = src0->nb[2];
  3598. // const uint64_t ne10 = src1->ne[0];
  3599. const uint64_t ne11 = src1->ne[1];
  3600. const uint64_t ne12 = src1->ne[2];
  3601. // const uint64_t ne13 = src1->ne[3];
  3602. GGML_ASSERT(ne11 == 1);
  3603. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3604. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3605. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3606. vk_buffer d_Qy = nullptr;
  3607. size_t qy_buf_offset = 0;
  3608. bool src1_uma = false;
  3609. if (ctx->device->uma) {
  3610. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3611. src1_uma = d_Qy != nullptr;
  3612. }
  3613. const uint64_t d_ne = ne01 * ne11 * ne12;
  3614. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  3615. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  3616. const uint64_t qx_sz = ggml_nbytes(src0);
  3617. const uint64_t qy_sz = ggml_nbytes(src1);
  3618. const uint64_t d_sz = sizeof(float) * d_ne;
  3619. if (dryrun) {
  3620. // Request descriptor sets
  3621. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  3622. return;
  3623. }
  3624. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3625. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3626. GGML_ASSERT(d_D != nullptr);
  3627. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3628. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3629. GGML_ASSERT(d_Qx != nullptr);
  3630. if (!src1_uma) {
  3631. d_Qy = src1_buf_ctx->dev_buffer;
  3632. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3633. GGML_ASSERT(d_Qx != nullptr);
  3634. }
  3635. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3636. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3637. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3638. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3639. // compute
  3640. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, (uint32_t)(ne12 / ne02), (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  3641. ggml_vk_sync_buffers(subctx);
  3642. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  3643. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3644. }
  3645. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3646. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  3647. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  3648. // detect 0213 permutation, and batch size of 1
  3649. src0->nb[0] <= src0->nb[2] &&
  3650. src0->nb[2] <= src0->nb[1] &&
  3651. src0->nb[1] <= src0->nb[3] &&
  3652. src1->nb[0] <= src1->nb[2] &&
  3653. src1->nb[2] <= src1->nb[1] &&
  3654. src1->nb[1] <= src1->nb[3] &&
  3655. src0->ne[3] == 1 &&
  3656. src1->ne[3] == 1) {
  3657. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3658. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  3659. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  3660. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3661. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  3662. // when ne12 and ne13 are one.
  3663. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  3664. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3665. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3666. } else {
  3667. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3668. }
  3669. }
  3670. static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, bool dryrun = false) {
  3671. VK_LOG_DEBUG("ggml_vk_mul_mat_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3672. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3673. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  3674. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3] << "),)");
  3675. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3676. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3677. const uint64_t ne00 = src0->ne[0];
  3678. const uint64_t ne01 = src0->ne[1];
  3679. const uint64_t ne02 = src0->ne[2];
  3680. const uint64_t ne03 = src0->ne[3];
  3681. const uint64_t ne10 = src1->ne[0];
  3682. const uint64_t ne11 = src1->ne[1];
  3683. const uint64_t ne12 = src1->ne[2];
  3684. const uint64_t ne13 = src1->ne[3];
  3685. const uint64_t nei0 = ids->ne[0];
  3686. const uint64_t nei1 = ids->ne[1];
  3687. GGML_ASSERT(nei0 * nei1 <= 3072);
  3688. const uint32_t nbi1 = ids->nb[1];
  3689. const uint32_t nbi2 = ids->nb[2];
  3690. const uint64_t ne20 = dst->ne[0];
  3691. const uint64_t ne21 = dst->ne[1];
  3692. const uint64_t ne22 = dst->ne[2];
  3693. const uint64_t ne23 = dst->ne[3];
  3694. const uint64_t n_as = ne02;
  3695. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3696. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3697. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3698. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3699. vk_buffer d_Qx = nullptr;
  3700. size_t qx_buf_offset = 0;
  3701. vk_buffer d_Qy = nullptr;
  3702. size_t qy_buf_offset = 0;
  3703. vk_buffer d_ids = nullptr;
  3704. size_t ids_buf_offset = 0;
  3705. bool src0_uma = false;
  3706. bool src1_uma = false;
  3707. bool ids_uma = false;
  3708. if (ctx->device->uma) {
  3709. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3710. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3711. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3712. src0_uma = d_Qx != nullptr;
  3713. src1_uma = d_Qy != nullptr;
  3714. ids_uma = d_ids != nullptr;
  3715. }
  3716. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  3717. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  3718. !ggml_vk_dim01_contiguous(src0);
  3719. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3720. !ggml_vk_dim01_contiguous(src1);
  3721. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3722. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3723. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3724. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3725. if (qx_needs_dequant) {
  3726. // Fall back to dequant + f16 mulmat
  3727. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3728. }
  3729. // Not implemented
  3730. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3731. const uint64_t x_ne = ne01 * ne00;
  3732. const uint64_t y_ne = ne11 * ne10;
  3733. const uint64_t d_ne = ne21 * ne20;
  3734. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1));
  3735. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  3736. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned);
  3737. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3738. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3739. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3740. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3741. const uint64_t ids_sz = nbi2;
  3742. const uint64_t d_sz = sizeof(float) * d_ne;
  3743. vk_pipeline to_fp16_vk_0 = nullptr;
  3744. vk_pipeline to_fp16_vk_1 = nullptr;
  3745. if (x_non_contig) {
  3746. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3747. } else {
  3748. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3749. }
  3750. if (y_non_contig) {
  3751. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3752. } else {
  3753. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3754. }
  3755. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3756. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3757. if (dryrun) {
  3758. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3759. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3760. if (
  3761. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3762. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3763. GGML_ABORT("Requested preallocation size is too large");
  3764. }
  3765. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3766. ctx->prealloc_size_x = x_sz_upd;
  3767. }
  3768. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3769. ctx->prealloc_size_y = y_sz_upd;
  3770. }
  3771. // Request descriptor sets
  3772. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3773. if (qx_needs_dequant) {
  3774. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3775. }
  3776. if (qy_needs_dequant) {
  3777. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3778. }
  3779. return;
  3780. }
  3781. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3782. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3783. GGML_ASSERT(d_D != nullptr);
  3784. vk_buffer d_X;
  3785. uint64_t x_buf_offset = 0;
  3786. vk_buffer d_Y;
  3787. uint64_t y_buf_offset = 0;
  3788. if (!src0_uma) {
  3789. d_Qx = src0_buf_ctx->dev_buffer;
  3790. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3791. GGML_ASSERT(d_Qx != nullptr);
  3792. }
  3793. if (!src1_uma) {
  3794. d_Qy = src1_buf_ctx->dev_buffer;
  3795. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3796. GGML_ASSERT(d_Qy != nullptr);
  3797. }
  3798. if (!ids_uma) {
  3799. d_ids = ids_buf_ctx->dev_buffer;
  3800. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3801. GGML_ASSERT(d_ids != nullptr);
  3802. }
  3803. if (qx_needs_dequant) {
  3804. d_X = ctx->prealloc_x;
  3805. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3806. } else {
  3807. d_X = d_Qx;
  3808. x_buf_offset = qx_buf_offset;
  3809. GGML_ASSERT(qx_sz == x_sz);
  3810. }
  3811. if (qy_needs_dequant) {
  3812. d_Y = ctx->prealloc_y;
  3813. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3814. } else {
  3815. d_Y = d_Qy;
  3816. y_buf_offset = qy_buf_offset;
  3817. GGML_ASSERT(qy_sz == y_sz);
  3818. }
  3819. if (x_non_contig) {
  3820. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3821. } else if (qx_needs_dequant) {
  3822. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3823. ggml_vk_sync_buffers(subctx);
  3824. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  3825. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3826. }
  3827. if (y_non_contig) {
  3828. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3829. }
  3830. uint32_t stride_batch_x = ne00*ne01;
  3831. uint32_t stride_batch_y = ne10*ne11;
  3832. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3833. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3834. }
  3835. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3836. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3837. }
  3838. // compute
  3839. ggml_vk_matmul_id(
  3840. ctx, subctx, pipeline,
  3841. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3842. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  3843. ne01, ne21, ne10, ne10, ne10, ne01,
  3844. stride_batch_x, stride_batch_y, ne20*ne21,
  3845. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11
  3846. ); // NOLINT
  3847. }
  3848. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, bool dryrun = false) {
  3849. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3850. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3851. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  3852. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3853. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3854. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3855. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3856. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3857. const uint64_t ne00 = src0->ne[0];
  3858. const uint64_t ne01 = src0->ne[1];
  3859. const uint64_t ne02 = src0->ne[2];
  3860. const uint64_t ne03 = src0->ne[3];
  3861. const uint64_t ne10 = src1->ne[0];
  3862. const uint64_t ne11 = src1->ne[1];
  3863. const uint64_t ne12 = src1->ne[2];
  3864. const uint64_t ne13 = src1->ne[3];
  3865. const uint64_t nei0 = ids->ne[0];
  3866. const uint64_t nei1 = ids->ne[1];
  3867. const uint64_t nbi2 = ids->nb[2];
  3868. GGML_ASSERT(nei1 == 1);
  3869. const uint64_t ne20 = dst->ne[0];
  3870. const uint64_t ne21 = dst->ne[1];
  3871. const uint64_t ne22 = dst->ne[2];
  3872. const uint64_t ne23 = dst->ne[3];
  3873. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3874. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3875. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3876. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3877. vk_buffer d_Qx = nullptr;
  3878. size_t qx_buf_offset = 0;
  3879. vk_buffer d_Qy = nullptr;
  3880. size_t qy_buf_offset = 0;
  3881. vk_buffer d_ids = nullptr;
  3882. size_t ids_buf_offset = 0;
  3883. bool src0_uma = false;
  3884. bool src1_uma = false;
  3885. bool ids_uma = false;
  3886. if (ctx->device->uma) {
  3887. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3888. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3889. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3890. src0_uma = d_Qx != nullptr;
  3891. src1_uma = d_Qy != nullptr;
  3892. ids_uma = d_ids != nullptr;
  3893. }
  3894. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3895. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3896. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3897. const bool qx_needs_dequant = x_non_contig;
  3898. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3899. // Not implemented
  3900. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3901. const uint64_t x_ne = ne01 * ne00;
  3902. const uint64_t y_ne = ne11 * ne10;
  3903. const uint64_t d_ne = ne21 * ne20;
  3904. const uint64_t qx_sz = ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  3905. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3906. const uint64_t x_sz = x_non_contig ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : qx_sz;
  3907. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3908. const uint64_t ids_sz = nbi2;
  3909. const uint64_t d_sz = sizeof(float) * d_ne;
  3910. vk_pipeline to_fp16_vk_0 = nullptr;
  3911. vk_pipeline to_fp16_vk_1 = nullptr;
  3912. if (x_non_contig) {
  3913. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3914. }
  3915. if (y_non_contig) {
  3916. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3917. } else {
  3918. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3919. }
  3920. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  3921. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3922. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3923. GGML_ASSERT(dmmv != nullptr);
  3924. if (dryrun) {
  3925. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3926. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3927. if (
  3928. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3929. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3930. GGML_ABORT("Requested preallocation size is too large");
  3931. }
  3932. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3933. ctx->prealloc_size_x = x_sz_upd;
  3934. }
  3935. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3936. ctx->prealloc_size_y = y_sz_upd;
  3937. }
  3938. // Request descriptor sets
  3939. if (qx_needs_dequant) {
  3940. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3941. }
  3942. if (qy_needs_dequant) {
  3943. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3944. }
  3945. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3946. return;
  3947. }
  3948. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3949. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3950. GGML_ASSERT(d_D != nullptr);
  3951. vk_buffer d_X;
  3952. uint64_t x_buf_offset = 0;
  3953. vk_buffer d_Y;
  3954. uint64_t y_buf_offset = 0;
  3955. if(!src0_uma) {
  3956. d_Qx = src0_buf_ctx->dev_buffer;
  3957. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3958. GGML_ASSERT(d_Qx != nullptr);
  3959. }
  3960. if(!src1_uma) {
  3961. d_Qy = src1_buf_ctx->dev_buffer;
  3962. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3963. GGML_ASSERT(d_Qy != nullptr);
  3964. }
  3965. if(!ids_uma) {
  3966. d_ids = ids_buf_ctx->dev_buffer;
  3967. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3968. GGML_ASSERT(d_ids != nullptr);
  3969. }
  3970. if (qx_needs_dequant) {
  3971. d_X = ctx->prealloc_x;
  3972. } else {
  3973. d_X = d_Qx;
  3974. x_buf_offset = qx_buf_offset;
  3975. GGML_ASSERT(qx_sz == x_sz);
  3976. }
  3977. if (qy_needs_dequant) {
  3978. d_Y = ctx->prealloc_y;
  3979. } else {
  3980. d_Y = d_Qy;
  3981. y_buf_offset = qy_buf_offset;
  3982. GGML_ASSERT(qy_sz == y_sz);
  3983. }
  3984. if (x_non_contig) {
  3985. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3986. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3987. }
  3988. if (y_non_contig) {
  3989. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3990. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3991. }
  3992. uint32_t stride_batch_y = ne10*ne11;
  3993. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3994. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3995. }
  3996. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3997. uint32_t groups_x = ne01;
  3998. uint32_t groups_z = 1;
  3999. if (ne01 > max_groups_x) {
  4000. groups_z = 64;
  4001. groups_x = CEIL_DIV(groups_x, groups_z);
  4002. }
  4003. // compute
  4004. const vk_mat_vec_id_push_constants pc = {
  4005. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  4006. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  4007. (uint32_t)nei0, (uint32_t)ne11,
  4008. };
  4009. ggml_vk_sync_buffers(subctx);
  4010. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  4011. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  4012. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23}, vk_subbuffer{ d_ids, ids_buf_offset, ids_sz } },
  4013. sizeof(vk_mat_vec_id_push_constants), &pc, { groups_x, (uint32_t)nei0, groups_z });
  4014. }
  4015. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  4016. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  4017. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  4018. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  4019. } else {
  4020. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  4021. }
  4022. }
  4023. static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, ggml_tensor * dst, bool dryrun = false) {
  4024. VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3];
  4025. std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3];
  4026. std::cerr << "), (" << v << ", name=" << v->name << ", type=" << v->type << ", ne0=" << v->ne[0] << ", ne1=" << v->ne[1] << ", ne2=" << v->ne[2] << ", ne3=" << v->ne[3] << ", nb0=" << v->nb[0] << ", nb1=" << v->nb[1] << ", nb2=" << v->nb[2] << ", nb3=" << v->nb[3];
  4027. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  4028. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  4029. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  4030. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  4031. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  4032. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  4033. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  4034. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  4035. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  4036. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  4037. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  4038. const uint32_t nbm1 = mask ? mask->nb[1] : 0;
  4039. const uint32_t D = neq0;
  4040. const uint32_t N = neq1;
  4041. const uint32_t KV = nek1;
  4042. GGML_ASSERT(ne0 == D);
  4043. GGML_ASSERT(ne2 == N);
  4044. // input tensor rows must be contiguous
  4045. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  4046. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  4047. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  4048. GGML_ASSERT(neq0 == D);
  4049. GGML_ASSERT(nek0 == D);
  4050. GGML_ASSERT(nev0 == D);
  4051. GGML_ASSERT(neq1 == N);
  4052. GGML_ASSERT(nev0 == D);
  4053. GGML_ASSERT(nev1 == nek1);
  4054. // dst cannot be transposed or permuted
  4055. GGML_ASSERT(nb0 == sizeof(float));
  4056. GGML_ASSERT(nb0 <= nb1);
  4057. GGML_ASSERT(nb1 <= nb2);
  4058. GGML_ASSERT(nb2 <= nb3);
  4059. assert(dst->type == GGML_TYPE_F32);
  4060. assert(q->type == GGML_TYPE_F32);
  4061. assert(k->type == v->type);
  4062. vk_pipeline *pipelines;
  4063. // XXX TODO other backends may be changing accumulator precision to default to f32 soon
  4064. bool f32acc = dst->op_params[3] == GGML_PREC_F32;
  4065. bool small_rows = N <= flash_attention_num_small_rows;
  4066. switch (D) {
  4067. case 64: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D64[k->type][f32acc][small_rows][0]; break;
  4068. case 80: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D80[k->type][f32acc][small_rows][0]; break;
  4069. case 96: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D96[k->type][f32acc][small_rows][0]; break;
  4070. case 112: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D112[k->type][f32acc][small_rows][0]; break;
  4071. case 128: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D128[k->type][f32acc][small_rows][0]; break;
  4072. case 256: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D256[k->type][f32acc][small_rows][0]; break;
  4073. default:
  4074. assert(!"unsupported D value");
  4075. return;
  4076. }
  4077. assert(pipelines);
  4078. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  4079. const uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  4080. const uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  4081. bool aligned = (KV % pipelines[1]->align) == 0 &&
  4082. // the "aligned" shader variant will forcibly align strides, for performance
  4083. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  4084. vk_pipeline pipeline = pipelines[aligned];
  4085. assert(pipeline);
  4086. if (dryrun) {
  4087. // Request descriptor sets
  4088. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4089. return;
  4090. }
  4091. float scale = 1.0f;
  4092. float max_bias = 0.0f;
  4093. float logit_softcap = 0.0f;
  4094. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  4095. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  4096. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  4097. if (logit_softcap != 0) {
  4098. scale /= logit_softcap;
  4099. }
  4100. const uint32_t n_head_kv = neq2;
  4101. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  4102. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  4103. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  4104. ggml_vk_sync_buffers(subctx);
  4105. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr;
  4106. size_t q_buf_offset = 0, k_buf_offset = 0, v_buf_offset = 0, d_buf_offset = 0, m_buf_offset = 0;
  4107. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false;
  4108. if (ctx->device->uma) {
  4109. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  4110. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  4111. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  4112. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  4113. Q_uma = d_Q != nullptr;
  4114. K_uma = d_K != nullptr;
  4115. V_uma = d_V != nullptr;
  4116. D_uma = d_D != nullptr;
  4117. if (mask) {
  4118. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  4119. M_uma = d_M != nullptr;
  4120. }
  4121. }
  4122. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4123. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  4124. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  4125. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  4126. if (!Q_uma) {
  4127. d_Q = q_buf_ctx->dev_buffer;
  4128. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  4129. }
  4130. if (!K_uma) {
  4131. d_K = k_buf_ctx->dev_buffer;
  4132. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  4133. }
  4134. if (!V_uma) {
  4135. d_V = v_buf_ctx->dev_buffer;
  4136. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  4137. }
  4138. if (!D_uma) {
  4139. d_D = d_buf_ctx->dev_buffer;
  4140. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4141. }
  4142. if (!M_uma) {
  4143. d_M = d_Q;
  4144. m_buf_offset = q_buf_offset;
  4145. if (mask) {
  4146. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  4147. d_M = m_buf_ctx->dev_buffer;
  4148. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  4149. }
  4150. }
  4151. const vk_flash_attn_push_constants pc = { N, KV,
  4152. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  4153. (uint32_t)neq2, (uint32_t)neq3,
  4154. (uint32_t)nek2, (uint32_t)nek3,
  4155. (uint32_t)nev2, (uint32_t)nev3,
  4156. nem1,
  4157. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  4158. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  4159. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  4160. nbm1,
  4161. scale, max_bias, logit_softcap,
  4162. mask != nullptr, n_head_log2, m0, m1 };
  4163. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  4164. {
  4165. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  4166. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  4167. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  4168. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  4169. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  4170. },
  4171. sizeof(vk_flash_attn_push_constants), &pc, { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3 });
  4172. }
  4173. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, ggml_op op) {
  4174. switch (op) {
  4175. case GGML_OP_GET_ROWS:
  4176. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  4177. if (dst->type == GGML_TYPE_F16) {
  4178. return ctx->device->pipeline_get_rows[src0->type];
  4179. }
  4180. if (dst->type == GGML_TYPE_F32) {
  4181. return ctx->device->pipeline_get_rows_f32[src0->type];
  4182. }
  4183. return nullptr;
  4184. case GGML_OP_ACC:
  4185. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4186. return ctx->device->pipeline_acc_f32;
  4187. }
  4188. return nullptr;
  4189. case GGML_OP_ADD:
  4190. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4191. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f32_norepeat : ctx->device->pipeline_add_f32;
  4192. }
  4193. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4194. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f16_f32_f16_norepeat : ctx->device->pipeline_add_f16_f32_f16;
  4195. }
  4196. return nullptr;
  4197. case GGML_OP_MUL:
  4198. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4199. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_f32_norepeat : ctx->device->pipeline_mul_f32;
  4200. }
  4201. return nullptr;
  4202. case GGML_OP_DIV:
  4203. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4204. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_f32_norepeat : ctx->device->pipeline_div_f32;
  4205. }
  4206. return nullptr;
  4207. case GGML_OP_CONCAT:
  4208. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4209. return ctx->device->pipeline_concat_f32;
  4210. }
  4211. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4212. return ctx->device->pipeline_concat_f16;
  4213. }
  4214. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  4215. return ctx->device->pipeline_concat_i32;
  4216. }
  4217. return nullptr;
  4218. case GGML_OP_UPSCALE:
  4219. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4220. return ctx->device->pipeline_upscale_f32;
  4221. }
  4222. return nullptr;
  4223. case GGML_OP_SCALE:
  4224. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4225. return ctx->device->pipeline_scale_f32;
  4226. }
  4227. return nullptr;
  4228. case GGML_OP_SQR:
  4229. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4230. return ctx->device->pipeline_sqr_f32;
  4231. }
  4232. return nullptr;
  4233. case GGML_OP_SIN:
  4234. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4235. return ctx->device->pipeline_sin_f32;
  4236. }
  4237. return nullptr;
  4238. case GGML_OP_COS:
  4239. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4240. return ctx->device->pipeline_cos_f32;
  4241. }
  4242. return nullptr;
  4243. case GGML_OP_CLAMP:
  4244. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4245. return ctx->device->pipeline_clamp_f32;
  4246. }
  4247. return nullptr;
  4248. case GGML_OP_PAD:
  4249. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4250. return ctx->device->pipeline_pad_f32;
  4251. }
  4252. return nullptr;
  4253. case GGML_OP_REPEAT:
  4254. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  4255. return ctx->device->pipeline_repeat_f32;
  4256. }
  4257. return nullptr;
  4258. case GGML_OP_CPY:
  4259. case GGML_OP_CONT:
  4260. case GGML_OP_DUP:
  4261. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  4262. case GGML_OP_NORM:
  4263. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4264. return ctx->device->pipeline_norm_f32;
  4265. }
  4266. return nullptr;
  4267. case GGML_OP_GROUP_NORM:
  4268. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4269. return ctx->device->pipeline_group_norm_f32;
  4270. }
  4271. return nullptr;
  4272. case GGML_OP_RMS_NORM:
  4273. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4274. return ctx->device->pipeline_rms_norm_f32;
  4275. }
  4276. return nullptr;
  4277. case GGML_OP_UNARY:
  4278. switch (ggml_get_unary_op(dst)) {
  4279. case GGML_UNARY_OP_SILU:
  4280. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4281. return ctx->device->pipeline_silu_f32;
  4282. }
  4283. break;
  4284. case GGML_UNARY_OP_GELU:
  4285. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4286. return ctx->device->pipeline_gelu_f32;
  4287. }
  4288. break;
  4289. case GGML_UNARY_OP_GELU_QUICK:
  4290. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4291. return ctx->device->pipeline_gelu_quick_f32;
  4292. }
  4293. break;
  4294. case GGML_UNARY_OP_RELU:
  4295. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4296. return ctx->device->pipeline_relu_f32;
  4297. }
  4298. break;
  4299. case GGML_UNARY_OP_TANH:
  4300. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4301. return ctx->device->pipeline_tanh_f32;
  4302. }
  4303. break;
  4304. default:
  4305. break;
  4306. }
  4307. return nullptr;
  4308. case GGML_OP_DIAG_MASK_INF:
  4309. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4310. return ctx->device->pipeline_diag_mask_inf_f32;
  4311. }
  4312. return nullptr;
  4313. case GGML_OP_SOFT_MAX:
  4314. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  4315. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  4316. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  4317. }
  4318. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  4319. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  4320. }
  4321. return nullptr;
  4322. case GGML_OP_ROPE:
  4323. {
  4324. const int mode = ((const int32_t *) dst->op_params)[2];
  4325. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  4326. if (is_neox) {
  4327. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4328. return ctx->device->pipeline_rope_neox_f32;
  4329. }
  4330. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4331. return ctx->device->pipeline_rope_neox_f16;
  4332. }
  4333. } else {
  4334. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4335. return ctx->device->pipeline_rope_norm_f32;
  4336. }
  4337. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4338. return ctx->device->pipeline_rope_norm_f16;
  4339. }
  4340. }
  4341. return nullptr;
  4342. }
  4343. case GGML_OP_ARGSORT:
  4344. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  4345. return ctx->device->pipeline_argsort_f32;
  4346. }
  4347. return nullptr;
  4348. case GGML_OP_SUM_ROWS:
  4349. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4350. return ctx->device->pipeline_sum_rows_f32;
  4351. }
  4352. return nullptr;
  4353. case GGML_OP_IM2COL:
  4354. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4355. return ctx->device->pipeline_im2col_f32;
  4356. }
  4357. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4358. return ctx->device->pipeline_im2col_f32_f16;
  4359. }
  4360. return nullptr;
  4361. case GGML_OP_TIMESTEP_EMBEDDING:
  4362. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4363. return ctx->device->pipeline_timestep_embedding_f32;
  4364. }
  4365. return nullptr;
  4366. case GGML_OP_POOL_2D:
  4367. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4368. return ctx->device->pipeline_pool2d_f32;
  4369. }
  4370. return nullptr;
  4371. case GGML_OP_RWKV_WKV6:
  4372. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4373. return ctx->device->pipeline_rwkv_wkv6_f32;
  4374. }
  4375. return nullptr;
  4376. case GGML_OP_LEAKY_RELU:
  4377. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4378. return ctx->device->pipeline_leaky_relu_f32;
  4379. }
  4380. return nullptr;
  4381. default:
  4382. return nullptr;
  4383. }
  4384. GGML_UNUSED(src2);
  4385. }
  4386. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  4387. switch (op) {
  4388. case GGML_OP_CPY:
  4389. case GGML_OP_GET_ROWS:
  4390. case GGML_OP_ADD:
  4391. case GGML_OP_MUL:
  4392. case GGML_OP_DIV:
  4393. case GGML_OP_CONCAT:
  4394. case GGML_OP_UPSCALE:
  4395. case GGML_OP_SQR:
  4396. case GGML_OP_SIN:
  4397. case GGML_OP_COS:
  4398. case GGML_OP_CLAMP:
  4399. case GGML_OP_PAD:
  4400. case GGML_OP_REPEAT:
  4401. return true;
  4402. default:
  4403. return false;
  4404. }
  4405. }
  4406. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  4407. {
  4408. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  4409. }
  4410. template <typename T> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, T &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  4411. GGML_UNUSED(p);
  4412. GGML_UNUSED(src0);
  4413. GGML_UNUSED(src1);
  4414. GGML_UNUSED(src2);
  4415. GGML_UNUSED(dst);
  4416. static_assert(!std::is_const<T>::value, "unexpected type");
  4417. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  4418. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  4419. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  4420. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  4421. }
  4422. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_unary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  4423. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4424. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4425. p.misalign_offsets = (a_offset << 16) | d_offset;
  4426. GGML_UNUSED(src1);
  4427. GGML_UNUSED(src2);
  4428. }
  4429. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_binary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  4430. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4431. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  4432. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4433. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  4434. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  4435. GGML_UNUSED(src2);
  4436. }
  4437. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_upscale_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  4438. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4439. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4440. p.a_offset = a_offset;
  4441. p.d_offset = d_offset;
  4442. GGML_UNUSED(src1);
  4443. GGML_UNUSED(src2);
  4444. }
  4445. template<typename PC>
  4446. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, ggml_op op, PC&& pc, bool dryrun = false) {
  4447. VK_LOG_DEBUG("ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  4448. if (src1 != nullptr) {
  4449. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  4450. }
  4451. if (src2 != nullptr) {
  4452. std::cerr << "), (" << src2 << ", name=" << src2->name << ", type=" << src2->type << ", ne0=" << src2->ne[0] << ", ne1=" << src2->ne[1] << ", ne2=" << src2->ne[2] << ", ne3=" << src2->ne[3] << ", nb0=" << src2->nb[0] << ", nb1=" << src2->nb[1] << ", nb2=" << src2->nb[2] << ", nb3=" << src2->nb[3];
  4453. }
  4454. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  4455. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  4456. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  4457. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  4458. GGML_ASSERT(dst->buffer != nullptr);
  4459. const uint64_t ne00 = src0->ne[0];
  4460. const uint64_t ne01 = src0->ne[1];
  4461. const uint64_t ne02 = src0->ne[2];
  4462. const uint64_t ne03 = src0->ne[3];
  4463. const uint64_t ne0 = ne00 * ne01;
  4464. const bool use_src1 = src1 != nullptr;
  4465. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  4466. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  4467. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  4468. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  4469. const uint64_t ne1 = ne10 * ne11;
  4470. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  4471. const bool use_src2 = src2 != nullptr;
  4472. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  4473. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  4474. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  4475. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  4476. const uint64_t ne2 = ne20 * ne21;
  4477. const uint64_t ned0 = dst->ne[0];
  4478. const uint64_t ned1 = dst->ne[1];
  4479. const uint64_t ned2 = dst->ne[2];
  4480. const uint64_t ned3 = dst->ne[3];
  4481. const uint64_t ned = ned0 * ned1;
  4482. init_pushconst_fastdiv(pc);
  4483. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  4484. if (pipeline == nullptr) {
  4485. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  4486. if (src1 != nullptr) {
  4487. std::cerr << " and " << ggml_type_name(src1->type);
  4488. }
  4489. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  4490. GGML_ABORT("fatal error");
  4491. }
  4492. if (dryrun) {
  4493. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4494. return;
  4495. }
  4496. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  4497. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4498. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4499. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  4500. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  4501. vk_buffer d_X = nullptr;
  4502. size_t x_buf_offset = 0;
  4503. vk_buffer d_Y = nullptr;
  4504. size_t y_buf_offset = 0;
  4505. vk_buffer d_Z = nullptr;
  4506. size_t z_buf_offset = 0;
  4507. bool src0_uma = false;
  4508. bool src1_uma = false;
  4509. bool src2_uma = false;
  4510. if (ctx->device->uma) {
  4511. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  4512. src0_uma = d_X != nullptr;
  4513. if (use_src1) {
  4514. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  4515. src1_uma = d_Y != nullptr;
  4516. }
  4517. if (use_src2) {
  4518. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  4519. src2_uma = d_Z != nullptr;
  4520. }
  4521. }
  4522. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  4523. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  4524. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  4525. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  4526. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4527. // Workaround for tiny tensor inputs on ROPE
  4528. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  4529. y_sz = VK_WHOLE_SIZE;
  4530. }
  4531. GGML_ASSERT(d_D != nullptr);
  4532. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4533. if(!src0_uma) {
  4534. d_X = src0_buf_ctx->dev_buffer;
  4535. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4536. GGML_ASSERT(d_X != nullptr);
  4537. }
  4538. if (use_src1 && !src1_uma) {
  4539. d_Y = src1_buf_ctx->dev_buffer;
  4540. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4541. GGML_ASSERT(d_Y != nullptr);
  4542. }
  4543. if (use_src2 && !src2_uma) {
  4544. d_Z = src2_buf_ctx->dev_buffer;
  4545. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  4546. GGML_ASSERT(d_Z != nullptr);
  4547. }
  4548. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  4549. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, dst);
  4550. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4551. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4552. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4553. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4554. if (op_supports_incontiguous) {
  4555. x_sz = ggml_nbytes(src0);
  4556. y_sz = use_src1 ? ggml_nbytes(src1) : 0;
  4557. z_sz = use_src2 ? ggml_nbytes(src2) : 0;
  4558. d_sz = ggml_nbytes(dst);
  4559. if (x_buf_offset + x_sz >= d_X->size) {
  4560. x_sz = VK_WHOLE_SIZE;
  4561. }
  4562. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  4563. y_sz = VK_WHOLE_SIZE;
  4564. }
  4565. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  4566. z_sz = VK_WHOLE_SIZE;
  4567. }
  4568. if (d_buf_offset + d_sz >= d_D->size) {
  4569. d_sz = VK_WHOLE_SIZE;
  4570. }
  4571. }
  4572. std::array<uint32_t, 3> elements;
  4573. // Single call if dimension 2 is contiguous
  4574. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  4575. switch (op) {
  4576. case GGML_OP_NORM:
  4577. case GGML_OP_RMS_NORM:
  4578. case GGML_OP_SOFT_MAX:
  4579. case GGML_OP_SUM_ROWS:
  4580. {
  4581. const uint32_t nr = ggml_nrows(src0);
  4582. if (nr > 262144) {
  4583. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  4584. } else if (nr > 512) {
  4585. elements = { 512, CEIL_DIV(nr, 512), 1 };
  4586. } else {
  4587. elements = { nr, 1, 1 };
  4588. }
  4589. } break;
  4590. case GGML_OP_GROUP_NORM:
  4591. {
  4592. const uint32_t num_groups = dst->op_params[0];
  4593. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  4594. } break;
  4595. case GGML_OP_DIAG_MASK_INF:
  4596. case GGML_OP_ROPE:
  4597. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  4598. break;
  4599. case GGML_OP_GET_ROWS:
  4600. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  4601. break;
  4602. case GGML_OP_ARGSORT:
  4603. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  4604. break;
  4605. case GGML_OP_IM2COL:
  4606. {
  4607. const bool is_2D = dst->op_params[6] == 1;
  4608. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4609. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4610. const uint32_t KW = src0->ne[0];
  4611. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4612. const uint32_t OW = dst->ne[1];
  4613. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  4614. elements = { OW * KW * KH, OH, batch * IC };
  4615. } break;
  4616. case GGML_OP_TIMESTEP_EMBEDDING:
  4617. {
  4618. const uint32_t dim = dst->op_params[0];
  4619. uint32_t half_ceil = (dim + 1) / 2;
  4620. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  4621. } break;
  4622. case GGML_OP_POOL_2D:
  4623. {
  4624. const uint32_t N = dst->ne[3];
  4625. const uint32_t OC = dst->ne[2];
  4626. const uint32_t OH = dst->ne[1];
  4627. const uint32_t OW = dst->ne[0];
  4628. elements = { N * OC * OH * OW, 1, 1};
  4629. } break;
  4630. case GGML_OP_ADD:
  4631. case GGML_OP_DIV:
  4632. case GGML_OP_MUL:
  4633. case GGML_OP_SCALE:
  4634. case GGML_OP_SQR:
  4635. case GGML_OP_SIN:
  4636. case GGML_OP_COS:
  4637. case GGML_OP_CLAMP:
  4638. case GGML_OP_PAD:
  4639. case GGML_OP_REPEAT:
  4640. case GGML_OP_CPY:
  4641. case GGML_OP_CONCAT:
  4642. case GGML_OP_UPSCALE:
  4643. case GGML_OP_UNARY:
  4644. {
  4645. const uint32_t ne = ggml_nelements(dst);
  4646. if (ne > 262144) {
  4647. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  4648. } else if (ne > 512) {
  4649. elements = { 512, CEIL_DIV(ne, 512), 1 };
  4650. } else {
  4651. elements = { ne, 1, 1 };
  4652. }
  4653. } break;
  4654. default:
  4655. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  4656. break;
  4657. }
  4658. if (!op_supports_incontiguous) {
  4659. if (x_sz != VK_WHOLE_SIZE) {
  4660. x_sz *= ne02 * ne03;
  4661. }
  4662. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  4663. y_sz *= ne12 * ne13;
  4664. }
  4665. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  4666. z_sz *= ne22 * ne23;
  4667. }
  4668. if (d_sz != VK_WHOLE_SIZE) {
  4669. d_sz *= ned2 * ned3;
  4670. }
  4671. }
  4672. if (op == GGML_OP_SOFT_MAX) {
  4673. // Empty src1 is possible in soft_max, but the shader needs a buffer
  4674. vk_subbuffer subbuf_y;
  4675. if (use_src1) {
  4676. subbuf_y = { d_Y, y_buf_offset, y_sz };
  4677. } else {
  4678. subbuf_y = { d_X, 0, x_sz };
  4679. }
  4680. ggml_vk_sync_buffers(subctx);
  4681. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4682. } else if (op == GGML_OP_ROPE) {
  4683. // Empty src2 is possible in rope, but the shader needs a buffer
  4684. vk_subbuffer subbuf_z;
  4685. if (use_src2) {
  4686. subbuf_z = { d_Z, z_buf_offset, z_sz };
  4687. } else {
  4688. subbuf_z = { d_X, 0, x_sz };
  4689. }
  4690. ggml_vk_sync_buffers(subctx);
  4691. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4692. } else if (op == GGML_OP_IM2COL) {
  4693. // im2col uses only src1 and dst buffers
  4694. ggml_vk_sync_buffers(subctx);
  4695. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4696. } else if (use_src2) {
  4697. ggml_vk_sync_buffers(subctx);
  4698. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4699. } else if (use_src1) {
  4700. ggml_vk_sync_buffers(subctx);
  4701. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4702. } else {
  4703. ggml_vk_sync_buffers(subctx);
  4704. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4705. }
  4706. }
  4707. static void ggml_vk_get_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4708. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4709. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4710. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4711. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  4712. (uint32_t)ggml_nelements(src0),
  4713. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4714. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4715. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4716. 0,
  4717. 0.0f, 0.0f, 0,
  4718. }, dryrun);
  4719. }
  4720. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4721. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4722. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4723. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4724. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  4725. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  4726. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  4727. int offset = dst->op_params[3] / 4; // offset in bytes
  4728. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  4729. (uint32_t)ggml_nelements(src0),
  4730. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t)src0->nb[3] / src0_type_size,
  4731. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4732. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t) dst->nb[3] / dst_type_size,
  4733. 0,
  4734. 0.0f, 0.0f, offset,
  4735. }, dryrun);
  4736. }
  4737. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4738. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4739. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4740. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4741. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  4742. (uint32_t)ggml_nelements(src0),
  4743. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4744. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4745. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4746. 0,
  4747. 0.0f, 0.0f, 0,
  4748. }, dryrun);
  4749. }
  4750. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4751. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4752. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4753. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4754. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  4755. (uint32_t)ggml_nelements(src0),
  4756. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4757. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4758. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4759. 0,
  4760. 0.0f, 0.0f, 0,
  4761. }, dryrun);
  4762. }
  4763. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4764. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4765. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4766. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4767. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  4768. (uint32_t)ggml_nelements(src0),
  4769. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4770. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4771. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4772. 0,
  4773. 0.0f, 0.0f, 0,
  4774. }, dryrun);
  4775. }
  4776. static void ggml_vk_op_f32_rwkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, bool dryrun = false) {
  4777. const ggml_tensor * k = dst->src[0];
  4778. const ggml_tensor * v = dst->src[1];
  4779. const ggml_tensor * r = dst->src[2];
  4780. const ggml_tensor * tf = dst->src[3];
  4781. const ggml_tensor * td = dst->src[4];
  4782. const ggml_tensor * state = dst->src[5];
  4783. GGML_ASSERT(!ggml_is_quantized(k->type));
  4784. GGML_ASSERT(!ggml_is_quantized(v->type));
  4785. GGML_ASSERT(!ggml_is_quantized(r->type));
  4786. GGML_ASSERT(!ggml_is_quantized(tf->type));
  4787. GGML_ASSERT(!ggml_is_quantized(td->type));
  4788. GGML_ASSERT(!ggml_is_quantized(state->type));
  4789. GGML_ASSERT(dst->buffer != nullptr);
  4790. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, k, v, r, dst, GGML_OP_RWKV_WKV6);
  4791. GGML_ASSERT(pipeline != nullptr);
  4792. if (dryrun) {
  4793. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4794. return;
  4795. }
  4796. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4797. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  4798. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  4799. ggml_backend_vk_buffer_context * r_buf_ctx = (ggml_backend_vk_buffer_context *)r->buffer->context;
  4800. ggml_backend_vk_buffer_context * tf_buf_ctx = (ggml_backend_vk_buffer_context *)tf->buffer->context;
  4801. ggml_backend_vk_buffer_context * td_buf_ctx = (ggml_backend_vk_buffer_context *)td->buffer->context;
  4802. ggml_backend_vk_buffer_context * state_buf_ctx = (ggml_backend_vk_buffer_context *)state->buffer->context;
  4803. ggml_vk_sync_buffers(subctx);
  4804. vk_buffer d_D = nullptr, d_K = nullptr, d_V = nullptr, d_R = nullptr, d_TF = nullptr, d_TD = nullptr, d_State = nullptr;
  4805. size_t k_offset = 0, v_offset = 0, r_offset = 0, tf_offset = 0, td_offset = 0, state_offset = 0, dst_offset = 0;
  4806. bool K_uma = false, V_uma = false, R_uma = false, TF_uma = false, TD_uma = false, STATE_uma = false, DST_uma = false;
  4807. if (ctx->device->uma) {
  4808. ggml_vk_host_get(ctx->device, k->data, d_K, k_offset);
  4809. ggml_vk_host_get(ctx->device, v->data, d_V, v_offset);
  4810. ggml_vk_host_get(ctx->device, r->data, d_R, r_offset);
  4811. ggml_vk_host_get(ctx->device, tf->data, d_TF, tf_offset);
  4812. ggml_vk_host_get(ctx->device, td->data, d_TD, td_offset);
  4813. ggml_vk_host_get(ctx->device, state->data, d_State, state_offset);
  4814. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  4815. K_uma = d_K != nullptr;
  4816. V_uma = d_V != nullptr;
  4817. R_uma = d_R != nullptr;
  4818. TF_uma = d_TF != nullptr;
  4819. TD_uma = d_TD != nullptr;
  4820. STATE_uma = d_State != nullptr;
  4821. DST_uma = d_D != nullptr;
  4822. }
  4823. if (!K_uma) {
  4824. d_K = k_buf_ctx->dev_buffer;
  4825. k_offset = vk_tensor_offset(k) + k->view_offs;
  4826. }
  4827. if (!V_uma) {
  4828. d_V = v_buf_ctx->dev_buffer;
  4829. v_offset = vk_tensor_offset(v) + v->view_offs;
  4830. }
  4831. if (!R_uma) {
  4832. d_R = r_buf_ctx->dev_buffer;
  4833. r_offset = vk_tensor_offset(r) + r->view_offs;
  4834. }
  4835. if (!TF_uma) {
  4836. d_TF = tf_buf_ctx->dev_buffer;
  4837. tf_offset = vk_tensor_offset(tf) + tf->view_offs;
  4838. }
  4839. if (!TD_uma) {
  4840. d_TD = td_buf_ctx->dev_buffer;
  4841. td_offset = vk_tensor_offset(td) + td->view_offs;
  4842. }
  4843. if (!STATE_uma) {
  4844. d_State = state_buf_ctx->dev_buffer;
  4845. state_offset = vk_tensor_offset(state) + state->view_offs;
  4846. }
  4847. if (!DST_uma) {
  4848. d_D = dst_buf_ctx->dev_buffer;
  4849. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  4850. }
  4851. const uint64_t k_size = ggml_nbytes(k);
  4852. const uint64_t v_size = ggml_nbytes(v);
  4853. const uint64_t r_size = ggml_nbytes(r);
  4854. const uint64_t tf_size = ggml_nbytes(tf);
  4855. const uint64_t td_size = ggml_nbytes(td);
  4856. const uint64_t state_size = ggml_nbytes(state);
  4857. const uint64_t dst_size = ggml_nbytes(dst);
  4858. std::array<uint32_t, 3> elements = {
  4859. (uint32_t)(pc.B * pc.H),
  4860. 1,
  4861. 1
  4862. };
  4863. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  4864. vk_subbuffer{ d_K, k_offset, k_size },
  4865. vk_subbuffer{ d_V, v_offset, v_size },
  4866. vk_subbuffer{ d_R, r_offset, r_size },
  4867. vk_subbuffer{ d_TF, tf_offset, tf_size },
  4868. vk_subbuffer{ d_TD, td_offset, td_size },
  4869. vk_subbuffer{ d_State, state_offset, state_size },
  4870. vk_subbuffer{ d_D, dst_offset, dst_size }
  4871. }, sizeof(vk_op_rwkv_wkv6_push_constants), &pc, elements);
  4872. }
  4873. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  4874. const size_t seq_length = dst->src[0]->ne[2];
  4875. const size_t n_embed = dst->ne[0];
  4876. const size_t n_heads = dst->src[0]->ne[1];
  4877. const size_t n_seqs = dst->src[5]->ne[1];
  4878. ggml_vk_op_f32_rwkv6(
  4879. ctx, subctx, dst,
  4880. {
  4881. (uint32_t)n_seqs,
  4882. (uint32_t)seq_length,
  4883. (uint32_t)n_embed,
  4884. (uint32_t)n_heads,
  4885. },
  4886. dryrun
  4887. );
  4888. }
  4889. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4890. int * op_params = (int *)dst->op_params;
  4891. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4892. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4893. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4894. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  4895. (uint32_t)ggml_nelements(dst),
  4896. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4897. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  4898. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4899. 0,
  4900. 0.0f, 0.0f, op_params[0],
  4901. }, dryrun);
  4902. }
  4903. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4904. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4905. const float sf0 = (float)dst->ne[0] / src0->ne[0];
  4906. const float sf1 = (float)dst->ne[1] / src0->ne[1];
  4907. const float sf2 = (float)dst->ne[2] / src0->ne[2];
  4908. const float sf3 = (float)dst->ne[3] / src0->ne[3];
  4909. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  4910. (uint32_t)ggml_nelements(dst), 0, 0,
  4911. (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4912. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  4913. sf0, sf1, sf2, sf3,
  4914. }, dryrun);
  4915. }
  4916. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4917. float * op_params = (float *)dst->op_params;
  4918. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4919. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4920. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, {
  4921. (uint32_t)ggml_nelements(src0),
  4922. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4923. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4924. 0,
  4925. op_params[0], 0.0f,
  4926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4927. }, dryrun);
  4928. }
  4929. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4930. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4931. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4932. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, {
  4933. (uint32_t)ggml_nelements(src0),
  4934. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4935. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4936. 0,
  4937. 0.0f, 0.0f,
  4938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4939. }, dryrun);
  4940. }
  4941. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4942. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4943. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4944. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, {
  4945. (uint32_t)ggml_nelements(src0),
  4946. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4947. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4948. 0,
  4949. 0.0f, 0.0f,
  4950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4951. }, dryrun);
  4952. }
  4953. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4954. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4955. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4956. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, {
  4957. (uint32_t)ggml_nelements(src0),
  4958. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4959. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4960. 0,
  4961. 0.0f, 0.0f,
  4962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4963. }, dryrun);
  4964. }
  4965. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4966. float * op_params = (float *)dst->op_params;
  4967. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4968. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4969. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, {
  4970. (uint32_t)ggml_nelements(src0),
  4971. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4972. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4973. 0,
  4974. op_params[0], op_params[1],
  4975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4976. }, dryrun);
  4977. }
  4978. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4979. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4980. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4981. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, {
  4982. (uint32_t)ggml_nelements(dst),
  4983. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4984. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4985. 0,
  4986. 0.0f, 0.0f,
  4987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4988. }, dryrun);
  4989. }
  4990. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4991. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4992. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4993. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, {
  4994. (uint32_t)ggml_nelements(dst),
  4995. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  4996. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  4997. 0,
  4998. 0.0f, 0.0f,
  4999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5000. }, dryrun);
  5001. }
  5002. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5003. const uint32_t src0_type_size = ggml_type_size(src0->type);
  5004. const uint32_t dst_type_size = ggml_type_size(dst->type);
  5005. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, {
  5006. (uint32_t)ggml_nelements(src0),
  5007. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2], (uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  5008. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  5009. 0,
  5010. 0.0f, 0.0f,
  5011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5012. }, dryrun);
  5013. }
  5014. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5015. float * op_params = (float *)dst->op_params;
  5016. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  5017. }
  5018. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5019. const int * int_op_params = (const int *)dst->op_params;
  5020. const float * float_op_params = (const float *)dst->op_params;
  5021. const uint32_t num_groups = int_op_params[0];
  5022. const float eps = float_op_params[1];
  5023. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  5024. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f }, dryrun);
  5025. }
  5026. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5027. float * op_params = (float *)dst->op_params;
  5028. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_RMS_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  5029. }
  5030. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5031. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  5032. }
  5033. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5034. int32_t * op_params = (int32_t *)dst->op_params;
  5035. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] }, dryrun);
  5036. }
  5037. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5038. float * op_params = (float *)dst->op_params;
  5039. float scale = op_params[0];
  5040. float max_bias = op_params[1];
  5041. const uint32_t ncols = (uint32_t)src0->ne[0];
  5042. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  5043. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  5044. const uint32_t n_head_kv = nrows_x/nrows_y;
  5045. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  5046. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  5047. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  5048. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SOFT_MAX, {
  5049. ncols,
  5050. src1 != nullptr ? nrows_y : (uint32_t)0,
  5051. scale, max_bias,
  5052. m0, m1,
  5053. n_head_log2,
  5054. nrows_x,
  5055. }, dryrun);
  5056. }
  5057. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  5058. const int n_dims = ((int32_t *) dst->op_params)[1];
  5059. // const int mode = ((int32_t *) dst->op_params)[2];
  5060. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  5061. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  5062. const float freq_base = ((float *) dst->op_params)[5];
  5063. const float freq_scale = ((float *) dst->op_params)[6];
  5064. const float ext_factor = ((float *) dst->op_params)[7];
  5065. const float attn_factor = ((float *) dst->op_params)[8];
  5066. const float beta_fast = ((float *) dst->op_params)[9];
  5067. const float beta_slow = ((float *) dst->op_params)[10];
  5068. float corr_dims[2];
  5069. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  5070. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  5071. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  5072. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  5073. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  5074. src2 != nullptr,
  5075. }, dryrun);
  5076. }
  5077. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5078. int32_t * op_params = (int32_t *)dst->op_params;
  5079. uint32_t ncols = src0->ne[0];
  5080. uint32_t ncols_pad = 1;
  5081. while (ncols_pad < ncols) {
  5082. ncols_pad *= 2;
  5083. }
  5084. GGML_ASSERT(ncols_pad <= 1024);
  5085. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  5086. ncols,
  5087. ncols_pad,
  5088. op_params[0],
  5089. }, dryrun);
  5090. }
  5091. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5092. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, { (uint32_t)src0->ne[0], 0, 0.0f, 0.0f }, dryrun);
  5093. }
  5094. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5095. const int32_t s0 = dst->op_params[0];
  5096. const int32_t s1 = dst->op_params[1];
  5097. const int32_t p0 = dst->op_params[2];
  5098. const int32_t p1 = dst->op_params[3];
  5099. const int32_t d0 = dst->op_params[4];
  5100. const int32_t d1 = dst->op_params[5];
  5101. const bool is_2D = dst->op_params[6] == 1;
  5102. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  5103. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  5104. const uint32_t IW = src1->ne[0];
  5105. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  5106. const uint32_t KW = src0->ne[0];
  5107. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  5108. const uint32_t OW = dst->ne[1];
  5109. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  5110. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  5111. const uint32_t pelements = OW * KW * KH;
  5112. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  5113. batch_offset, offset_delta,
  5114. IC, IW, IH, OW, OH, KW, KH,
  5115. pelements,
  5116. IC * KH * KW,
  5117. s0, s1, p0, p1, d0, d1,
  5118. }, dryrun);
  5119. }
  5120. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5121. const uint32_t dim = dst->op_params[0];
  5122. const uint32_t max_period = dst->op_params[1];
  5123. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  5124. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  5125. nb1, dim, max_period,
  5126. }, dryrun);
  5127. }
  5128. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5129. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  5130. const int32_t k1 = dst->op_params[1];
  5131. const int32_t k0 = dst->op_params[2];
  5132. const int32_t s1 = dst->op_params[3];
  5133. const int32_t s0 = dst->op_params[4];
  5134. const int32_t p1 = dst->op_params[5];
  5135. const int32_t p0 = dst->op_params[6];
  5136. const uint32_t IH = src0->ne[1];
  5137. const uint32_t IW = src0->ne[0];
  5138. const uint32_t N = dst->ne[3];
  5139. const uint32_t OC = dst->ne[2];
  5140. const uint32_t OH = dst->ne[1];
  5141. const uint32_t OW = dst->ne[0];
  5142. const uint32_t parallel_elements = N * OC * OH * OW;
  5143. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  5144. IW, IH, OW, OH, OC,
  5145. parallel_elements,
  5146. op,
  5147. k0, k1, s0, s1, p0, p1,
  5148. }, dryrun);
  5149. }
  5150. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5151. const float * op_params = (const float *)dst->op_params;
  5152. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f }, dryrun);
  5153. }
  5154. #ifdef GGML_VULKAN_RUN_TESTS
  5155. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  5156. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  5157. return;
  5158. }
  5159. i0 = std::max(i0, 5);
  5160. i1 = std::max(i1, 5);
  5161. i2 = std::max(i2, 0);
  5162. fprintf(stderr, " ");
  5163. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5164. fprintf(stderr, "%7d ", idx1);
  5165. }
  5166. fprintf(stderr, "\n");
  5167. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5168. fprintf(stderr, "%7d: ", idx0);
  5169. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5170. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  5171. float val;
  5172. if (type == GGML_TYPE_F32) {
  5173. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  5174. } else if (type == GGML_TYPE_F16) {
  5175. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  5176. } else {
  5177. GGML_ABORT("fatal error");
  5178. }
  5179. fprintf(stderr, "% 7.2f ", val);
  5180. } else {
  5181. fprintf(stderr, " ");
  5182. }
  5183. }
  5184. fprintf(stderr, "\n");
  5185. }
  5186. }
  5187. template <typename X_TYPE, typename Y_TYPE>
  5188. static void ggml_vk_test_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, int split_k, int shader_size) {
  5189. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  5190. const size_t x_ne = m * k * batch;
  5191. const size_t y_ne = k * n * batch;
  5192. const size_t d_ne = m * n * batch;
  5193. vk_pipeline p;
  5194. std::string shname;
  5195. if (shader_size == 0) {
  5196. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5197. p = ctx->device->pipeline_matmul_f32->a_s;
  5198. shname = "F32_ALIGNED_S";
  5199. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5200. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  5201. shname = "F32_F16_ALIGNED_S";
  5202. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5203. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  5204. shname = "F16_F32_ALIGNED_S";
  5205. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5206. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  5207. shname = "F16_ALIGNED_S";
  5208. } else {
  5209. GGML_ABORT("fatal error");
  5210. }
  5211. } else if (shader_size == 1) {
  5212. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5213. p = ctx->device->pipeline_matmul_f32->a_m;
  5214. shname = "F32_ALIGNED_M";
  5215. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5216. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  5217. shname = "F32_F16_ALIGNED_M";
  5218. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5219. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  5220. shname = "F16_F32_ALIGNED_M";
  5221. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5222. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  5223. shname = "F16_ALIGNED_M";
  5224. } else {
  5225. GGML_ABORT("fatal error");
  5226. }
  5227. } else if (shader_size == 2) {
  5228. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5229. p = ctx->device->pipeline_matmul_f32->a_l;
  5230. shname = "F32_ALIGNED_L";
  5231. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5232. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  5233. shname = "F32_F16_ALIGNED_L";
  5234. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5235. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  5236. shname = "F16_F32_ALIGNED_L";
  5237. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5238. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  5239. shname = "F16_ALIGNED_L";
  5240. } else {
  5241. GGML_ABORT("fatal error");
  5242. }
  5243. } else {
  5244. GGML_ASSERT(0);
  5245. }
  5246. const size_t kpad = ggml_vk_align_size(k, p->align);
  5247. if (k != kpad) {
  5248. if (shader_size == 0) {
  5249. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5250. p = ctx->device->pipeline_matmul_f32->s;
  5251. shname = "F32_S";
  5252. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5253. p = ctx->device->pipeline_matmul_f32_f16->s;
  5254. shname = "F32_F16_S";
  5255. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5256. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  5257. shname = "F16_F32_S";
  5258. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5259. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  5260. shname = "F16_S";
  5261. }
  5262. } else if (shader_size == 1) {
  5263. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5264. p = ctx->device->pipeline_matmul_f32->m;
  5265. shname = "F32_M";
  5266. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5267. p = ctx->device->pipeline_matmul_f32_f16->m;
  5268. shname = "F32_F16_M";
  5269. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5270. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  5271. shname = "F16_F32_M";
  5272. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5273. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  5274. shname = "F16_M";
  5275. }
  5276. } else if (shader_size == 2) {
  5277. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5278. p = ctx->device->pipeline_matmul_f32->l;
  5279. shname = "F32_L";
  5280. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5281. p = ctx->device->pipeline_matmul_f32_f16->l;
  5282. shname = "F32_F16_L";
  5283. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5284. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  5285. shname = "F16_F32_L";
  5286. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5287. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  5288. shname = "F16_L";
  5289. }
  5290. }
  5291. }
  5292. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5293. if (split_k > 1) {
  5294. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5295. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5296. // Resize buffer
  5297. if (ctx->prealloc_split_k != nullptr) {
  5298. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5299. }
  5300. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5301. }
  5302. }
  5303. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5304. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5305. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5306. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5307. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  5308. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  5309. float* d = (float *) malloc(sizeof(float) * d_ne);
  5310. for (size_t i = 0; i < x_ne; i++) {
  5311. if (std::is_same<float, X_TYPE>()) {
  5312. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5313. // x[i] = 1.0f;
  5314. // x[i] = i + 1;
  5315. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5316. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  5317. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  5318. // x[i] = ggml_fp32_to_fp16(1.0f);
  5319. // x[i] = ggml_fp32_to_fp16(i + 1);
  5320. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  5321. } else {
  5322. GGML_ABORT("fatal error");
  5323. }
  5324. }
  5325. for (size_t i = 0; i < y_ne; i++) {
  5326. if (std::is_same<float, Y_TYPE>()) {
  5327. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5328. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5329. // y[i] = i + 1;
  5330. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5331. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  5332. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  5333. // y[i] = ggml_fp32_to_fp16(i + 1);
  5334. } else {
  5335. GGML_ABORT("fatal error");
  5336. }
  5337. }
  5338. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  5339. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  5340. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5341. ggml_vk_ctx_begin(ctx->device, subctx);
  5342. for (size_t i = 0; i < num_it; i++) {
  5343. ggml_vk_matmul(
  5344. ctx, subctx, p, ggml_vk_subbuffer(d_X), ggml_vk_subbuffer(d_Y), ggml_vk_subbuffer(d_D), ggml_vk_subbuffer(ctx->prealloc_split_k),
  5345. m, n, k,
  5346. k, k, m, k*m, k*n, m*n,
  5347. split_k, batch, batch, batch, 1, 1
  5348. );
  5349. }
  5350. ggml_vk_ctx_end(subctx);
  5351. auto begin = std::chrono::high_resolution_clock::now();
  5352. ggml_vk_submit(subctx, ctx->fence);
  5353. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  5354. ctx->device->device.resetFences({ ctx->fence });
  5355. auto end = std::chrono::high_resolution_clock::now();
  5356. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5357. // copy dst to host
  5358. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  5359. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  5360. ggml_init_params iparams = {
  5361. /*.mem_size =*/ 1024*1024*1024,
  5362. /*.mem_buffer =*/ NULL,
  5363. /*.no_alloc =*/ true,
  5364. };
  5365. ggml_context * ggml_ctx = ggml_init(iparams);
  5366. ggml_type src0_type;
  5367. ggml_type src1_type;
  5368. if (std::is_same<float, X_TYPE>()) {
  5369. src0_type = GGML_TYPE_F32;
  5370. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  5371. src0_type = GGML_TYPE_F16;
  5372. } else {
  5373. GGML_ABORT("fatal error");
  5374. }
  5375. if (std::is_same<float, Y_TYPE>()) {
  5376. src1_type = GGML_TYPE_F32;
  5377. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5378. src1_type = GGML_TYPE_F16;
  5379. } else {
  5380. GGML_ABORT("fatal error");
  5381. }
  5382. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  5383. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  5384. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5385. src0_ggml->data = x;
  5386. src1_ggml->data = y;
  5387. tensor_ggml->data = d_chk;
  5388. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5389. ggml_build_forward_expand(cgraph, tensor_ggml);
  5390. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5391. ggml_free(ggml_ctx);
  5392. double avg_err = 0.0;
  5393. int first_err_n = -1;
  5394. int first_err_m = -1;
  5395. int first_err_b = -1;
  5396. for (size_t i = 0; i < m*n*batch; i++) {
  5397. double err = std::fabs(d[i] - d_chk[i]);
  5398. avg_err += err;
  5399. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5400. first_err_b = i / (m * n);
  5401. first_err_n = (i % (m * n)) / m;
  5402. first_err_m = (i % (m * n)) % m;
  5403. }
  5404. }
  5405. avg_err /= m * n;
  5406. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5407. std::cerr << "TEST " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  5408. if (avg_err > 0.1 || std::isnan(avg_err)) {
  5409. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5410. std::cerr << "Actual result: " << std::endl << std::endl;
  5411. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5412. std::cerr << "Expected result: " << std::endl << std::endl;
  5413. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5414. if (split_k > 1) {
  5415. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5416. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5417. std::cerr << "d_buf0: " << std::endl << std::endl;
  5418. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5419. std::cerr << "d_buf1: " << std::endl << std::endl;
  5420. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5421. std::cerr << "d_buf2: " << std::endl << std::endl;
  5422. ggml_vk_print_matrix_area(split_k_buf + 2 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5423. std::cerr << "d_buf3: " << std::endl << std::endl;
  5424. ggml_vk_print_matrix_area(split_k_buf + 3 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5425. free(split_k_buf);
  5426. }
  5427. }
  5428. free(d_chk);
  5429. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5430. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5431. ggml_vk_destroy_buffer(d_X);
  5432. ggml_vk_destroy_buffer(d_Y);
  5433. ggml_vk_destroy_buffer(d_D);
  5434. ggml_pipeline_cleanup(p);
  5435. ggml_pipeline_cleanup(ctx->device->pipeline_matmul_split_k_reduce);
  5436. free(x);
  5437. free(y);
  5438. free(d);
  5439. }
  5440. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  5441. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  5442. return;
  5443. }
  5444. i0 = std::max(i0, 5);
  5445. i1 = std::max(i1, 5);
  5446. i2 = std::max(i2, 0);
  5447. i3 = std::max(i3, 0);
  5448. fprintf(stderr, " ");
  5449. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5450. fprintf(stderr, "%7d ", idx1);
  5451. }
  5452. fprintf(stderr, "\n");
  5453. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5454. fprintf(stderr, "%7d: ", idx0);
  5455. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5456. if (idx0 >= 0 && idx0 < tensor->ne[0] && idx1 >= 0 && idx1 < tensor->ne[1] && i2 >= 0 && i2 < tensor->ne[2] && i3 >= 0 && i3 < tensor->ne[3]) {
  5457. float val;
  5458. if (tensor->type == GGML_TYPE_F32) {
  5459. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  5460. } else if (tensor->type == GGML_TYPE_F16) {
  5461. val = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]));
  5462. } else {
  5463. GGML_ABORT("fatal error");
  5464. }
  5465. fprintf(stderr, "% 7.2f ", val);
  5466. } else {
  5467. fprintf(stderr, " ");
  5468. }
  5469. }
  5470. fprintf(stderr, "\n");
  5471. }
  5472. }
  5473. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  5474. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  5475. }
  5476. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  5477. if (quant == GGML_TYPE_F32) {
  5478. memcpy(to, from, sizeof(float) * ne);
  5479. return;
  5480. }
  5481. const auto * tt = ggml_get_type_traits(quant);
  5482. ggml_to_float_t dequant_fn = tt->to_float;
  5483. dequant_fn(from, to, ne);
  5484. }
  5485. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  5486. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  5487. const size_t x_sz = sizeof(float) * ne;
  5488. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  5489. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5490. float * x = (float *) malloc(x_sz);
  5491. void * qx = malloc(qx_sz);
  5492. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5493. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5494. float * x_ref = (float *) malloc(x_sz);
  5495. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  5496. for (size_t i = 0; i < ne; i++) {
  5497. x[i] = rand() / (float)RAND_MAX;
  5498. }
  5499. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  5500. ggml_vk_quantize_data(x, qx, ne, quant);
  5501. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  5502. ggml_pipeline_request_descriptor_sets(ctx->device, p, 1);
  5503. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5504. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5505. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5506. ggml_vk_ctx_begin(ctx->device, subctx);
  5507. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  5508. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  5509. ggml_vk_ctx_end(subctx);
  5510. auto begin = std::chrono::high_resolution_clock::now();
  5511. ggml_vk_submit(subctx, ctx->fence);
  5512. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5513. ctx->device->device.resetFences({ ctx->fence });
  5514. auto end = std::chrono::high_resolution_clock::now();
  5515. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5516. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  5517. int first_err = -1;
  5518. double avg_err = 0.0;
  5519. for (size_t i = 0; i < ne; i++) {
  5520. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  5521. avg_err += error;
  5522. if (first_err < 0 && error > 0.05) {
  5523. first_err = i;
  5524. }
  5525. }
  5526. avg_err /= ne;
  5527. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  5528. if (avg_err > 0.1) {
  5529. std::cerr << "first_error = " << first_err << std::endl;
  5530. std::cerr << "Actual result: " << std::endl << std::endl;
  5531. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5532. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  5533. }
  5534. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  5535. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5536. std::cerr << x_ref[i] << ", ";
  5537. }
  5538. std::cerr << std::endl;
  5539. }
  5540. ggml_vk_destroy_buffer(x_buf);
  5541. ggml_vk_destroy_buffer(qx_buf);
  5542. free(x);
  5543. free(qx);
  5544. free(x_ref);
  5545. free(x_chk);
  5546. }
  5547. static void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, size_t split_k, size_t shader_size, ggml_type quant) {
  5548. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  5549. const size_t x_ne = m * k * batch;
  5550. const size_t y_ne = k * n * batch;
  5551. const size_t d_ne = m * n * batch;
  5552. vk_pipeline p;
  5553. std::string shname;
  5554. if (shader_size == 0) {
  5555. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_s;
  5556. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  5557. } else if (shader_size == 1) {
  5558. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_m;
  5559. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  5560. } else if (shader_size == 2) {
  5561. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_l;
  5562. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  5563. } else {
  5564. GGML_ASSERT(0);
  5565. }
  5566. const size_t kpad = ggml_vk_align_size(k, p->align);
  5567. if (k != kpad) {
  5568. if (shader_size == 0) {
  5569. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->s;
  5570. shname = std::string(ggml_type_name(quant)) + "_S";
  5571. } else if (shader_size == 1) {
  5572. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->m;
  5573. shname = std::string(ggml_type_name(quant)) + "_M";
  5574. } else if (shader_size == 2) {
  5575. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->l;
  5576. shname = std::string(ggml_type_name(quant)) + "_L";
  5577. } else {
  5578. GGML_ASSERT(0);
  5579. }
  5580. }
  5581. const size_t x_sz = sizeof(float) * x_ne;
  5582. const size_t y_sz = sizeof(float) * y_ne;
  5583. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5584. const size_t d_sz = sizeof(float) * d_ne;
  5585. float * x = (float *) malloc(x_sz);
  5586. float * y = (float *) malloc(y_sz);
  5587. void * qx = malloc(qx_sz);
  5588. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5589. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5590. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5591. float * d = (float *) malloc(d_sz);
  5592. float * d_chk = (float *) malloc(d_sz);
  5593. for (size_t i = 0; i < x_ne; i++) {
  5594. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5595. }
  5596. ggml_vk_quantize_data(x, qx, x_ne, quant);
  5597. for (size_t i = 0; i < y_ne; i++) {
  5598. // y[i] = rand() / (float)RAND_MAX;
  5599. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5600. }
  5601. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5602. if (split_k > 1) {
  5603. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5604. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5605. // Resize buffer
  5606. if (ctx->prealloc_split_k != nullptr) {
  5607. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5608. }
  5609. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5610. }
  5611. }
  5612. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5613. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5614. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  5615. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5616. ggml_vk_ctx_begin(ctx->device, subctx);
  5617. for (size_t i = 0; i < num_it; i++) {
  5618. ggml_vk_matmul(
  5619. ctx, subctx, p, ggml_vk_subbuffer(qx_buf), ggml_vk_subbuffer(y_buf), ggml_vk_subbuffer(d_buf), ggml_vk_subbuffer(ctx->prealloc_split_k),
  5620. m, n, k,
  5621. k, k, m, k*m, k*n, m*n,
  5622. split_k, batch, batch, batch, 1, 1
  5623. );
  5624. }
  5625. ggml_vk_ctx_end(subctx);
  5626. auto begin = std::chrono::high_resolution_clock::now();
  5627. ggml_vk_submit(subctx, ctx->fence);
  5628. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5629. ctx->device->device.resetFences({ ctx->fence });
  5630. auto end = std::chrono::high_resolution_clock::now();
  5631. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5632. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  5633. ggml_init_params iparams = {
  5634. /*.mem_size =*/ 1024*1024*1024,
  5635. /*.mem_buffer =*/ NULL,
  5636. /*.no_alloc =*/ true,
  5637. };
  5638. ggml_context * ggml_ctx = ggml_init(iparams);
  5639. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  5640. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  5641. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5642. src0_ggml->data = qx;
  5643. src1_ggml->data = y;
  5644. tensor_ggml->data = d_chk;
  5645. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5646. ggml_build_forward_expand(cgraph, tensor_ggml);
  5647. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5648. ggml_free(ggml_ctx);
  5649. double avg_err = 0.0;
  5650. int first_err_n = -1;
  5651. int first_err_m = -1;
  5652. int first_err_b = -1;
  5653. for (size_t i = 0; i < m*n*batch; i++) {
  5654. double err = std::fabs(d[i] - d_chk[i]);
  5655. avg_err += err;
  5656. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5657. first_err_b = i / (m * n);
  5658. first_err_n = (i % (m * n)) / m;
  5659. first_err_m = (i % (m * n)) % m;
  5660. }
  5661. }
  5662. avg_err /= m * n;
  5663. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5664. std::cerr << "TEST MMQ " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  5665. if (avg_err > 0.01 || std::isnan(avg_err)) {
  5666. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5667. std::cerr << "Actual result: " << std::endl << std::endl;
  5668. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5669. std::cerr << std::endl;
  5670. std::cerr << "Expected result: " << std::endl << std::endl;
  5671. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5672. if (split_k > 1) {
  5673. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5674. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5675. std::cerr << "d_buf0: " << std::endl << std::endl;
  5676. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5677. std::cerr << "d_buf1: " << std::endl << std::endl;
  5678. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5679. std::cerr << "d_buf2: " << std::endl << std::endl;
  5680. ggml_vk_print_matrix_area(split_k_buf + 2 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5681. std::cerr << "d_buf3: " << std::endl << std::endl;
  5682. ggml_vk_print_matrix_area(split_k_buf + 3 * d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5683. free(split_k_buf);
  5684. }
  5685. }
  5686. ggml_vk_destroy_buffer(qx_buf);
  5687. ggml_vk_destroy_buffer(y_buf);
  5688. ggml_vk_destroy_buffer(d_buf);
  5689. free(x);
  5690. free(qx);
  5691. free(y);
  5692. free(d);
  5693. free(d_chk);
  5694. }
  5695. #endif
  5696. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  5697. #if defined(GGML_VULKAN_RUN_TESTS)
  5698. const std::vector<size_t> vals {
  5699. 512, 512, 128,
  5700. 128, 512, 512,
  5701. 4096, 512, 4096,
  5702. 11008, 512, 4096,
  5703. 4096, 512, 11008,
  5704. 32000, 512, 4096,
  5705. 8, 8, 8,
  5706. 100, 46, 576,
  5707. 623, 111, 128,
  5708. 100, 46, 558,
  5709. 512, 1, 256,
  5710. 128, 110, 622,
  5711. 511, 511, 127,
  5712. 511, 511, 7,
  5713. 511, 511, 17,
  5714. 49, 49, 128,
  5715. 128, 49, 49,
  5716. 4096, 49, 4096,
  5717. };
  5718. const size_t num_it = 100;
  5719. for (size_t i = 0; i < vals.size(); i += 3) {
  5720. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  5721. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  5722. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  5723. std::cerr << '\n';
  5724. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  5725. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  5726. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  5727. std::cerr << '\n';
  5728. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  5729. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  5730. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  5731. std::cerr << '\n' << std::endl;
  5732. if (vals[i + 2] % 32 == 0) {
  5733. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  5734. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  5735. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  5736. std::cerr << '\n';
  5737. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  5738. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  5739. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  5740. std::cerr << '\n';
  5741. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  5742. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  5743. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  5744. std::cerr << '\n' << std::endl;
  5745. }
  5746. if (vals[i + 2] % 256 == 0) {
  5747. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  5748. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  5749. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  5750. std::cerr << '\n';
  5751. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  5752. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  5753. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  5754. std::cerr << '\n';
  5755. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  5756. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  5757. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  5758. std::cerr << '\n' << std::endl;
  5759. }
  5760. }
  5761. GGML_ABORT("fatal error");
  5762. #endif
  5763. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  5764. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  5765. // Resize buffer
  5766. if (ctx->prealloc_x != nullptr) {
  5767. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5768. }
  5769. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  5770. }
  5771. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  5772. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  5773. // Resize buffer
  5774. if (ctx->prealloc_y != nullptr) {
  5775. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5776. }
  5777. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  5778. }
  5779. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  5780. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  5781. // Resize buffer
  5782. if (ctx->prealloc_split_k != nullptr) {
  5783. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5784. }
  5785. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  5786. }
  5787. }
  5788. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_tensor* tensor, int tensor_idx, bool use_fence);
  5789. // Returns true if node has enqueued work into the queue, false otherwise
  5790. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  5791. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool dryrun, bool last_node, bool submit){
  5792. if (ggml_is_empty(node) || !node->buffer) {
  5793. return false;
  5794. }
  5795. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  5796. ctx->semaphore_idx = 0;
  5797. const ggml_tensor * src0 = node->src[0];
  5798. const ggml_tensor * src1 = node->src[1];
  5799. const ggml_tensor * src2 = node->src[2];
  5800. const ggml_tensor * src3 = node->src[3];
  5801. switch (node->op) {
  5802. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  5803. case GGML_OP_RESHAPE:
  5804. case GGML_OP_VIEW:
  5805. case GGML_OP_PERMUTE:
  5806. case GGML_OP_TRANSPOSE:
  5807. case GGML_OP_NONE:
  5808. return false;
  5809. case GGML_OP_UNARY:
  5810. switch (ggml_get_unary_op(node)) {
  5811. case GGML_UNARY_OP_SILU:
  5812. case GGML_UNARY_OP_GELU:
  5813. case GGML_UNARY_OP_GELU_QUICK:
  5814. case GGML_UNARY_OP_RELU:
  5815. case GGML_UNARY_OP_TANH:
  5816. break;
  5817. default:
  5818. return false;
  5819. }
  5820. break;
  5821. case GGML_OP_REPEAT:
  5822. case GGML_OP_GET_ROWS:
  5823. case GGML_OP_ADD:
  5824. case GGML_OP_ACC:
  5825. case GGML_OP_MUL:
  5826. case GGML_OP_DIV:
  5827. case GGML_OP_CONCAT:
  5828. case GGML_OP_UPSCALE:
  5829. case GGML_OP_SCALE:
  5830. case GGML_OP_SQR:
  5831. case GGML_OP_SIN:
  5832. case GGML_OP_COS:
  5833. case GGML_OP_CLAMP:
  5834. case GGML_OP_PAD:
  5835. case GGML_OP_CPY:
  5836. case GGML_OP_CONT:
  5837. case GGML_OP_DUP:
  5838. case GGML_OP_NORM:
  5839. case GGML_OP_GROUP_NORM:
  5840. case GGML_OP_RMS_NORM:
  5841. case GGML_OP_DIAG_MASK_INF:
  5842. case GGML_OP_SOFT_MAX:
  5843. case GGML_OP_ROPE:
  5844. case GGML_OP_MUL_MAT:
  5845. case GGML_OP_MUL_MAT_ID:
  5846. case GGML_OP_ARGSORT:
  5847. case GGML_OP_SUM_ROWS:
  5848. case GGML_OP_IM2COL:
  5849. case GGML_OP_TIMESTEP_EMBEDDING:
  5850. case GGML_OP_POOL_2D:
  5851. case GGML_OP_RWKV_WKV6:
  5852. case GGML_OP_LEAKY_RELU:
  5853. case GGML_OP_FLASH_ATTN_EXT:
  5854. break;
  5855. default:
  5856. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  5857. GGML_ABORT("fatal error");
  5858. return false;
  5859. }
  5860. vk_context compute_ctx;
  5861. if (!dryrun) {
  5862. if (ctx->compute_ctx.expired()) {
  5863. compute_ctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5864. ctx->compute_ctx = compute_ctx;
  5865. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  5866. } else {
  5867. compute_ctx = ctx->compute_ctx.lock();
  5868. }
  5869. } else {
  5870. switch (node->op) {
  5871. case GGML_OP_REPEAT:
  5872. case GGML_OP_ACC:
  5873. case GGML_OP_GET_ROWS:
  5874. case GGML_OP_ADD:
  5875. case GGML_OP_MUL:
  5876. case GGML_OP_DIV:
  5877. case GGML_OP_CONCAT:
  5878. case GGML_OP_UPSCALE:
  5879. case GGML_OP_SCALE:
  5880. case GGML_OP_SQR:
  5881. case GGML_OP_SIN:
  5882. case GGML_OP_COS:
  5883. case GGML_OP_CLAMP:
  5884. case GGML_OP_PAD:
  5885. case GGML_OP_CPY:
  5886. case GGML_OP_CONT:
  5887. case GGML_OP_DUP:
  5888. case GGML_OP_NORM:
  5889. case GGML_OP_GROUP_NORM:
  5890. case GGML_OP_RMS_NORM:
  5891. case GGML_OP_UNARY:
  5892. case GGML_OP_DIAG_MASK_INF:
  5893. case GGML_OP_SOFT_MAX:
  5894. case GGML_OP_ROPE:
  5895. case GGML_OP_ARGSORT:
  5896. case GGML_OP_SUM_ROWS:
  5897. case GGML_OP_IM2COL:
  5898. case GGML_OP_TIMESTEP_EMBEDDING:
  5899. case GGML_OP_POOL_2D:
  5900. case GGML_OP_LEAKY_RELU:
  5901. {
  5902. // These operations all go through ggml_vk_op_f32, so short-circuit and
  5903. // do the only thing needed for the dryrun.
  5904. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  5905. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  5906. return false;
  5907. }
  5908. default:
  5909. break;
  5910. }
  5911. }
  5912. switch (node->op) {
  5913. case GGML_OP_REPEAT:
  5914. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  5915. break;
  5916. case GGML_OP_ACC:
  5917. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  5918. break;
  5919. case GGML_OP_GET_ROWS:
  5920. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  5921. break;
  5922. case GGML_OP_ADD:
  5923. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  5924. break;
  5925. case GGML_OP_MUL:
  5926. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  5927. break;
  5928. case GGML_OP_DIV:
  5929. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  5930. break;
  5931. case GGML_OP_CONCAT:
  5932. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  5933. break;
  5934. case GGML_OP_UPSCALE:
  5935. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  5936. break;
  5937. case GGML_OP_SCALE:
  5938. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  5939. break;
  5940. case GGML_OP_SQR:
  5941. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  5942. break;
  5943. case GGML_OP_SIN:
  5944. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  5945. break;
  5946. case GGML_OP_COS:
  5947. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  5948. break;
  5949. case GGML_OP_CLAMP:
  5950. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  5951. break;
  5952. case GGML_OP_PAD:
  5953. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  5954. break;
  5955. case GGML_OP_CPY:
  5956. case GGML_OP_CONT:
  5957. case GGML_OP_DUP:
  5958. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  5959. break;
  5960. case GGML_OP_NORM:
  5961. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  5962. break;
  5963. case GGML_OP_GROUP_NORM:
  5964. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  5965. break;
  5966. case GGML_OP_RMS_NORM:
  5967. ggml_vk_rms_norm(ctx, compute_ctx, src0, node, dryrun);
  5968. break;
  5969. case GGML_OP_UNARY:
  5970. switch (ggml_get_unary_op(node)) {
  5971. case GGML_UNARY_OP_SILU:
  5972. case GGML_UNARY_OP_GELU:
  5973. case GGML_UNARY_OP_GELU_QUICK:
  5974. case GGML_UNARY_OP_RELU:
  5975. case GGML_UNARY_OP_TANH:
  5976. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  5977. break;
  5978. default:
  5979. return false;
  5980. }
  5981. break;
  5982. case GGML_OP_DIAG_MASK_INF:
  5983. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  5984. break;
  5985. case GGML_OP_SOFT_MAX:
  5986. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, node, dryrun);
  5987. break;
  5988. case GGML_OP_ROPE:
  5989. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  5990. break;
  5991. case GGML_OP_ARGSORT:
  5992. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  5993. break;
  5994. case GGML_OP_SUM_ROWS:
  5995. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  5996. break;
  5997. case GGML_OP_IM2COL:
  5998. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  5999. break;
  6000. case GGML_OP_TIMESTEP_EMBEDDING:
  6001. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  6002. break;
  6003. case GGML_OP_POOL_2D:
  6004. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  6005. break;
  6006. case GGML_OP_LEAKY_RELU:
  6007. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  6008. break;
  6009. case GGML_OP_MUL_MAT:
  6010. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  6011. break;
  6012. case GGML_OP_MUL_MAT_ID:
  6013. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  6014. break;
  6015. case GGML_OP_FLASH_ATTN_EXT:
  6016. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node, dryrun);
  6017. break;
  6018. case GGML_OP_RWKV_WKV6:
  6019. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  6020. break;
  6021. default:
  6022. return false;
  6023. }
  6024. if (dryrun) {
  6025. return false;
  6026. }
  6027. ctx->tensor_ctxs[node_idx] = compute_ctx;
  6028. #if defined(GGML_VULKAN_CHECK_RESULTS) || defined(GGML_VULKAN_PERF)
  6029. // Force context reset on each node so that each tensor ends up in its own context
  6030. // and can be run and compared to its CPU equivalent separately
  6031. last_node = true;
  6032. #endif
  6033. if (submit || last_node) {
  6034. ggml_vk_ctx_end(compute_ctx);
  6035. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  6036. if (last_node) {
  6037. compute_ctx->exit_tensor_idx = node_idx_begin;
  6038. }
  6039. else {
  6040. compute_ctx->exit_tensor_idx = -1;
  6041. }
  6042. ctx->compute_ctx.reset();
  6043. bool ok = ggml_vk_compute_forward(ctx, node_begin, node_idx_begin, false);
  6044. if (!ok) {
  6045. if (node->op == GGML_OP_UNARY) {
  6046. std::cerr << __func__ << ": error: op not supported UNARY " << node->name << " (" << ggml_unary_op_name(static_cast<ggml_unary_op>(node->op_params[0])) << ")" << std::endl;
  6047. }
  6048. else {
  6049. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  6050. }
  6051. }
  6052. }
  6053. return true;
  6054. }
  6055. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_tensor * tensor, int tensor_idx, bool use_fence = true){
  6056. ggml_backend_buffer * buf = nullptr;
  6057. switch (tensor->op) {
  6058. case GGML_OP_ADD:
  6059. case GGML_OP_ACC:
  6060. case GGML_OP_GET_ROWS:
  6061. case GGML_OP_MUL:
  6062. case GGML_OP_DIV:
  6063. case GGML_OP_CONCAT:
  6064. case GGML_OP_UPSCALE:
  6065. case GGML_OP_SCALE:
  6066. case GGML_OP_SQR:
  6067. case GGML_OP_SIN:
  6068. case GGML_OP_COS:
  6069. case GGML_OP_CLAMP:
  6070. case GGML_OP_PAD:
  6071. case GGML_OP_CPY:
  6072. case GGML_OP_CONT:
  6073. case GGML_OP_DUP:
  6074. case GGML_OP_NORM:
  6075. case GGML_OP_GROUP_NORM:
  6076. case GGML_OP_RMS_NORM:
  6077. case GGML_OP_DIAG_MASK_INF:
  6078. case GGML_OP_SOFT_MAX:
  6079. case GGML_OP_ROPE:
  6080. case GGML_OP_RESHAPE:
  6081. case GGML_OP_VIEW:
  6082. case GGML_OP_PERMUTE:
  6083. case GGML_OP_TRANSPOSE:
  6084. case GGML_OP_NONE:
  6085. case GGML_OP_ARGSORT:
  6086. case GGML_OP_SUM_ROWS:
  6087. case GGML_OP_IM2COL:
  6088. case GGML_OP_TIMESTEP_EMBEDDING:
  6089. case GGML_OP_POOL_2D:
  6090. case GGML_OP_RWKV_WKV6:
  6091. case GGML_OP_LEAKY_RELU:
  6092. case GGML_OP_REPEAT:
  6093. buf = tensor->buffer;
  6094. break;
  6095. case GGML_OP_UNARY:
  6096. switch (ggml_get_unary_op(tensor)) {
  6097. case GGML_UNARY_OP_SILU:
  6098. case GGML_UNARY_OP_GELU:
  6099. case GGML_UNARY_OP_GELU_QUICK:
  6100. case GGML_UNARY_OP_RELU:
  6101. case GGML_UNARY_OP_TANH:
  6102. buf = tensor->buffer;
  6103. break;
  6104. default:
  6105. return false;
  6106. }
  6107. break;
  6108. case GGML_OP_MUL_MAT:
  6109. case GGML_OP_MUL_MAT_ID:
  6110. case GGML_OP_FLASH_ATTN_EXT:
  6111. buf = tensor->buffer;
  6112. break;
  6113. default:
  6114. return false;
  6115. }
  6116. if (buf == nullptr) {
  6117. return false;
  6118. }
  6119. VK_LOG_DEBUG("ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << ", view_src=" << tensor->view_src << ", view_offs=" << tensor->view_offs << ")");
  6120. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  6121. // always wait for the GPU work to be done for the last submit
  6122. if (tensor_idx == subctx->exit_tensor_idx) {
  6123. use_fence = true;
  6124. }
  6125. // Only run if ctx hasn't been submitted yet
  6126. if (!subctx->seqs.empty()) {
  6127. #ifdef GGML_VULKAN_CHECK_RESULTS
  6128. ggml_vk_check_results_0(tensor);
  6129. use_fence = true;
  6130. #endif
  6131. // Do staging buffer copies
  6132. for (auto& cpy : subctx->in_memcpys) {
  6133. memcpy(cpy.dst, cpy.src, cpy.n);
  6134. }
  6135. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  6136. if (use_fence) {
  6137. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  6138. ctx->device->device.resetFences({ ctx->fence });
  6139. }
  6140. #ifdef GGML_VULKAN_CHECK_RESULTS
  6141. ggml_vk_check_results_1(tensor);
  6142. #endif
  6143. }
  6144. if (tensor_idx == subctx->exit_tensor_idx) {
  6145. // Do staging buffer copies
  6146. for (auto& cpy : subctx->out_memcpys) {
  6147. memcpy(cpy.dst, cpy.src, cpy.n);
  6148. }
  6149. subctx->in_memcpys.clear();
  6150. subctx->out_memcpys.clear();
  6151. }
  6152. return true;
  6153. }
  6154. // Clean up after graph processing is done
  6155. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  6156. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  6157. for (auto& buffer : ctx->gc.temp_buffers) {
  6158. ggml_vk_pool_free(ctx, buffer);
  6159. }
  6160. ctx->gc.temp_buffers.clear();
  6161. for (auto& dsr : ctx->device->pipeline_descriptor_set_requirements) {
  6162. vk_pipeline_ref plr = ctx->device->pipelines[dsr.first];
  6163. if (plr.expired()) {
  6164. continue;
  6165. }
  6166. vk_pipeline pl = plr.lock();
  6167. ggml_pipeline_cleanup(pl);
  6168. }
  6169. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  6170. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  6171. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  6172. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  6173. }
  6174. ctx->gc.semaphores.clear();
  6175. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  6176. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  6177. }
  6178. ctx->gc.tl_semaphores.clear();
  6179. ctx->semaphore_idx = 0;
  6180. ctx->event_idx = 0;
  6181. for (auto& event : ctx->gc.events) {
  6182. ctx->device->device.resetEvent(event);
  6183. }
  6184. ctx->tensor_ctxs.clear();
  6185. ctx->gc.contexts.clear();
  6186. ctx->device->pipeline_descriptor_set_requirements.clear();
  6187. }
  6188. // Clean up on backend free
  6189. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  6190. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  6191. ggml_vk_graph_cleanup(ctx);
  6192. ggml_vk_destroy_buffer(ctx->prealloc_x);
  6193. ggml_vk_destroy_buffer(ctx->prealloc_y);
  6194. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  6195. for (auto& buffer : ctx->buffer_pool) {
  6196. ggml_vk_destroy_buffer(buffer);
  6197. }
  6198. ctx->prealloc_size_x = 0;
  6199. ctx->prealloc_size_y = 0;
  6200. ctx->prealloc_size_split_k = 0;
  6201. for (auto& event : ctx->gc.events) {
  6202. ctx->device->device.destroyEvent(event);
  6203. }
  6204. ctx->gc.events.clear();
  6205. ctx->device->device.destroyFence(ctx->fence);
  6206. }
  6207. static int ggml_vk_get_device_count() {
  6208. ggml_vk_instance_init();
  6209. return vk_instance.device_indices.size();
  6210. }
  6211. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  6212. ggml_vk_instance_init();
  6213. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  6214. vk::PhysicalDeviceProperties props;
  6215. devices[device].getProperties(&props);
  6216. snprintf(description, description_size, "%s", props.deviceName.data());
  6217. }
  6218. // backend interface
  6219. #define UNUSED GGML_UNUSED
  6220. // device backend
  6221. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  6222. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  6223. }
  6224. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  6225. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  6226. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6227. ggml_vk_destroy_buffer(ctx->dev_buffer);
  6228. delete ctx;
  6229. }
  6230. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  6231. return vk_ptr_base;
  6232. UNUSED(buffer);
  6233. }
  6234. static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  6235. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  6236. if (tensor->view_src != nullptr) {
  6237. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  6238. }
  6239. }
  6240. static void ggml_backend_vk_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  6241. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  6242. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6243. vk_buffer buf = buf_ctx->dev_buffer;
  6244. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6245. }
  6246. static void ggml_backend_vk_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  6247. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  6248. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6249. vk_buffer buf = buf_ctx->dev_buffer;
  6250. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6251. }
  6252. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  6253. if (ggml_backend_buffer_is_vk(src->buffer)) {
  6254. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6255. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6256. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6257. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6258. ggml_vk_buffer_copy(dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  6259. return true;
  6260. }
  6261. return false;
  6262. UNUSED(buffer);
  6263. }
  6264. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  6265. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6266. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  6267. }
  6268. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  6269. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  6270. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  6271. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  6272. /* .memset_tensor = */ NULL,
  6273. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  6274. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  6275. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  6276. /* .clear = */ ggml_backend_vk_buffer_clear,
  6277. /* .reset = */ NULL,
  6278. };
  6279. // vk buffer type
  6280. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  6281. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6282. return ctx->name.c_str();
  6283. }
  6284. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  6285. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  6286. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6287. vk_buffer dev_buffer = nullptr;
  6288. try {
  6289. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  6290. } catch (const vk::SystemError& e) {
  6291. return nullptr;
  6292. }
  6293. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  6294. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  6295. }
  6296. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  6297. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6298. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6299. }
  6300. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  6301. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6302. return ctx->device->max_memory_allocation_size;
  6303. }
  6304. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  6305. return ggml_nbytes(tensor);
  6306. UNUSED(buft);
  6307. }
  6308. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  6309. ggml_vk_instance_init();
  6310. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  6311. vk_device dev = ggml_vk_get_device(dev_num);
  6312. return &dev->buffer_type;
  6313. }
  6314. // host buffer type
  6315. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  6316. return GGML_VK_NAME "_Host";
  6317. UNUSED(buft);
  6318. }
  6319. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  6320. return GGML_VK_NAME "_Host";
  6321. UNUSED(buffer);
  6322. }
  6323. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  6324. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  6325. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  6326. }
  6327. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  6328. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  6329. size += 32; // Behave like the CPU buffer type
  6330. void * ptr = nullptr;
  6331. try {
  6332. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  6333. } catch (vk::SystemError& e) {
  6334. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  6335. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  6336. // fallback to cpu buffer
  6337. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  6338. }
  6339. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  6340. buffer->buft = buft;
  6341. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  6342. return buffer;
  6343. UNUSED(buft);
  6344. }
  6345. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  6346. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  6347. UNUSED(buft);
  6348. }
  6349. // Should be changed to return device-specific host buffer type
  6350. // but that probably requires changes in llama.cpp
  6351. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  6352. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  6353. /* .iface = */ {
  6354. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  6355. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  6356. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  6357. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  6358. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  6359. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  6360. },
  6361. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  6362. /* .context = */ nullptr,
  6363. };
  6364. // Make sure device 0 is initialized
  6365. ggml_vk_instance_init();
  6366. ggml_vk_get_device(0);
  6367. return &ggml_backend_vk_buffer_type_host;
  6368. }
  6369. // backend
  6370. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  6371. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6372. return ctx->name.c_str();
  6373. }
  6374. static void ggml_backend_vk_free(ggml_backend_t backend) {
  6375. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6376. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  6377. ggml_vk_cleanup(ctx);
  6378. delete ctx;
  6379. delete backend;
  6380. }
  6381. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  6382. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6383. return &ctx->device->buffer_type;
  6384. }
  6385. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  6386. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  6387. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6388. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  6389. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6390. vk_context transfer_ctx;
  6391. if (ctx->transfer_ctx.expired()) {
  6392. // Initialize new transfer context
  6393. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6394. ctx->transfer_ctx = transfer_ctx;
  6395. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6396. } else {
  6397. transfer_ctx = ctx->transfer_ctx.lock();
  6398. }
  6399. vk_buffer buf = buf_ctx->dev_buffer;
  6400. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6401. }
  6402. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  6403. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  6404. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6405. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  6406. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6407. vk_context transfer_ctx;
  6408. if (ctx->transfer_ctx.expired()) {
  6409. // Initialize new transfer context
  6410. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6411. ctx->transfer_ctx = transfer_ctx;
  6412. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6413. } else {
  6414. transfer_ctx = ctx->transfer_ctx.lock();
  6415. }
  6416. vk_buffer buf = buf_ctx->dev_buffer;
  6417. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6418. }
  6419. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  6420. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  6421. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6422. if ((dst->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || dst->buffer->buft == ggml_backend_vk_host_buffer_type()) && ggml_backend_buffer_is_vk(src->buffer)) {
  6423. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6424. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6425. vk_context transfer_ctx;
  6426. if (ctx->transfer_ctx.expired()) {
  6427. // Initialize new transfer context
  6428. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6429. ctx->transfer_ctx = transfer_ctx;
  6430. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6431. } else {
  6432. transfer_ctx = ctx->transfer_ctx.lock();
  6433. }
  6434. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6435. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6436. ggml_vk_buffer_copy_async(transfer_ctx, dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  6437. return true;
  6438. }
  6439. return false;
  6440. }
  6441. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  6442. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  6443. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6444. if(ctx->transfer_ctx.expired()) {
  6445. return;
  6446. }
  6447. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  6448. ggml_vk_ctx_end(transfer_ctx);
  6449. for (auto& cpy : transfer_ctx->in_memcpys) {
  6450. memcpy(cpy.dst, cpy.src, cpy.n);
  6451. }
  6452. ggml_vk_submit(transfer_ctx, ctx->fence);
  6453. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  6454. ctx->device->device.resetFences({ ctx->fence });
  6455. for (auto& cpy : transfer_ctx->out_memcpys) {
  6456. memcpy(cpy.dst, cpy.src, cpy.n);
  6457. }
  6458. ctx->transfer_ctx.reset();
  6459. }
  6460. static bool ggml_vk_is_empty(ggml_tensor * node) {
  6461. return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  6462. }
  6463. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  6464. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  6465. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6466. for (int i = 0; i < cgraph->n_nodes; i++) {
  6467. ggml_vk_build_graph(ctx, cgraph->nodes[i], i, nullptr, 0, true, false, false);
  6468. }
  6469. ggml_vk_preallocate_buffers(ctx);
  6470. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  6471. int last_node = cgraph->n_nodes - 1;
  6472. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  6473. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  6474. last_node -= 1;
  6475. }
  6476. // Reserve tensor context space for all nodes
  6477. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  6478. bool first_node_in_batch = true; // true if next node will be first node in a batch
  6479. int submit_node_idx = 0; // index to first node in a batch
  6480. // Submit work every nodes_per_submit nodes to overlap CPU cmdbuffer generation with GPU execution.
  6481. // Start with a smaller count to get work submitted right away, and increase it after each submit.
  6482. int nodes_per_submit = 20;
  6483. int submitted_nodes = 0;
  6484. int submit_count = 0;
  6485. for (int i = 0; i < cgraph->n_nodes; i++) {
  6486. if (first_node_in_batch) {
  6487. submit_node_idx = i;
  6488. }
  6489. bool submit = (submitted_nodes >= nodes_per_submit) || (i == last_node);
  6490. bool enqueued = ggml_vk_build_graph(ctx, cgraph->nodes[i], i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i == last_node, submit);
  6491. if (enqueued) {
  6492. ++submitted_nodes;
  6493. #ifndef GGML_VULKAN_CHECK_RESULTS
  6494. if (first_node_in_batch) {
  6495. first_node_in_batch = false;
  6496. }
  6497. #endif
  6498. }
  6499. if (submit) {
  6500. first_node_in_batch = true;
  6501. submitted_nodes = 0;
  6502. switch (submit_count) {
  6503. case 0:
  6504. nodes_per_submit = 50;
  6505. break;
  6506. default:
  6507. nodes_per_submit = 100;
  6508. break;
  6509. }
  6510. submit_count++;
  6511. }
  6512. }
  6513. #ifdef GGML_VULKAN_PERF
  6514. ctx->device->perf_logger->print_timings();
  6515. #endif
  6516. ggml_vk_graph_cleanup(ctx);
  6517. return GGML_STATUS_SUCCESS;
  6518. UNUSED(backend);
  6519. }
  6520. // TODO: enable async and synchronize
  6521. static ggml_backend_i ggml_backend_vk_interface = {
  6522. /* .get_name = */ ggml_backend_vk_name,
  6523. /* .free = */ ggml_backend_vk_free,
  6524. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  6525. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  6526. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  6527. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  6528. /* .graph_plan_create = */ NULL,
  6529. /* .graph_plan_free = */ NULL,
  6530. /* .graph_plan_update = */ NULL,
  6531. /* .graph_plan_compute = */ NULL,
  6532. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  6533. /* .event_record = */ NULL,
  6534. /* .event_wait = */ NULL,
  6535. };
  6536. static ggml_guid_t ggml_backend_vk_guid() {
  6537. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  6538. return &guid;
  6539. }
  6540. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  6541. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  6542. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  6543. ggml_vk_init(ctx, dev_num);
  6544. ggml_backend_t vk_backend = new ggml_backend {
  6545. /* .guid = */ ggml_backend_vk_guid(),
  6546. /* .interface = */ ggml_backend_vk_interface,
  6547. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  6548. /* .context = */ ctx,
  6549. };
  6550. return vk_backend;
  6551. }
  6552. bool ggml_backend_is_vk(ggml_backend_t backend) {
  6553. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  6554. }
  6555. int ggml_backend_vk_get_device_count() {
  6556. return ggml_vk_get_device_count();
  6557. }
  6558. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  6559. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6560. int dev_idx = vk_instance.device_indices[device];
  6561. ggml_vk_get_device_description(dev_idx, description, description_size);
  6562. }
  6563. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  6564. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6565. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  6566. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  6567. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  6568. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  6569. *total = heap.size;
  6570. *free = heap.size;
  6571. break;
  6572. }
  6573. }
  6574. }
  6575. //////////////////////////
  6576. struct ggml_backend_vk_device_context {
  6577. size_t device;
  6578. std::string name;
  6579. std::string description;
  6580. };
  6581. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  6582. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6583. return ctx->name.c_str();
  6584. }
  6585. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  6586. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6587. return ctx->description.c_str();
  6588. }
  6589. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  6590. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  6591. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  6592. }
  6593. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  6594. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6595. return ggml_backend_vk_buffer_type(ctx->device);
  6596. }
  6597. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  6598. UNUSED(dev);
  6599. return ggml_backend_vk_host_buffer_type();
  6600. }
  6601. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  6602. UNUSED(dev);
  6603. return GGML_BACKEND_DEVICE_TYPE_GPU;
  6604. }
  6605. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  6606. props->name = ggml_backend_vk_device_get_name(dev);
  6607. props->description = ggml_backend_vk_device_get_description(dev);
  6608. props->type = ggml_backend_vk_device_get_type(dev);
  6609. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  6610. props->caps = {
  6611. /* .async = */ false,
  6612. /* .host_buffer = */ true,
  6613. /* .buffer_from_host_ptr = */ false,
  6614. /* .events = */ false,
  6615. };
  6616. }
  6617. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  6618. UNUSED(params);
  6619. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6620. return ggml_backend_vk_init(ctx->device);
  6621. }
  6622. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6623. switch (op->op) {
  6624. case GGML_OP_UNARY:
  6625. switch (ggml_get_unary_op(op)) {
  6626. case GGML_UNARY_OP_GELU:
  6627. case GGML_UNARY_OP_GELU_QUICK:
  6628. case GGML_UNARY_OP_SILU:
  6629. case GGML_UNARY_OP_RELU:
  6630. case GGML_UNARY_OP_TANH:
  6631. return ggml_is_contiguous(op->src[0]);
  6632. default:
  6633. return false;
  6634. }
  6635. break;
  6636. case GGML_OP_MUL_MAT:
  6637. case GGML_OP_MUL_MAT_ID:
  6638. {
  6639. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6640. const vk_device& device = ggml_vk_get_device(ctx->device);
  6641. if (op->op == GGML_OP_MUL_MAT_ID && !device->mul_mat_id_s && !device->mul_mat_id_m && !device->mul_mat_id_l) {
  6642. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  6643. return false;
  6644. }
  6645. switch (op->src[0]->type) {
  6646. case GGML_TYPE_F32:
  6647. case GGML_TYPE_F16:
  6648. case GGML_TYPE_Q4_0:
  6649. case GGML_TYPE_Q4_1:
  6650. case GGML_TYPE_Q5_0:
  6651. case GGML_TYPE_Q5_1:
  6652. case GGML_TYPE_Q8_0:
  6653. case GGML_TYPE_Q2_K:
  6654. case GGML_TYPE_Q3_K:
  6655. case GGML_TYPE_Q4_K:
  6656. case GGML_TYPE_Q5_K:
  6657. case GGML_TYPE_Q6_K:
  6658. case GGML_TYPE_IQ4_NL:
  6659. break;
  6660. default:
  6661. return false;
  6662. }
  6663. struct ggml_tensor * a;
  6664. struct ggml_tensor * b;
  6665. if (op->op == GGML_OP_MUL_MAT) {
  6666. a = op->src[0];
  6667. b = op->src[1];
  6668. } else {
  6669. a = op->src[2];
  6670. b = op->src[1];
  6671. }
  6672. if (a->ne[3] != b->ne[3]) {
  6673. return false;
  6674. }
  6675. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) ||
  6676. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  6677. return false;
  6678. }
  6679. return true;
  6680. } break;
  6681. case GGML_OP_FLASH_ATTN_EXT:
  6682. {
  6683. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6684. if (!ggml_vk_get_device(ctx->device)->coopmat2) {
  6685. return false;
  6686. }
  6687. switch (op->src[0]->ne[0]) {
  6688. case 64:
  6689. case 80:
  6690. case 96:
  6691. case 112:
  6692. case 128:
  6693. case 256:
  6694. break;
  6695. default:
  6696. return false;
  6697. }
  6698. if (op->src[0]->type != GGML_TYPE_F32) {
  6699. return false;
  6700. }
  6701. if (op->type != GGML_TYPE_F32) {
  6702. return false;
  6703. }
  6704. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  6705. return false;
  6706. }
  6707. // It's straightforward to support different K/V dequant, but would
  6708. // significantly increase the number of pipelines
  6709. if (op->src[1]->type != op->src[2]->type) {
  6710. return false;
  6711. }
  6712. switch (op->src[1]->type) {
  6713. case GGML_TYPE_F16:
  6714. case GGML_TYPE_Q4_0:
  6715. case GGML_TYPE_Q4_1:
  6716. case GGML_TYPE_Q5_0:
  6717. case GGML_TYPE_Q5_1:
  6718. case GGML_TYPE_Q8_0:
  6719. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  6720. //case GGML_TYPE_Q2_K:
  6721. //case GGML_TYPE_Q3_K:
  6722. //case GGML_TYPE_Q4_K:
  6723. //case GGML_TYPE_Q5_K:
  6724. //case GGML_TYPE_Q6_K:
  6725. case GGML_TYPE_IQ4_NL:
  6726. break;
  6727. default:
  6728. return false;
  6729. }
  6730. return true;
  6731. }
  6732. case GGML_OP_GET_ROWS:
  6733. {
  6734. switch (op->src[0]->type) {
  6735. case GGML_TYPE_F32:
  6736. case GGML_TYPE_F16:
  6737. case GGML_TYPE_Q4_0:
  6738. case GGML_TYPE_Q4_1:
  6739. case GGML_TYPE_Q5_0:
  6740. case GGML_TYPE_Q5_1:
  6741. case GGML_TYPE_Q8_0:
  6742. case GGML_TYPE_IQ4_NL:
  6743. return true;
  6744. default:
  6745. return false;
  6746. }
  6747. } break;
  6748. case GGML_OP_CONT:
  6749. case GGML_OP_CPY:
  6750. case GGML_OP_DUP:
  6751. {
  6752. ggml_type src0_type = op->src[0]->type;
  6753. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  6754. if (src0_type == GGML_TYPE_F32) {
  6755. switch (src1_type) {
  6756. case GGML_TYPE_F32:
  6757. case GGML_TYPE_F16:
  6758. case GGML_TYPE_Q4_0:
  6759. case GGML_TYPE_Q4_1:
  6760. case GGML_TYPE_Q5_0:
  6761. case GGML_TYPE_Q5_1:
  6762. case GGML_TYPE_Q8_0:
  6763. case GGML_TYPE_IQ4_NL:
  6764. return true;
  6765. default:
  6766. break;
  6767. }
  6768. }
  6769. if (src1_type == GGML_TYPE_F32) {
  6770. switch (src0_type) {
  6771. case GGML_TYPE_Q4_0:
  6772. case GGML_TYPE_Q4_1:
  6773. case GGML_TYPE_Q5_0:
  6774. case GGML_TYPE_Q5_1:
  6775. case GGML_TYPE_Q8_0:
  6776. case GGML_TYPE_IQ4_NL:
  6777. return true;
  6778. default:
  6779. break;
  6780. }
  6781. }
  6782. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  6783. return true;
  6784. }
  6785. return false;
  6786. } break;
  6787. case GGML_OP_REPEAT:
  6788. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  6789. case GGML_OP_ROPE:
  6790. {
  6791. const int mode = ((const int32_t *) op->op_params)[2];
  6792. if (mode & GGML_ROPE_TYPE_MROPE) {
  6793. return false;
  6794. }
  6795. if (mode & GGML_ROPE_TYPE_VISION) {
  6796. return false;
  6797. }
  6798. return ggml_is_contiguous(op->src[0]);
  6799. }
  6800. case GGML_OP_NONE:
  6801. case GGML_OP_RESHAPE:
  6802. case GGML_OP_VIEW:
  6803. case GGML_OP_PERMUTE:
  6804. case GGML_OP_TRANSPOSE:
  6805. case GGML_OP_NORM:
  6806. case GGML_OP_GROUP_NORM:
  6807. case GGML_OP_RMS_NORM:
  6808. case GGML_OP_ADD:
  6809. case GGML_OP_ACC:
  6810. case GGML_OP_MUL:
  6811. case GGML_OP_DIV:
  6812. case GGML_OP_CONCAT:
  6813. case GGML_OP_UPSCALE:
  6814. case GGML_OP_SCALE:
  6815. case GGML_OP_SQR:
  6816. case GGML_OP_SIN:
  6817. case GGML_OP_COS:
  6818. case GGML_OP_CLAMP:
  6819. case GGML_OP_PAD:
  6820. case GGML_OP_DIAG_MASK_INF:
  6821. case GGML_OP_SOFT_MAX:
  6822. case GGML_OP_ARGSORT:
  6823. case GGML_OP_SUM_ROWS:
  6824. case GGML_OP_IM2COL:
  6825. case GGML_OP_TIMESTEP_EMBEDDING:
  6826. case GGML_OP_POOL_2D:
  6827. case GGML_OP_RWKV_WKV6:
  6828. case GGML_OP_LEAKY_RELU:
  6829. return true;
  6830. default:
  6831. return false;
  6832. }
  6833. UNUSED(dev);
  6834. }
  6835. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  6836. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  6837. return false;
  6838. }
  6839. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6840. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6841. return buft_ctx->device->idx == ctx->device;
  6842. }
  6843. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6844. const int min_batch_size = 32;
  6845. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  6846. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  6847. UNUSED(dev);
  6848. }
  6849. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  6850. /* .get_name = */ ggml_backend_vk_device_get_name,
  6851. /* .get_description = */ ggml_backend_vk_device_get_description,
  6852. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  6853. /* .get_type = */ ggml_backend_vk_device_get_type,
  6854. /* .get_props = */ ggml_backend_vk_device_get_props,
  6855. /* .init_backend = */ ggml_backend_vk_device_init,
  6856. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  6857. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  6858. /* .buffer_from_host_ptr = */ NULL,
  6859. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  6860. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  6861. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  6862. /* .event_new = */ NULL,
  6863. /* .event_free = */ NULL,
  6864. /* .event_synchronize = */ NULL,
  6865. };
  6866. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  6867. UNUSED(reg);
  6868. return GGML_VK_NAME;
  6869. }
  6870. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  6871. UNUSED(reg);
  6872. return ggml_backend_vk_get_device_count();
  6873. }
  6874. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  6875. static std::vector<ggml_backend_dev_t> devices;
  6876. static bool initialized = false;
  6877. {
  6878. static std::mutex mutex;
  6879. std::lock_guard<std::mutex> lock(mutex);
  6880. if (!initialized) {
  6881. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  6882. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  6883. char desc[256];
  6884. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  6885. ctx->device = i;
  6886. ctx->name = GGML_VK_NAME + std::to_string(i);
  6887. ctx->description = desc;
  6888. devices.push_back(new ggml_backend_device {
  6889. /* .iface = */ ggml_backend_vk_device_i,
  6890. /* .reg = */ reg,
  6891. /* .context = */ ctx,
  6892. });
  6893. }
  6894. initialized = true;
  6895. }
  6896. }
  6897. GGML_ASSERT(device < devices.size());
  6898. return devices[device];
  6899. }
  6900. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  6901. /* .get_name = */ ggml_backend_vk_reg_get_name,
  6902. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  6903. /* .get_device = */ ggml_backend_vk_reg_get_device,
  6904. /* .get_proc_address = */ NULL,
  6905. };
  6906. ggml_backend_reg_t ggml_backend_vk_reg() {
  6907. static ggml_backend_reg reg = {
  6908. /* .api_version = */ GGML_BACKEND_API_VERSION,
  6909. /* .iface = */ ggml_backend_vk_reg_i,
  6910. /* .context = */ nullptr,
  6911. };
  6912. return &reg;
  6913. }
  6914. // Extension availability
  6915. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6916. #ifdef GGML_VULKAN_VALIDATE
  6917. bool portability_enumeration_ext = false;
  6918. // Check for portability enumeration extension for MoltenVK support
  6919. for (const auto& properties : instance_extensions) {
  6920. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6921. return true;
  6922. }
  6923. }
  6924. if (!portability_enumeration_ext) {
  6925. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6926. }
  6927. #endif
  6928. return false;
  6929. UNUSED(instance_extensions);
  6930. }
  6931. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6932. #ifdef __APPLE__
  6933. bool portability_enumeration_ext = false;
  6934. // Check for portability enumeration extension for MoltenVK support
  6935. for (const auto& properties : instance_extensions) {
  6936. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6937. return true;
  6938. }
  6939. }
  6940. if (!portability_enumeration_ext) {
  6941. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6942. }
  6943. #endif
  6944. return false;
  6945. UNUSED(instance_extensions);
  6946. }
  6947. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props) {
  6948. switch (props.vendorID) {
  6949. case VK_VENDOR_ID_INTEL:
  6950. // Intel drivers don't support coopmat properly yet
  6951. return false;
  6952. case VK_VENDOR_ID_AMD:
  6953. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  6954. // Workaround for AMD proprietary driver reporting support on all GPUs
  6955. const std::string name = props.deviceName;
  6956. return name.rfind("AMD Radeon RX 7", 0) == 0 || name.rfind("AMD Radeon(TM) RX 7", 0) == 0 || // RDNA 3 consumer GPUs
  6957. name.rfind("AMD Radeon PRO W7", 0) == 0 || name.rfind("AMD Radeon(TM) PRO W7", 0) == 0 || // RDNA 3 workstation GPUs
  6958. name.rfind("AMD Radeon 7", 0) == 0 || name.rfind("AMD Radeon(TM) 7", 0) == 0; // RDNA 3 APUs
  6959. }
  6960. return true;
  6961. default:
  6962. return true;
  6963. }
  6964. }
  6965. // checks
  6966. #ifdef GGML_VULKAN_CHECK_RESULTS
  6967. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  6968. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  6969. return;
  6970. }
  6971. for (int j = 0; j < level; j++) {
  6972. std::cerr << " ";
  6973. }
  6974. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  6975. done.push_back(tensor);
  6976. for (int i = 0; i < GGML_MAX_SRC; i++) {
  6977. if (tensor->src[i] != nullptr) {
  6978. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  6979. }
  6980. }
  6981. }
  6982. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  6983. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  6984. return;
  6985. }
  6986. i0 = std::max(i0, 5);
  6987. i1 = std::max(i1, 5);
  6988. i2 = std::max(i2, 0);
  6989. i3 = std::max(i3, 0);
  6990. fprintf(stderr, " ");
  6991. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6992. fprintf(stderr, "%7d ", idx1);
  6993. }
  6994. fprintf(stderr, "\n");
  6995. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  6996. fprintf(stderr, "%7d: ", idx0);
  6997. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6998. if (idx0 >= 0 && idx0 < tensor->ne[0] && idx1 >= 0 && idx1 < tensor->ne[1] && i2 >= 0 && i2 < tensor->ne[2] && i3 >= 0 && i3 < tensor->ne[3]) {
  6999. float val;
  7000. if (tensor->type == GGML_TYPE_F32) {
  7001. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  7002. } else if (tensor->type == GGML_TYPE_F16) {
  7003. val = ggml_fp16_to_fp32(*(const ggml_fp16_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]));
  7004. } else if (tensor->type == GGML_TYPE_I32) {
  7005. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  7006. } else {
  7007. GGML_ABORT("fatal error");
  7008. }
  7009. fprintf(stderr, "% 7.2f ", val);
  7010. } else {
  7011. fprintf(stderr, " ");
  7012. }
  7013. }
  7014. fprintf(stderr, "\n");
  7015. }
  7016. }
  7017. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  7018. void * tensor_data = tensor->data;
  7019. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  7020. if (is_gpu) {
  7021. const size_t tensor_size = ggml_nbytes(tensor);
  7022. tensor_data = malloc(tensor_size);
  7023. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  7024. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  7025. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  7026. }
  7027. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  7028. std::cerr << "tensor=" << tensor << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << std::endl;
  7029. if (tensor->src[0] != nullptr) {
  7030. std::cerr << "tensor->src[0]=" << tensor->src[0] << " name=" << tensor->src[0]->name << " op=" << ggml_op_name(tensor->src[0]->op) << " type=" << ggml_type_name(tensor->src[0]->type) << " ne0=" << tensor->src[0]->ne[0] << " nb0=" << tensor->src[0]->nb[0] << " ne1=" << tensor->src[0]->ne[1] << " nb1=" << tensor->src[0]->nb[1] << " ne2=" << tensor->src[0]->ne[2] << " nb2=" << tensor->src[0]->nb[2] << " ne3=" << tensor->src[0]->ne[3] << " nb3=" << tensor->src[0]->nb[3] << std::endl;
  7031. }
  7032. if (tensor->src[1] != nullptr) {
  7033. std::cerr << "tensor->src[1]=" << tensor->src[1] << " name=" << tensor->src[1]->name << " op=" << ggml_op_name(tensor->src[1]->op) << " type=" << ggml_type_name(tensor->src[1]->type) << " ne0=" << tensor->src[1]->ne[0] << " nb0=" << tensor->src[1]->nb[0] << " ne1=" << tensor->src[1]->ne[1] << " nb1=" << tensor->src[1]->nb[1] << " ne2=" << tensor->src[1]->ne[2] << " nb2=" << tensor->src[1]->nb[2] << " ne3=" << tensor->src[1]->ne[3] << " nb3=" << tensor->src[1]->nb[3] << std::endl;
  7034. }
  7035. std::cerr << std::endl << "Result:" << std::endl;
  7036. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7037. std::cerr << std::endl;
  7038. std::vector<const ggml_tensor *> done;
  7039. ggml_vk_print_graph_origin(tensor, done);
  7040. if (is_gpu) {
  7041. free(tensor_data);
  7042. }
  7043. }
  7044. void * comp_result;
  7045. size_t comp_size;
  7046. size_t comp_nb[GGML_MAX_DIMS];
  7047. size_t check_counter = 0;
  7048. static void ggml_vk_check_results_0(ggml_tensor * tensor) {
  7049. if (tensor->op == GGML_OP_TRANSPOSE) {
  7050. return;
  7051. }
  7052. check_counter++;
  7053. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  7054. return;
  7055. }
  7056. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  7057. ggml_tensor * src0 = tensor->src[0];
  7058. ggml_tensor * src1 = tensor->src[1];
  7059. ggml_tensor * src2 = tensor->src[2];
  7060. ggml_tensor * src3 = tensor->src[3];
  7061. struct ggml_init_params iparams = {
  7062. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  7063. /*.mem_buffer =*/ NULL,
  7064. /*.no_alloc =*/ false,
  7065. };
  7066. struct ggml_context * ggml_ctx = ggml_init(iparams);
  7067. struct ggml_tensor * src0_clone = nullptr;
  7068. struct ggml_tensor * src1_clone = nullptr;
  7069. struct ggml_tensor * src2_clone = nullptr;
  7070. struct ggml_tensor * src3_clone = nullptr;
  7071. struct ggml_tensor * tensor_clone = nullptr;
  7072. size_t src0_size;
  7073. size_t src1_size;
  7074. size_t src2_size;
  7075. size_t src3_size;
  7076. void * src0_buffer = nullptr;
  7077. void * src1_buffer = nullptr;
  7078. void * src2_buffer = nullptr;
  7079. void * src3_buffer = nullptr;
  7080. if (src0 != nullptr) {
  7081. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  7082. src0_size = ggml_nbytes(src0);
  7083. src0_buffer = malloc(src0_size);
  7084. src0_clone->data = src0_buffer;
  7085. if (ggml_backend_buffer_is_host(src0->buffer)) {
  7086. memcpy(src0_clone->data, src0->data, src0_size);
  7087. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7088. } else if (ggml_backend_buffer_is_vk(src0->buffer)) {
  7089. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7090. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7091. uint64_t offset = vk_tensor_offset(src0) + src0->view_offs;
  7092. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  7093. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  7094. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  7095. const int idx = i3*src0->ne[2] + i2;
  7096. ggml_vk_buffer_read(buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  7097. }
  7098. }
  7099. src0_clone->nb[0] = src0->nb[0];
  7100. src0_clone->nb[1] = src0->nb[1];
  7101. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7102. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  7103. }
  7104. } else {
  7105. if (offset + src0_size >= buffer_gpu->size) {
  7106. src0_size = buffer_gpu->size - offset;
  7107. }
  7108. ggml_vk_buffer_read(buffer_gpu, offset, src0_clone->data, src0_size);
  7109. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7110. }
  7111. } else {
  7112. GGML_ABORT("fatal error");
  7113. }
  7114. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7115. ggml_vk_print_tensor(src0, "src0");
  7116. }
  7117. }
  7118. if (src1 != nullptr) {
  7119. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  7120. src1_size = ggml_nbytes(src1);
  7121. src1_buffer = malloc(src1_size);
  7122. src1_clone->data = src1_buffer;
  7123. if (ggml_backend_buffer_is_host(src1->buffer)) {
  7124. memcpy(src1_clone->data, src1->data, src1_size);
  7125. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7126. } else if (ggml_backend_buffer_is_vk(src1->buffer)) {
  7127. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  7128. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7129. uint64_t offset = vk_tensor_offset(src1) + src1->view_offs;
  7130. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  7131. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  7132. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  7133. const int idx = i3*src1->ne[2] + i2;
  7134. ggml_vk_buffer_read(buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  7135. }
  7136. }
  7137. src1_clone->nb[0] = src1->nb[0];
  7138. src1_clone->nb[1] = src1->nb[1];
  7139. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7140. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  7141. }
  7142. } else {
  7143. if (offset + src1_size >= buffer_gpu->size) {
  7144. src1_size = buffer_gpu->size - offset;
  7145. }
  7146. ggml_vk_buffer_read(buffer_gpu, offset, src1_clone->data, src1_size);
  7147. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7148. }
  7149. } else {
  7150. GGML_ABORT("fatal error");
  7151. }
  7152. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7153. ggml_vk_print_tensor(src1, "src1");
  7154. }
  7155. }
  7156. if (src2 != nullptr) {
  7157. src2_clone = ggml_dup_tensor(ggml_ctx, src2);
  7158. src2_size = ggml_nbytes(src2);
  7159. src2_buffer = malloc(src2_size);
  7160. src2_clone->data = src2_buffer;
  7161. if (ggml_backend_buffer_is_host(src2->buffer)) {
  7162. memcpy(src2_clone->data, src2->data, src2_size);
  7163. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7164. } else if (ggml_backend_buffer_is_vk(src2->buffer)) {
  7165. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src2->buffer->context;
  7166. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7167. uint64_t offset = vk_tensor_offset(src2) + src2->view_offs;
  7168. if (!ggml_is_contiguous(src2) && ggml_vk_dim01_contiguous(src2)) {
  7169. for (int i3 = 0; i3 < src2->ne[3]; i3++) {
  7170. for (int i2 = 0; i2 < src2->ne[2]; i2++) {
  7171. const int idx = i3*src2->ne[2] + i2;
  7172. ggml_vk_buffer_read(buffer_gpu, offset + idx * src2->nb[2], ((char *)src2_clone->data + idx * src2_clone->nb[2]), src2->ne[1] * src2->nb[1]);
  7173. }
  7174. }
  7175. src2_clone->nb[0] = src2->nb[0];
  7176. src2_clone->nb[1] = src2->nb[1];
  7177. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7178. src2_clone->nb[i] = src2_clone->nb[i - 1]*src2_clone->ne[i - 1];
  7179. }
  7180. } else {
  7181. if (offset + src2_size >= buffer_gpu->size) {
  7182. src2_size = buffer_gpu->size - offset;
  7183. }
  7184. ggml_vk_buffer_read(buffer_gpu, offset, src2_clone->data, src2_size);
  7185. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7186. }
  7187. } else {
  7188. GGML_ABORT("fatal error");
  7189. }
  7190. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7191. ggml_vk_print_tensor(src2, "src2");
  7192. }
  7193. }
  7194. if (src3 != nullptr) {
  7195. src3_clone = ggml_dup_tensor(ggml_ctx, src3);
  7196. src3_size = ggml_nbytes(src3);
  7197. src3_buffer = malloc(src3_size);
  7198. src3_clone->data = src3_buffer;
  7199. if (ggml_backend_buffer_is_host(src3->buffer)) {
  7200. memcpy(src3_clone->data, src3->data, src3_size);
  7201. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7202. } else if (ggml_backend_buffer_is_vk(src3->buffer)) {
  7203. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src3->buffer->context;
  7204. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7205. uint64_t offset = vk_tensor_offset(src3) + src3->view_offs;
  7206. if (!ggml_is_contiguous(src3) && ggml_vk_dim01_contiguous(src3)) {
  7207. for (int i3 = 0; i3 < src3->ne[3]; i3++) {
  7208. for (int i2 = 0; i2 < src3->ne[2]; i2++) {
  7209. const int idx = i3*src3->ne[2] + i2;
  7210. ggml_vk_buffer_read(buffer_gpu, offset + idx * src3->nb[2], ((char *)src3_clone->data + idx * src3_clone->nb[2]), src3->ne[1] * src3->nb[1]);
  7211. }
  7212. }
  7213. src3_clone->nb[0] = src3->nb[0];
  7214. src3_clone->nb[1] = src3->nb[1];
  7215. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7216. src3_clone->nb[i] = src3_clone->nb[i - 1]*src3_clone->ne[i - 1];
  7217. }
  7218. } else {
  7219. if (offset + src3_size >= buffer_gpu->size) {
  7220. src3_size = buffer_gpu->size - offset;
  7221. }
  7222. ggml_vk_buffer_read(buffer_gpu, offset, src3_clone->data, src3_size);
  7223. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7224. }
  7225. } else {
  7226. GGML_ABORT("fatal error");
  7227. }
  7228. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7229. ggml_vk_print_tensor(src3, "src3");
  7230. }
  7231. }
  7232. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  7233. const float *params = (const float *)tensor->op_params;
  7234. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, src3_clone, params[0], params[1], params[2]);
  7235. } else if (tensor->op == GGML_OP_MUL_MAT) {
  7236. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  7237. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  7238. tensor_clone = ggml_mul_mat_id(ggml_ctx, src0_clone, src1_clone, src2_clone);
  7239. } else if (tensor->op == GGML_OP_MUL) {
  7240. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  7241. } else if (tensor->op == GGML_OP_DIV) {
  7242. tensor_clone = ggml_div(ggml_ctx, src0_clone, src1_clone);
  7243. } else if (tensor->op == GGML_OP_CONCAT) {
  7244. tensor_clone = ggml_concat(ggml_ctx, src0_clone, src1_clone, *(int *)tensor->op_params);
  7245. } else if (tensor->op == GGML_OP_UPSCALE) {
  7246. tensor_clone = ggml_upscale_ext(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7247. } else if (tensor->op == GGML_OP_SCALE) {
  7248. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  7249. } else if (tensor->op == GGML_OP_SQR) {
  7250. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  7251. } else if (tensor->op == GGML_OP_SIN) {
  7252. tensor_clone = ggml_sin(ggml_ctx, src0_clone);
  7253. } else if (tensor->op == GGML_OP_COS) {
  7254. tensor_clone = ggml_cos(ggml_ctx, src0_clone);
  7255. } else if (tensor->op == GGML_OP_CLAMP) {
  7256. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  7257. } else if (tensor->op == GGML_OP_PAD) {
  7258. tensor_clone = ggml_pad(ggml_ctx, src0_clone, tensor->ne[0] - src0_clone->ne[0], tensor->ne[1] - src0_clone->ne[1], tensor->ne[2] - src0_clone->ne[2], tensor->ne[3] - src0_clone->ne[3]);
  7259. } else if (tensor->op == GGML_OP_REPEAT) {
  7260. tensor_clone = ggml_repeat(ggml_ctx, src0_clone, tensor);
  7261. } else if (tensor->op == GGML_OP_ADD) {
  7262. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  7263. } else if (tensor->op == GGML_OP_ACC) {
  7264. tensor_clone = ggml_acc(ggml_ctx, src0_clone, src1_clone, tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  7265. } else if (tensor->op == GGML_OP_NORM) {
  7266. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  7267. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  7268. tensor_clone = ggml_group_norm(ggml_ctx, src0_clone, *(int *)tensor->op_params, ((float *)tensor->op_params)[1]);
  7269. } else if (tensor->op == GGML_OP_RMS_NORM) {
  7270. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  7271. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  7272. if (src1 != nullptr) {
  7273. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  7274. } else {
  7275. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  7276. }
  7277. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  7278. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(int *)tensor->op_params);
  7279. } else if (tensor->op == GGML_OP_ROPE) {
  7280. const int n_dims = ((int32_t *) tensor->op_params)[1];
  7281. const int mode = ((int32_t *) tensor->op_params)[2];
  7282. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  7283. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  7284. const float freq_base = ((float *) tensor->op_params)[5];
  7285. const float freq_scale = ((float *) tensor->op_params)[6];
  7286. const float ext_factor = ((float *) tensor->op_params)[7];
  7287. const float attn_factor = ((float *) tensor->op_params)[8];
  7288. const float beta_fast = ((float *) tensor->op_params)[9];
  7289. const float beta_slow = ((float *) tensor->op_params)[10];
  7290. tensor_clone = ggml_rope_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  7291. } else if (tensor->op == GGML_OP_UNARY) {
  7292. switch (ggml_get_unary_op(tensor)) {
  7293. case GGML_UNARY_OP_SILU:
  7294. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  7295. break;
  7296. case GGML_UNARY_OP_GELU:
  7297. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  7298. break;
  7299. case GGML_UNARY_OP_GELU_QUICK:
  7300. tensor_clone = ggml_gelu_quick(ggml_ctx, src0_clone);
  7301. break;
  7302. case GGML_UNARY_OP_RELU:
  7303. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  7304. break;
  7305. case GGML_UNARY_OP_TANH:
  7306. tensor_clone = ggml_tanh(ggml_ctx, src0_clone);
  7307. break;
  7308. default:
  7309. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  7310. GGML_ABORT("fatal error");
  7311. }
  7312. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  7313. if (src1 == nullptr) {
  7314. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  7315. tensor_clone->type = tensor->type;
  7316. } else {
  7317. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  7318. }
  7319. } else if (tensor->op == GGML_OP_CONT) {
  7320. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7321. } else if (tensor->op == GGML_OP_RESHAPE) {
  7322. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7323. } else if (tensor->op == GGML_OP_VIEW) {
  7324. tensor_clone = ggml_view_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], tensor->nb[1], tensor->nb[2], tensor->nb[3], ((int32_t *) tensor->op_params)[0]);
  7325. } else if (tensor->op == GGML_OP_PERMUTE) {
  7326. int32_t * params = (int32_t *)tensor->op_params;
  7327. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  7328. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  7329. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  7330. } else if (tensor->op == GGML_OP_GET_ROWS) {
  7331. tensor_clone = ggml_get_rows(ggml_ctx, src0_clone, src1_clone);
  7332. } else if (tensor->op == GGML_OP_ARGSORT) {
  7333. tensor_clone = ggml_argsort(ggml_ctx, src0_clone, (ggml_sort_order) *(int *)tensor->op_params);
  7334. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  7335. tensor_clone = ggml_sum_rows(ggml_ctx, src0_clone);
  7336. } else if (tensor->op == GGML_OP_IM2COL) {
  7337. const int32_t s0 = tensor->op_params[0];
  7338. const int32_t s1 = tensor->op_params[1];
  7339. const int32_t p0 = tensor->op_params[2];
  7340. const int32_t p1 = tensor->op_params[3];
  7341. const int32_t d0 = tensor->op_params[4];
  7342. const int32_t d1 = tensor->op_params[5];
  7343. const bool is_2D = tensor->op_params[6] == 1;
  7344. tensor_clone = ggml_im2col(ggml_ctx, src0_clone, src1_clone, s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  7345. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  7346. const int32_t dim = tensor->op_params[0];
  7347. const int32_t max_period = tensor->op_params[1];
  7348. tensor_clone = ggml_timestep_embedding(ggml_ctx, src0_clone, dim, max_period);
  7349. } else if (tensor->op == GGML_OP_POOL_2D) {
  7350. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  7351. const int32_t k0 = tensor->op_params[1];
  7352. const int32_t k1 = tensor->op_params[2];
  7353. const int32_t s0 = tensor->op_params[3];
  7354. const int32_t s1 = tensor->op_params[4];
  7355. const int32_t p0 = tensor->op_params[5];
  7356. const int32_t p1 = tensor->op_params[6];
  7357. tensor_clone = ggml_pool_2d(ggml_ctx, src0_clone, op, k0, k1, s0, s1, p0, p1);
  7358. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  7359. const float * op_params = (const float *)tensor->op_params;
  7360. tensor_clone = ggml_leaky_relu(ggml_ctx, src0_clone, op_params[0], false);
  7361. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  7362. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, tensor->src[0], tensor->src[1], tensor->src[2], tensor->src[3],
  7363. tensor->src[4], tensor->src[5]);
  7364. }
  7365. else {
  7366. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  7367. GGML_ABORT("fatal error");
  7368. }
  7369. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  7370. ggml_build_forward_expand(cgraph, tensor_clone);
  7371. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  7372. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7373. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  7374. }
  7375. comp_size = ggml_nbytes(tensor_clone);
  7376. comp_result = malloc(comp_size);
  7377. memcpy(comp_result, tensor_clone->data, comp_size);
  7378. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7379. if (src0 != nullptr) {
  7380. free(src0_buffer);
  7381. }
  7382. if (src1 != nullptr) {
  7383. free(src1_buffer);
  7384. }
  7385. ggml_free(ggml_ctx);
  7386. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  7387. }
  7388. static void ggml_vk_check_results_1(ggml_tensor * tensor) {
  7389. if (tensor->op == GGML_OP_TRANSPOSE) {
  7390. return;
  7391. }
  7392. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  7393. return;
  7394. }
  7395. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  7396. ggml_tensor * src0 = tensor->src[0];
  7397. ggml_tensor * src1 = tensor->src[1];
  7398. ggml_tensor * src2 = tensor->src[2];
  7399. ggml_tensor * src3 = tensor->src[3];
  7400. void * tensor_data = tensor->data;
  7401. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7402. size_t tensor_size = ggml_nbytes(tensor);
  7403. tensor_data = malloc(tensor_size);
  7404. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  7405. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7406. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  7407. if (offset + tensor_size >= buffer_gpu->size) {
  7408. tensor_size = buffer_gpu->size - offset;
  7409. }
  7410. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  7411. }
  7412. float first_error_result = -1.0f;
  7413. float first_error_correct = -1.0f;
  7414. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  7415. double avg_err = 0.0;
  7416. size_t counter = 0;
  7417. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  7418. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  7419. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  7420. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  7421. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  7422. float correct = 0.0f;
  7423. float result = 0.0f;
  7424. if (buffer_size_fit) {
  7425. if (tensor->type == GGML_TYPE_F32) {
  7426. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7427. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7428. } else if (tensor->type == GGML_TYPE_F16) {
  7429. correct = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  7430. result = ggml_fp16_to_fp32(*(ggml_fp16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  7431. } else if (tensor->type == GGML_TYPE_I32) {
  7432. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7433. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7434. } else {
  7435. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  7436. }
  7437. } else {
  7438. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  7439. GGML_ABORT("fatal error");
  7440. }
  7441. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  7442. std::cerr << "ERROR: Invalid value in " << ggml_op_name(tensor->op) << " i3=" << i3 << " i2=" << i2 << " i1=" << i1 << " i0=" << i0 << " result=" << result << " correct=" << correct << " avg_err=" << (avg_err / counter) << std::endl;
  7443. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7444. if (src0 != nullptr) {
  7445. std::cerr << "src0=" << src0 << " src0->name=" << src0->name << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7446. }
  7447. if (src1 != nullptr) {
  7448. std::cerr << "src1=" << src1 << " src1->name=" << src1->name << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7449. }
  7450. if (src2 != nullptr) {
  7451. std::cerr << "src2=" << src2 << " src2->name=" << src2->name << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7452. }
  7453. if (src3 != nullptr) {
  7454. std::cerr << "src3=" << src3 << " src3->name=" << src3->name << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  7455. }
  7456. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  7457. std::cerr << std::endl << "Result:" << std::endl;
  7458. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  7459. std::cerr << std::endl << "Correct:" << std::endl;
  7460. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  7461. std::cerr << std::endl;
  7462. std::vector<const ggml_tensor *> done;
  7463. ggml_vk_print_graph_origin(tensor, done);
  7464. GGML_ABORT("fatal error");
  7465. }
  7466. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  7467. first_error[0] = i0;
  7468. first_error[1] = i1;
  7469. first_error[2] = i2;
  7470. first_error[3] = i3;
  7471. first_error_result = result;
  7472. first_error_correct = correct;
  7473. }
  7474. // Special case, value is infinite, avoid NaN result in avg_err
  7475. // NaN also appears in results, if both are nan error is 0
  7476. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  7477. avg_err += std::fabs(correct - result);
  7478. }
  7479. counter++;
  7480. }
  7481. }
  7482. }
  7483. }
  7484. avg_err /= counter;
  7485. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7486. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7487. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7488. if (src0 != nullptr) {
  7489. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7490. }
  7491. if (src1 != nullptr) {
  7492. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7493. }
  7494. if (src2 != nullptr) {
  7495. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7496. }
  7497. if (src3 != nullptr) {
  7498. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  7499. }
  7500. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  7501. std::cerr << std::endl << "Result:" << std::endl;
  7502. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7503. std::cerr << std::endl << "Correct:" << std::endl;
  7504. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  7505. std::cerr << std::endl;
  7506. std::vector<const ggml_tensor *> done;
  7507. ggml_vk_print_graph_origin(tensor, done);
  7508. }
  7509. if (avg_err > 0.05 || std::isnan(avg_err)) {
  7510. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7511. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7512. if (src0 != nullptr) {
  7513. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7514. }
  7515. if (src1 != nullptr) {
  7516. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7517. }
  7518. if (src2 != nullptr) {
  7519. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7520. }
  7521. if (src3 != nullptr) {
  7522. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  7523. }
  7524. std::cerr << "First error: result=" << first_error_result << " correct=" << first_error_correct << " i3=" << first_error[3] << " i2=" << first_error[2] << " i1=" << first_error[1] << " i0=" << first_error[0] << std::endl;
  7525. std::cerr << std::endl << "Result:" << std::endl;
  7526. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  7527. std::cerr << std::endl << "Correct:" << std::endl;
  7528. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  7529. std::cerr << std::endl;
  7530. std::vector<const ggml_tensor *> done;
  7531. ggml_vk_print_graph_origin(tensor, done);
  7532. GGML_ABORT("fatal error");
  7533. } else {
  7534. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  7535. }
  7536. free(comp_result);
  7537. comp_result = nullptr;
  7538. comp_size = 0;
  7539. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7540. free(tensor_data);
  7541. }
  7542. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  7543. }
  7544. #endif
  7545. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)